circuit-cellar2002-05.pdf

100
7 9 25274 75349 05 > CIRCUIT CELLAR ® www.circuitcellar.com THE MAGAZINE FOR COMPUTER APPLICATIONS $4.95 U.S. ($5.95 Canada) SIGNAL PROCESSING How To Deal With EMC Power Line Modems and Home Control One-Bit Wireless I/O Port Handling SMDs By Hand #142 May 2002

Upload: tusaigon

Post on 26-Dec-2015

35 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: circuit-cellar2002-05.pdf

7 925274 75349

05>

®

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

How To Deal With EMC

Power Line Modems and Home Control

One-Bit Wireless I/O Port

Handling SMDs By Hand

Page 4: circuit-cellar2002-05.pdf

Digital Oscilloscopes

• 2 Channel Digital Oscilloscope• 100 MSa/s max single shot rate• 32K samples per channel• Advanced Triggering• Only 9 oz and 6.3” x 3.75” x 1.25”• Small, Lightweight, and Portable• Parallel Port interface to PC• Advanced Math options• FFT Spectrum Analyzer options

DSO-2102S $525DSO-2102M $650Each includes Oscilloscope,Probes, Interface Cable, PowerAdapter, and software forWin95/98, WinNT, Win2000and DOS.

• 40 to 160 channels• up to 500 MSa/s• Variable Threshold• 8 External Clocks• 16 Level Triggering• up to 512K samples/ch• Optional Parallel Interface• Optional 100 MSa/s Pattern Generator

LA4240-32K (200MHz, 40CH) $1350LA4280-32K (200MHz, 80CH) $2000LA4540-128K (500MHz, 40CH) $1900LA4580-128K (500MHz, 80CH) $2800LA45160-128K (500MHz, 160CH) $7000

www.LinkIns4.comLink Instruments • 369 Passaic Ave • Suite 100 • Fairfield, NJ 07004 • (973) 808-8990 • Fax (973) 808-8786

Logic Analyzers

• 24 Channel Logic Analyzer• 100MSa/S max sample rate• Variable Threshold Voltage• Large 128k Buffer• Small, Lightweight and Portable• Only 4 oz and 4.75” x 2.75” x 1”• Parallel Port Interface to PC• Trigger Out• Windows 95/98 Software

LA2124-128K (100MSa/s, 24CH)Clips, Wires, Interface Cable, ACAdapter and Software $800

All prices include Pods and Software

Page 7: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 5

Power Line Modems Meet Home ControlBrian Millier

Tiny Planet—A One-Bit Wireless I/O PortClaudio Lanconelli & Alberto Ricci Bitti

Working with EMCGeorge Novacek

Hand-Soldering Fine-Pitch QFP DevicesJohn Taylor

RoCK SpecificationsPart 2: The CircuitryJoseph Jones & Ben Wirz

Design Your Own MicroprocessorJim Turley

I ROBOTICS CORNERBehind the ScenesPart 1: Controlling an Animatronics SystemDaniel Ramirez

I APPLIED PCsTaking a Swim with Atmel’s STK500Fred Eady

I FROM THE BENCHYou’re Not AloneDealing with IsolationJeff Bachiochi

I SILICON UPDATE I-Way the Hard(ware) WayTom Cantrell

COLUMNS

ISSUE

Task ManagerJennifer HuberGetting the Right Signal

New Product Newsedited by John Gorsky

Test Your EQ

Advertiser’s IndexJune Preview

Priority InterruptSteve CiarciaThe Insanity of Sucess

6

8

11

94

96

142

34

56

70

76

FEATURES 12

20

28

50

46

62

Page 8: circuit-cellar2002-05.pdf

raditionally, we have used signals to communi-cate a plethora of information, because often, a sig-

nal is more straightforward than written or oral communi-cation. Without the benefit of proximity, we can still convey

messages. Additionally, many signals are universally understood and cross theboundaries of language and culture, such as waving a white flag.

Signals are used every day. Beams of light shed from lighthouses alongcoastlines communicate locations of harbors and obstacles to ensure the safe-ty of seamen and their ships. Since the mid-nineteenth century, people acrossthe world have used Morse code for radiotelegraphy. We also have sign lan-guage and braille. With a set of hand gestures and series of bumps, both deafand blind people can communicate as well as people with sight and hearing.

Just as in other aspects of life, signals are important, if not crucial, in engi-neering. A multitude of various projects involve signal processing. This month,you get to read about some projects that I’m sure you’ll enjoy. For instance, onpage 12, you’ll find Brian Millier’s take on home control. As Brian explains,Canadian winters can be brutal, so controlling the air temperature inside hishome is essential to keeping his family comfortable. His creative plan involvedadding indoor and outdoor humidity sensors using the least amount of wirehassle. Now, his home control unit is receiving all of the right signals andworks perfectly. Everyone else suffering in a cold climate can benefit from thesuccess of Brian’s design, as well. Note, too, that this home control schemecan trap precious air-conditioned air to help you survive August in hot climates.

For a peek behind the curtain, you’ll also want to turn to page 34 to readabout controlling an animatronics system. Daniel Ramirez explores the worldof special effects and brings us a step-by-step guide to building a DIY anima-tion system. Inspired by some of Hollywood’s legendary pioneers includingWalt Disney, Daniel designed a unique animation system that resides on aremote-controlled, servo-propelled robot.

Daniel’s article serves the dual purposes of providing another example ofhow critical signal processing is to engineering as well as marking the adventof Circuit Cellar’s new Robotics Corner. The Robotics Corner is a new featureto our regular lineup. The idea came about as a result of the numerous sub-missions and positive feedback from all of you regarding the annual Roboticstheme issue. Every year, the task of picking which articles to publish in ourRobotics issue increases in difficulty because we’re inundated with article pro-posals about intriguing projects. Now, you’ll have an extra dose of the roboticscontent you love each month. As always, you are our source for fresh content,so head over to the Author’s Guide at www.circuitcellar.com/authors and pre-pare to share your inventive project with the rest of us.

I want to say a special thanks to The New England Assistive TechnologyMarketplace (NEAT), which loaned us the children’s braille book about snakespresented on the cover. For more information about assistive products, pleasevisit the NEAT web site at www.neatmarketplace.org.

6 Issue 142 May 2002 www.circuitcellar.comCIRCUIT CELLAR®

EDITORIAL DIRECTOR/PUBLISHERSteve Ciarcia

WEB GROUP PUBLISHERJack Shandle

MANAGING EDITORJennifer Huber

SENIOR EDITORRob Walker

TECHNICAL EDITORJennifer Belmonte

WEST COAST EDITORTom Cantrell

CONTRIBUTING EDITORSIngo CyliaxFred Eady George MartinGeorge Novacek

NEW PRODUCTS EDITORJohn Gorsky

PROJECT EDITORSSteve Bedford David Tweed

ADVERTISINGADVERTISING SALES MANAGER

Kevin Dows Fax: (860) 871-0411(860) 872-3064 E-mail: [email protected] phone: (860) 930-4326

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

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

CONTACTING CIRCUIT CELLARSUBSCRIPTIONS:

INFORMATION: www.circuitcellar.com or [email protected] Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, [email protected]: [email protected]

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

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

CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub-lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid atVernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico$31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico$55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal moneyorder, or check drawn on U.S. bank. Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH03755-5650 or call (800) 269-6301. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

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

Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for theconsequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon orfrom plans, descriptions, or information published by Circuit Cellar®.

The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right tobuild things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right toconstruct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.The reader assumes any risk of infringement liability for constructing or operating such devices.

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

CHIEF FINANCIAL OFFICERJeannette Ciarcia

ACCOUNTANTHoward Geffner

CUSTOMER SERVICEElaine Johnston

ART DIRECTORKC Prescott

GRAPHIC DESIGNERSCindy KingMary Turek

STAFF ENGINEERS Jeff Bachiochi

John Gorsky

QUIZ COORDINATORDavid Tweed

EDITORIAL ADVISORY BOARDIngo Cyliax

Norman Jackson David Prutchi

TASK MANAGER

Cover photograph Ron Meadows—Meadows MarketingPRINTED IN THE UNITED STATES

tGetting the Right Signal

[email protected]

Page 10: circuit-cellar2002-05.pdf

NEWS

8 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

NEW PRODUCTEdited by John Gorsky

SINGLE BOARD COMPUTERThe TC51 SBC is an industrial controller assembly that

is easy to program and connect to external signals. Theboard can be programmed as a standalone controller usingits on-board Tiny Machine Basic programming language, orit can be used as an RS-232 serial data acquisition board.

The TC51 is based on the Atmel AT89C4051 microcon-troller chip with EEPROM program memory, and can bereprogrammed using any number of software developmenttools and device programmers available for Atmel micro-

controllers. There are two RS-232 ports withtrue RS-232 drivers and DE-9

connectors for communica-tions. Screw terminal connec-

tors are used for all of thedigital, analog, and relay

connections, which includefour 10 A form C relays, four logic-

level signals usable as inputs or outputs,and two 12-bit A/D inputs.

The board contains LCD support circuitry that interfacesto a 16-pin 0.1″ header connector matching most LCDmodule connections. It also features an on-board contrastpot. LCD commands are included in the Tiny MachineBasic language. Its on-board power supply has a wide inputrange and includes 5- and 12-V outputs for use by externaldevices.

The TC51 package includes a serial port cable for con-nection to a PC-compatible computer, a wall block powersupply, host computer software, programming examples,and hardware and software reference manuals.

The TC51 costs $129 in single quantities.

low-power and battery-operated applications.The TRS1722, TRS1755 and TRS1766 reflective color

sensors combine high-output LEDs with the TAOS high-sensitivity color sensors. These color sensors are basedon the popular TAOS TSL257 light-to-voltage converterplatform. With the TRS1722, TRS1755 and TRS1766,users can achieve 8 bits of resolution in their designs.

Each of the three TAOS color sensors has a suggestedresale price of $1.36 in 1000-piece quantities.

REFLECTIVE COLOR SENSORSThe TRS1722, TRS1755, and TRS1766 are three new

reflective color sensors that combine a color LED dieand a light-to-voltage converter with a correspondingcolor filter in a surface mount package. Each sensor isdesigned to emit and detect one of three primary colors:red, blue or green. The TRS1722 emits red, the TRS1755emits green and the TRS1766emits blue light. The output ofeach device is a voltage that isdirectly proportional to thereflected color light.

Because the sensors emit andrespond to a single color, they providesuperior discrimination (signal to noise ratio). Inaddition, with the LED drive current being as low as250 µA (TRS1766, blue), the sensors are well suited for

Texas Advanced Optoelectronic Solutions(972) 673-0759

www.taosinc.com

SOLID STATE RELAY MODULEThe WTSSR-M is a stackable RS-232 data module

with five optically isolated solid-state relays. Therelays can be wired directly in place of or parallel toexisting push buttons and toggle switches to enablesoftware control of the switch operation. Relay out-puts also can be used to switch external solenoids,actuators, and high-current relays.

A relay can be instructed to open or close andremain at that new state or switch back to the previ-ous state after a user-defined delay period. Each relaycan be controlled individually or as a group. Thebuilt-in event sequencer allows you to load a seriesof relay on/off patterns and time delays that willexecute sequentially.

Modules in this series can be plugged end-to-endon a common RS-232 cable attached to the serialport of a PC, laptop, or other host. An on-board 32-position DIP switch sets the address of each module,which is used for identifying data transmitted fromit as well as directing data transmitted by the host.

The data bus supports full anti-collision disciplinebetween connected modules and will allow up to 32modules to share the same communications line.Power is supplied by an external 8- to 30-VDCsource (not included) to the first module in the chainand is carried down the RS-232 cable to successivemodules.

The WTSSR-Msells for $69.

IndustroLogic(314) 707-8818www.industrologic.com

WeederTechnologies850-863-5723www.weedtech.com

Page 11: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 9

NEWSNEW PRODUCTDIGITAL TEMPERATURE SENSOR

The DS1631 digital thermometer and thermostat is asmall 0.5°C accurate digital temperature sensor. As elec-tronics decrease in size, PC board real estate has becomeincreasingly valuable. Meantime, the need for precisethermal management has reached critical proportions.

The microSOP footprint of the DS1631 is half the sizeof its competitor. Its accuracy provides the tight thermalcontrol needed for maximum circuit performance. TheDS1631 provides 9-, 10-, 11-, or 12-bit digital tempera-ture readings over a –55°C to 125°C range, with 0.5°Caccuracy over a 0°C to 70° C range. It has thermostatfunctionality with nonvolatile (EEPROM) user-definedtrip points that allow you to customize the thresholdtemperature and output hysteresis. Communicationwith the DS1631 is achieved through a standard two-wire serial interface.

Prices start at $1.77 for quantitiesof 1000.

386 ENGINEThe 386 Engine is a high-performance, credit card-

sized module derived from a range of sophisticated com-munication equipment that has traditionally been usedin large-scale banking and gaming networks.

The 386 Engine consists of an Intel386EX running at 25 MHz with com-pact flash memory, 10BaseTEthernet, USB, two RS-232ports, a real time clock, andgeneral-purpose I/Os.

The processor bus is con-nected to external connectorsso other chips can be directly con-trolled by the processor. The unit isdesigned for minimum power consumption.

Both Linux and DOS are supplied as standard featureswith the product and there is a full suite of communica-tions protocols written using the EUCA protocol stacks,where available protocols include SNA, HDLC, X.25,and TCP/IP. The 386 Engine costs $199.

Sumbox(952) 201-6507www.sumbox.com

Dallas Semiconductor(800) 998-8800www.maxim-ic.com

Page 12: circuit-cellar2002-05.pdf

10 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

NEWSNEW PRODUCTG CODE CONTROLLER FOR WINDOWS

The G Code Controller software for Windowscombines a graphical part program development,animation, and verification environment into apowerful PC-based machine controller. The systemcan control up to five axes of motion, three dis-played in a scalable, rotatable image as well as rapidfront, end, and side views. It also offers tool lengthand radius offset compensation, with look-ahead foroptimizing around corners and through verticalmotion.

The G Code Controller incorporates cannedcycles, fixture offsets, multiple part programs perjob, and unlimited subroutine nesting. Intuitivemenus make setting up, saving, and retrieving jobsquick and convenient. Additionally, user-defined M,T, and S codes with advanced digital output, switchinput, and stage manipulation are available. Thedevice uses the 32-bit Indexer LPT/XQ driver forexceptionally smooth N-block look-ahead contour-ing in real time from IEE-1284 standard parallelports.

The G Code Controller costs $375 and the IndexerLPT/XQ costs $349.

Ability Systems Corp.(215) 657-4338www.abilitysystems.com

Page 13: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 11

CIRCUIT CELLAR Test YYour EEQ

Problem 3—Would the following code compilesuccessfully? What is its output?

#include <stdio.h>

main () printf ("%c",

7["Circuitcellar"]);

Contributed by Naveen PN

Problem 4—A crystal can be modeled as aseries-resonant LCR circuit. What are typical L,C, and R values, in terms of orders of magnitude?

Contributed by Dave Tweed

Problem 1—Design a simple circuit based oncombinational logic that generates pulses at twicethe frequency of an input signal.

Contributed by Naveen PN

Problem 2—What does the following code output?

#include <stdio.h>

void main (void)

unsigned int a = 6; int b = -20; (a + b > 6) ? puts (">6") : puts

("<=6");

Contributed by Naveen PN

What’s your EQ?—The answers and 4 additionalquestions and answers are posted at

www.circuitcellar.comYou may contact the quizmasters at

[email protected]

AD422 (Requires 9VDC) $79.00AD422-1 for 110VAC 89.00AD422L signal powered 84.00

ADA485 (requires 9VDC) $79.00ADA485-1 for 110VAC 89.00ADA485L signal powered 84.00

CMC’s low cost converters adapt anyRS232 port for RS422 or RS485operation. These converters provide yourRS232 device with all the advantages ofRS422 or RS485 including reliable highspeed operation (up to 200 kbaud) anddata transmission distances up to 5000feet. Two AD422s can be used to extendany RS232 link up to 5000 feet.Completely transparent to the system;no software changes of any type arenecessary.

RS232/RS422/RS485 Converters

• Converts an RS232 port foruse with RS422 or RS485devices

• Supports up to 40 RS485 orRS422 multidrop devices

• Adds multidrop capability toRS232 devices

• Automatically determinesdata direction.

RS232 TO RS4854 wire

• Makes your RS232 port anRS485 port

• Supports up to 40 RS485devices

• Automatically determinesdata direction.

• Signal powered versionavailable

RS232 TO RS4852 wire

ADA425 (requires 9VDC) $89.00ADA425-1 for 110VAC 99.00

Mention this ad when you order and deduct 5%Use Visa, Mastercard or company purchase order

WWW.2CMC.COM Fax:(203)775-4595

codeCC83

PO BOX 186, Brookfield,CT 06804 (203)740-9890Connecticut microComputer, Inc.

• Converts bi-directionallybetween RS232 and RS422

• Use as a short haul modem• Plug in and go. No software

changes required

RS232 TO RS422

Page 14: circuit-cellar2002-05.pdf

12 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

dozen years agowhen I built my

home, energy conser-vation was a big consid-

eration in home design. In Canada, theR-2000 building certification programaddressed this issue by defining mini-mum standards for insulation, sealingto prevent air leaks, and many otherissues involving energy conservation.

At the time, it was known that youcouldn’t make a house airtight forenergy conservation purposes withoutintroducing some rather nasty healthand comfort issues. To address theseconcerns, air exchangers were intro-duced. Obviously, any device thatexchanges the air in a home on a regu-lar basis will suck out a lot of heatedair in the winter. Therefore, airexchanger designs soon improved andbecame known as heat recovery venti-lators (HRVs). The new designsincluded a heat exchanger to recoversome of the heat that would other-wise be pumped outside and lost.These HRVs are 60–80% efficient atbest, so there’s still a significantamount of heat lost in operation. Ilive in a cooler climate, but I suspectthat in areas with hot summers, theloss of air-conditioned air during thesummer is of equal concern.

Although the technology in thisarea has undoubtedly progressed, theHRV unit initially installed in ourhouse had the most rudimentary con-trol system: an inexpensive humidis-tat (mounted inside the unit) thatsampled the air passing through theunit. The system had provisions for anexternal humidistat that could bemounted in the actual living area ofthe home, but the contractors didn’tprovide this optional humidistat.During the building of the house, Ijust had too many other things on mymind to think of it.

The only control scheme the unitcame with turned the unit on if thehumidity inside the house became toohigh. Actually, it sensed the humidityin the basement where the unit waslocated, which was not particularlyrepresentative of the house itself.

Humidity is a legitimate concern, butit is only one of many. For instance, aminimum number of total changes ofinterior air per day are needed for healthand comfort reasons. There’s also nopoint in running the unit to reducehumidity indoors, if the humidity out-doors is as high, or higher thanindoors. There are times of the daywhen the outdoor temperature is morelikely to be moderate and operation atthis time would be more efficient.Last but not least, I don’t like the unitto come on at 3 a.m. and blow cool airon me while I’m trying to sleep!

What I sought to design was a con-troller that considers all of the aboveconcerns. Because the house construc-tion is complete (including a finishedbasement), running additional controlwires would not be an easy task. Ibegan searching for a method thatwould not involve running a lot ofcontrol wires around the house.

I decided that I would want temper-ature and humidity sensors bothinside and outside of the house. Theindoor sensors would be part of themaster control module that would belocated in the main living area. Idecided that it would be easy to wirethe outdoor sensors directly to theslave controller mounted next to theHRV unit in the basement using asmall hole in the outside wall of thehouse where other wires already trav-

Power Line ModemsMeet Home Control

aEnergy conservation isan important consider-ation when building ahouse. But, a poorlydesigned control sys-tem prevented Brian’sheat recovery ventila-tors from being aseffective as possible.So, he tried some newpower line modems toget the sensing unitsto talk to each other.

Brian Millier

FEATUREARTICLE

Page 15: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 13

If the inside temperature isgreater than the temperatureset point and the outside tem-perature is less than theinside temperature, then turnon the HRV.

And now for the last rule.Regardless of humidity, if theoutside temperature is morethan 10° greater than indoors,turn off the HRV.

In practice, there will bemany times when inside humidity (ortemperature) conditions can’t beimproved by running the HRV becauseoutside conditions are even worse.This controller won’t overcome this,but at least it won’t waste energy byneedlessly running the HRV.

MEASURING HUMIDITYOne of my previous projects

required a low-cost humidity sensor.A search on the ’Net produced a refer-ence to an inexpensive relative humid-ity sensor ($15 in unit quantities)made by Ohmic Instruments. I endedup using the Ohmic sensor for boththat project and this one.

The SC-600 module contains both ahumidity sensor and the associatedelectronics to condition the sensor sig-nal into a useful range. The humiditysensor must be driven by an AC exci-tation source, which in this case is a440 Hz, 150-mV signal provided onthe module. The actual sensorexhibits an impedance that varies inan inverse logarithmic relationship tothe relative humidity. The modulecontains an on-board chip to convertthis relationship into a linear func-tion. As you can see in Figure 1, the20% to 90% RH range of the sensor islinearly converted into a voltagebetween 1.25 V and 3 V. The specifica-tion sheet shows a set point accuracyof ±2% and the units that I obtainedmeet this specification.

Relative humidity sensors are nor-mally extremely sensitive to tempera-ture, but this module is temperature-compensated. The outdoor sensor willget rained on, so the fact that the SC-600 sensors recover from condensationwas important. The operating temper-ature is –4°F to 140°F. Although theoutdoor temperature would go lower

eled. Communication betweenthe master and slave moduleswould be accomplished usingpower line modems, which I’lldescribed in detail later on.

CONTROL ALGORITHMSDepending on the climate

where you live, the optimumoperation of an HRV could varysignificantly from what I decid-ed was best for my home. Letme briefly describe our climate andthe control algorithm that I settled on.Because conditions change with theseasons, I implemented a differentalgorithm for each.

Our winters are moderate, but it’scold enough that all doors and win-dows must be kept closed. To keep theair fresh and healthy, the HRV mustrun at least a minimum number ofhours to provide the necessary airexchange. The best results occur whenthis doesn’t happen in one long cycle,but instead is broken into severalintervals throughout the day.

The new control program allows meto specify any number of intervals dur-ing which the HRV will run, regardlessof any other conditions. To maximizeefficiency, it makes sense to place someof these running cycles in the after-noon, when the outside temperature isgenerally at its highest. The controlleralso allows me to specify any numberof favored time periods. These are thetimes in which the controller will usethe readings from its indoor/outdoorsensors to decide whether or not to run.

Basically the control algorithm worksas follows. In the winter, it’s importantthat the inside humidity does not gettoo high because the windows maysuffer from condensation and, if seriousenough, wood rot may occur. So, thecontroller checks to see if the insidehumidity is higher than the user-spec-ified setting. If it is, then you mustconsider whether or not pumping inair from outside will help the situation.

At first I considered comparinginside and outside relative humidity(RH) values directly to make the judg-ment. This won’t work because an RHreading takes into account the factthat cold air can’t hold as much mois-ture as warmer air. Because we would

be heating the cold outside air when itwas pumped in, it would actuallyexhibit a much lower relative humidi-ty after it got inside and was heated.

The solution is to convert the RHreadings into precipitable water read-ings, which are temperature-independ-ent, and compare those values. If theoutside air is drier than inside air, theHRV should be turned on. To saveheat, I decided to prevent the HRVfrom running if the outside tempera-ture is more than 45°F below theinside temperature. Of course, this isa subjective decision that might notwork in colder climates.

Note that I don’t address what hap-pens when the inside humidity is toolow. This does occur, but generally theoutside humidity is also low in winter,so turning on the HRV will not help.

In the summer, the rules are differ-ent. Our summers are moderate intemperature and not extremely humid,with temperatures generally coolingdown each evening. I can still pro-gram run cycles to ensure a minimumnumber of air changes per day, but inthe summer windows are often leftopen, making this issue less impor-tant. However, I can program the unitto run for a period in the late eveningin an attempt to cool down the house.

During the user-defined favoredperiods for run cycles, the controllerreads its sensors like during the winter.In the summer, however, different rulesapply. Let’s go through these rules.

If the inside humidity is greater thanthe humidity set point and the out-side humidity is less than the insidehumidity, then turn on the HRV.

If the inside humidity is less thanthe humidity set point and the outsidehumidity is greater than the insidehumidity, then turn on the HRV.

SC-600 Humidity sensor response3.5

3

2.5

2

1.5

1

0.5

020 40 60 80 1000

% RH

Vo

lta

ge

ou

t

Figure 1—The SC-600 exhibits a linear response between 20% and 90% RH.

Page 16: circuit-cellar2002-05.pdf

The Plinius module is an FSK-mod-ulated transceiver capable of sendingdata through power lines at rates up to2400 bps. As shipped, these units usea 132.45-kHz carrier frequency, whichfalls within the CENELEC band usedin Europe. Although the datasheetindicates that the carrier frequency isprogrammable via the SPI connectionson the module, I was told that thenecessary information for that taskisn’t available to the end user.

Plinius operates in Half-Duplexmode, which means it cannot trans-mit and receive simultaneously. Itsdirection is defined by the host micro-controller through the REQUEST TOSEND (RTS) pin. A CARRIERDETECT signal is also provided bythe module, which indicates the pres-ence of a Plinius signal on the powerline. (Note that both the RTS andCARRIER DETECT signals are actual-ly negative logic signals; their namesin the datasheet do not correctlyreflect this fact.)

The Plinius modules come in twoflavors: an industrial version and ahome version. As far as I can tell, theonly difference between the two isthat the industrial version uses a 24-Vbooster power supply and puts outmore power than the 12-V-poweredhome version. Both models alsorequire a regulated 5-V power supplycapable of supplying 25 mA. I used thehome version, which measures about40 mm × 23 mm × 13 mm. Photo 2 isa close-up shot of the module.

An 18-pin dual 0.1″ header is allthat’s needed to connect all of the sig-nals, and the power line connectionsare placed as far away from the latteras possible, which makes a safe PCBlayout much easier. The units Ireceived are meant to be connected to240-V lines, but also work fine on the120-V lines found in North America.

Apart from its central communica-tion function, there are several usefulfeatures incorporated into this module.A power-on reset generator with aprogrammable threshold is providedand both 11.0592- and 5.5296-MHzclock signals are available. Unfor-tunately, the real-time clock neededin my project would not work usingeither of these frequencies. I was,

14 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

than –4°F on occasion, under theseconditions the RH is usually low andthe temperature is a more importantfactor. The module itself measures35 mm × 20 mm × 15 mm and is athree-wire device: 5 V, signal, andground. Photo 1 is a split view show-ing both the sensor and the electronicsside of this module.

MEASURING TEMPERATUREI was initially tempted to try some-

thing different for the temperaturesensors. I use precision linear thermis-tors for sensitive temperature meas-urements at work as well as thermo-couples for wide range measurements.I had some samples of Dallas one-wirethermometers as well as DS1620 SPIthermostat chips, and my BASCOM-AVR compiler even has built-in sup-port for both of these protocols.

However, because the humidity sen-sors produced a DC voltage output,and the ’8535 microcontroller con-tained an eight-channel 10-bit analog-to-digital converter, it made moresense to use temperature sensors thatalso produced a voltage output. I chosethe National Semiconductor LM34DZin a TO-92 package.

Unlike many other solid-state sen-sors whose signal output is referencedto absolute zero Kelvin, this unit pro-duces 10 mV/degrees Fahrenheit overthe 32°F to 212°F range. For the out-door sensor, the LM34CZ is a better

choice because its temperature rangeextends down to –40°F and it willmeasure down to 5°F without a bipo-lar ADC or extra circuitry, which ismore expensive and probably not nec-essary in my climate.

The Plinius power line modem,described in detail later, contains aninternal 2.50-V reference, so I usedthat for the ADC’s reference voltage.Although this was not an ideal volt-age, it was a good compromise forboth the humidity and temperaturesensors, and it provided enough reso-lution for my purposes.

The LM34DZ’s accuracy is rated atonly ±3°F. The units I’ve used are cer-tainly no more accurate than this, so Iincluded a calibration constant in myprogram to correct this.

PLINIUS TO THE RESCUEFor this project, I had originally

intended to use some low-cost wire-less modules to interconnect the vari-ous sensors and the main controller.Around this time, however, I receivedan e-mail from a long-time CircuitCellar reader, Vincenzo Izzo fromItaly. He had read my recent article“A Wireless Remote Control MP3Jukebox” (Circuit Cellar 134) and as itturns out, he works for Telecontrolli(manufacturer of the wireless modulesI used in that project).

He sent me some datasheets on thePlinius bidirectional power line

modems, which he thought Imight find useful. The mod-ules are manufactured byTelecontrolli using an ASICdesigned by Siemens Meteringin Italy. After reading thedatasheets, I agreed with himthat these modems would be agood fit for my current project.The project’s main controllerwould be near a power outleton the main floor of the house,and the slave unit would bemounted next to the HRV inthe basement, also near apower outlet. A few dayslater, a parcel containing sev-eral Plinius modules as well asa nice assortment of RF andPIR detector modules landedon my doorstep.

Each byte in the packet is described as follows:SYNC Sync byte (54H) is predefined by HTHHDB2 Header definition byte 2 has a value of 50H, which defines: 1-byte source and destination addresses No protocol specific flag bytes No ACK/NAK packet requested in return

HDB1 Header definition byte 1 has a value of 32H, which defines: 8-bit CRC error detection 2 bytes of data DAB Destination address byte = 1 for the master = 2 for the slave

SAB Source address byte = 1 for the master = 2 for the slave

DATA1 Runflag (from master to slave) Outside temperature (from slave to master)

DATA2 Unused (from master to slave) Outside humidity (from slave to master)

CRC 1-byte CRC (error detection)

SY HDB HDB DAB SAB DAT DAT CRNC 2 1 A1 A2 C

Figure 2—For my project, I used this form of the SNAP packet.

Page 17: circuit-cellar2002-05.pdf

www.circuitcellar.com/PSoC2002

• The fastest growingMCU architecture

• The highest levelof integration

• The next new thingin Embedded

Get paid to learn about PSoC MCU

For complete rules and entry form

Win a share of

Brought to you by:

The Cypress logo mark is a registered trademark of Cypress Semiconductor and Cypress MicroSystems, PSoC, and Programmable System-on-Chip are trademarks of Cypress Microsystems Inc. The CircuitCellar name is a registered trademark of Circuit Cellar Inc.

$15,000 in Cash Prizes!\64

\64

Take your career to the next level.

Page 18: circuit-cellar2002-05.pdf

16 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

however, able to use the last remain-ing feature, the 2.5-V reference source,for the ’8535 microcontroller’s inter-nal ADC reference.

The Plinius modules contain aninput pin labeled ZCROS, whichstands for zero crossing. This signalis not required for normal operation,but the Plinius ASIC can be repro-grammed through its SPI port to usethis signal to synchronize the startof data transmission with a zerocrossing line.

I can’t be definitive about the rangeof these modules. Power line modemsare not like wireless links, the rangeof which is generally quoted as a max-imum distance under ideal, line-of-sight conditions. The range of a powerline modem is determined more bythe type of loads connected to thesame branch of the power line. Theseloads may inject RF noise onto thepower line itself, which interfereswith the modem’s carrier signal.During tests in my house in which Isent a constant small packet of knowndata once per second, I experiencedonly a few errors over several hours. Iinduced a few errors by starting upany of the large power tools in myworkshop, but that was limited to theactual turn-on transient and did notpersist while the tool was left run-ning. In my home, there would not bemore than a 30-m distance betweenany two receptacles and Pliniusmodems work fine in that setting.

However, I must emphasize that inNorth America, domestic power isprovided from the distribution sys-

tem via a center-tapped 240-V trans-former. This means that there aretwo out-of-phase 120-V distributionlines (L1 and L2) provided that sharea common neutral.

In any home, some of the recepta-cles will be tapped off of one of theselines, and the rest will come from theother. The RF signal from Pliniusmodules (as well as X10 modules andsuch) will not easily cross over fromL1 to L2. We have an electric heatingsystem, the heating elements of whichconnect directly across L1 and L2.The Plinius signal can sneak from L1to L2 through these heater loads, butthis is more of an exception than therule. I made sure that both my masterand slave modules were fed fromreceptacles that shared the samepower phase. This arrangementbecame somewhat of a nuisance asmost of the receptacles in the housewere on one phase, except the recep-tacle for the HRV, which happened tobe on the other.

Alternately, you can fit a signal cou-pler in your power entrance box to cou-ple the RF signal from one phase to theother. These devices are commonlyavailable for X10 systems. One exam-ple would be the passive CP000 avail-able from HomeAutomationNet.comfor about $30. I haven’t tried one ofthese devices, but the fact that X10uses a 100-kHz carrier should allow itto work well with Plinius modemsoperating just a bit higher in frequen-cy at 132.45 kHz.

I must mention some problems thatI ran into while incorporating thesemodems into my design. To startwith, it’s important to monitor thecarrier detect line before actuallyaccepting characters coming in fromthe Plinius modem’s received dataoutput because the modem will pro-duce a constant stream of extraneouscharacters whenever there is no validsignal coming in from another trans-mitting Plinius modem. If you’re con-necting a Plinius modem to a micro-controller, your best bet is to operateits internal UART in a polled modeand use the CARRIER DETECT signalas an interrupt source. That way,when the CARRIER DETECT signalis active, the associated interrupt serv-

ice routine can clear the UART’sreceiver flag and data register, andstart the polling process.

If you intend to connect a Pliniusmodem directly to a PC’s COM port,then you’ll want to use communica-tion driver routines that enable theUART’s receiver only when the carrierdetect handshake line is true. If youdon’t, the PC’s incoming data bufferwill be constantly filled with theseextraneous characters when the actualdata is not being transmitted. I foundthat the sheer number and random-ness of these extraneous characters isenough to overcome any checkingthat I might try to do in software (i.e.,looking for a sync character).

The other problem I had was inregard to the modem’s susceptibilityto RF noise on its VCC line. This prob-lem came up during preliminary test-ing when I used an Atmel AT90S2313microcontroller to interface to thePlinius modem.

The AT90S2313 turns out to be astrong little RF signal producer! I wasunable to get the Plinius to transmitgood data any time it was being pow-ered by the same 5-V power supply asthe AT90S2313. Several hundred mil-livolts of RF noise (at the second har-monic of the clock) were present onthe 5-V line whenever the AT90S2313microcontroller was plugged in. Noamount of filtering across the 5-V sup-ply would reduce it sufficiently toallow the Plinius to work properly.

This problem is not the fault of thePlinius modems. It took a while touncover this problem though becauseI had used AT90S2313s with VHF RFmodules successfully before, and hadnever actually used an oscilloscope onthe VCC line or observed this RF inter-ference before. The Atmel ’8535microcontroller, which I used at bothends of the data link, does not gener-ate this RF interference.

Although not a problem, I shouldmention that the Plinius does notlike to see its RTS line held low(transmitting) for more than 3 s. Itwill switch back to Receive mode ifthis occurs and stay in that modeuntil the RTS line is toggled high andthen returned low. The goal behindthis is to prevent a Plinius module

Photo 1—This split image shows the SC-600 sensoralong with its built-in signal conditioning electronics.

Page 19: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 17

from saturating or hoggingthe power line with an RFcarrier, in the event that arunaway microcontrollerprogram leaves the devicein Transmit mode. Thislimitation did not affectmy application in any waybecause my data packetsare short.

THE DATA LINKThe hardware layer of

the data link is taken careof by the Plinius modulesmentioned earlier. Theywill send and receive asyn-chronous data from themicrocontroller’s UARTport at up to 2400 bps without anyparticular regard to data format.Because the Plinius uses FSK modu-lation, you don’t have to worry aboutformatting the data for roughly equaloccurrences of ones and zeros in thedatastream as you would with an on-

off-keyed wireless transmission link.I’m sending a small data packet so Isettled on a transmission rate of1200 bps to improve reliability. Thiswas the slowest standard rate themicrocontroller will produce using a4.19-MHz crystal.

The Plinius CARRIERDETECT signal will becomeactive 4 ms after a carrier ofminimum-acceptable ampli-tude is present at its receiv-er. I transmit a preamble ofsix 0AAh characters aheadof the actual data packet sothe CARRIER DETECT sig-nal is true just before theactual data packet starts.

For anything other than ahardwired serial data link, afixed packet structure withsynchronization and errorchecking is an absolutenecessity. I’m sending onlya few byte-wide variables(temperature, humidity,

runflag) and there are only two Pliniusmodules involved, but I decided toallow for the possibility of using addi-tional Plinius modules in the housefor future ideas. In my initial talkswith Vincenzo, he mentioned that hehad tried the SNAP protocol with his

Plinius devices. Like the Pliniusmodules themselves, the SNAPprotocol is of European origin, soI opted to keep everything in thesame family, so to speak.

SNAP TO ITSNAP stands for Scalable Node

Address Protocol, which wasdeveloped by High Tech Horizon(HTH) in Sweden. It is a free,open network protocol that,when scaled down to its simplestform, requires minimal MCUresources to implement.

Although the protocol can beconfigured to handle up to16.7 million node address, it canbe scaled back to run a simplehome network containing lessthan 255 nodes. The SNAP pro-tocol can operate in a peer-to-peer or a master-slave configura-tion and supports many forms oferror checking or detectionschemes. SNAP was designed tobe media-independent, so it iscompletely flexible with regardto data format and preamblespecifications. And this protocolcan operate in simplex, half, orfull-duplex mode.

Figure 3—I chose the AT90S8535 for both the master and slave modules. The ’8535 has enough flash memory to allowwriting the program in BASIC, as well as 10-bit ADCs for reading the sensors.

Photo 2—This is a close-up view of the Plinius line modem module. The modulecould be much smaller except for the large line coupling capacitor seen just behindthe 18-pin signal connector.

Page 20: circuit-cellar2002-05.pdf

18 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

SNAP can be used freely by anyonefor personal projects such as this one.Even if it is used commercially, therearen’t hassles. The only requirementis that the user register with HTH toget a free vendor ID number.

The SNAP protocol is clearlydefined on HTH’s web site. I won’trepeat all of the information, but I’llshow you the SNAP packet structurethat I implemented to handle thesimple communications that I neededfor this project.

A 6-byte (0AAh) preamble is sentfollowed by an 8-byte packet asshown in Figure 2. For my particularsituation, I knew there would never bemore than 255 nodes in my home, so Iam never going to need anything otherthan 1-byte node addressing. Thatallows my SNAP driver to be com-pact. I merely check that the incom-ing packet comes from the correctsource and is addressed to the correctdestination. The only other check I

make is that the CRC byte iscorrect after the packet is fullyreceived. The possibility existsthat an incomplete packet maycome in, so I constantly checkfor the presence of a trueCARRIER DETECT signal dur-ing packet reception and abortthe packet handling routinewith an error flag set if theCARRIER DETECT signal dis-appears before the packet hasbeen fully received.

Although the data require-ments of this particular data link aremodest, I think it made sense to settleon a readily available packet standardrather than trying to roll my own.

THE MASTER CONTROLLERThe master controller contains a

keypad/LCD for the user interface, theinside temperature and humidity sen-sors, and a Plinius power line modem.This unit maintains the real time clock

(in software) that sets the operationalmode depending upon the time of day.The decision whether to turn theHRV on or off is made by this unit’smicrocontroller, based on the rules asdescribed earlier, as well as the valuesof the inside/outside sensors. Theoutside sensor values are reported bythe slave module in response to a datarequest sent by the master via thePlinius power line modem link.

Photo 3 shows the unit withthe cover (containing theLCD and keypad) removed.

Figure 3 shows the com-plete diagram of the masterunit. I picked the AtmelAT90S8535 device from theAVR family mainly becauseit had a built-in eight-chan-nel, 10-bit ADC for the sen-sors as well as 8 KB of flashmemory (almost all ofwhich was needed to holdthe compiled BASIC pro-gram). The device also con-tains 512 bytes of SRAM,plenty for this application,as well as 256 bytes of EEP-ROM. All operationalparameters are stored inEEPROM so the unit’sparameters won’t have to bereprogrammed if the powergoes out. The ’8535’s clocksignal is provided by a4.1934-MHz crystal, whichwas chosen because itdivides down nicely whenused by the real time clocksoftware routine.

The user interface con-sists of a 16-button matrixkeypad connected to port C

Figure 4—Take away the user interface and the slave module looks a lot like the master. A power supervisor chip is added forsecurity because this unit is hidden away in the basement.

Photo 3—Here’s a look at the master controller module with thetop cover removed. The Plinius modem is mounted at the upperright corner of the PCB.

Page 21: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 19

and a 4 × 20 LCD, driven by six linesof ports B and D. A small piezo buzzerdriven by port B4 alerts me if a powerfailure occurred (which requires userintervention to reset the clock).

The Plinius power line modem isconnected directly to the ’8535’s serialport. The Carrier Detect and RTShandshake lines are connected toports D2 and D3, respectively.

The inside sensors for temperatureand humidity are connected to chan-nels zero and one of the ’8535’s inter-nal ADC. The LM34DZ has a voltageoutput that falls within the 2.5-VADC range, but the SC-600 humiditysensor produces 3 V full-scale, so it isscaled down to 2.5 V by a calibrationpotentiometer. The ADC of the’8535’s gets its 2.5-V reference fromthe Plinius module.

The power supply is a conventionaltransformer-driven bridge rectifier fol-lowed by a three-terminal regulator.You can’t substitute a wall wartadapter because both L1 and neutrallines are needed to connect to thePlinius mains pins. Components R3and R4 set the threshold for thepower-on reset circuit within thePlinius module. Although I chose notto use the Plinius reset output to gen-erate the ’8535 reset signal, the com-ponents mentioned are needed to pro-vide a proper reset for the ASIC chipcontained in the Plinius itself.

THE SLAVE CONTROLLERFigure 4 illustrates the wiring of the

slave controller. If it looks a lot likethe master controller, that’s becauseits circuitry is similar. The slavedoesn’t require a user interface, sothe keypad and LCD are out of thepicture. In their place is the HRVcontrol relay and the heartbeat LED.The same type of temperature andhumidity sensors are used, but in thiscase they are placed outdoors in asmall plastic box.

My Lifebreath-brand HRV has anexternal terminal strip to which aremotely located humidistat may beconnected. This is a common 24-Vcontrol circuit. The slave’s controlrelay contacts are wired to this termi-nal strip in order to turn the HRV’sfan on and off.

The heartbeat LED is driven by portB1, and flashes briefly every time theCarrier Detect interrupt service rou-tine executes. Because the mastersends a data packet once per second,the LED will normally flash at thisrate if everything is OK. Note thatthis LED will flash if the data packethas errors in it, so it’s not really a fulltest of the data link.

Because this unit is hidden away inthe basement, I decided to use apower supervisor chip to reset thecontroller if power glitches occur.The software also uses the watchdogfunction of the AVR to reset thedevice if the program should runaway for any reason.

FIRMWARENone of the code for either the mas-

ter or slave modules had to be particu-larly fast. There’s always a fair bit ofcode involved in providing a user-friendly interface, which involvesentering numerous parameters. Somefloating-point operations were alsoneeded so I chose to write thefirmware for both modules in com-piled BASIC, using the Bascom-AVRcompiler from MCS Electronics.

This compiler supports all of theAVR’s interrupts, which was animportant consideration here becauseinterrupts are used for both the soft-ware real-time clock, and the CarrierDetect interrupt service routine. Thefact that the compiler contains abuilt-in device programmer for AVRdevices is icing on the cake. Idescribed this compiler in more detailin my article “My fAVRorite Familyof Micros” (Circuit Cellar 133).

The program code for the mastercontroller uses almost all of the 8192 bytes of available flash memo-ry, precluding the use of less well-endowed members of the AVR fami-ly. On the other hand, the slaverequired only 1422 bytes. I’ll admitthat I could have gotten away with asmaller microcontroller here. The 28-pin AT90S4433 was available andcertainly would have done the trick,but I didn’t think it was worthwhileto switch from the ’8535 device,which I keep on hand, just to save afew dollars.

Writing the program in BASIC alsohas the advantage that it is much easi-er for you to modify my control algo-rithms to better suit your climate.

GASPING FOR AIRThe controller is telling my HRV to

pump in some fresh air as I sit at thecomputer writing this article. Youmay be happy with the control aspectof your home’s environmental controlsystem, but that shouldn’t stop youfrom looking into the Plinius modulesfor other remote control applicationsaround the house. I

SOFTWARETo download the source and objectcode for the master and slave con-trollers and the Plinius datasheets,go to ftp.circuitcellar.com/pub/Circuit_Cellar/2002/142/. This andany additional information is alsoavailable on the author’s web siteat is.dal.ca/~bmillier/index.htm.

Brian Millier is an instrumentationengineer in the Chemistry Departmentof Dalhousie University in Halifax,Canada. He also runs ComputerInterface Consultants. You man reachhim at [email protected].

SOURCESAVR data books, assembler, andsimulatorAtmel Corp.www.atmel.com

BASCOM-AVR Compiler/program-merMCS Electronics (Holland)www.mcselec.com

Plinius power line modemsTelecontrolli s.p.a.+39 2 5516417www.telecontrolli.com

Lextronic(01) 45-76-83-88www.lextronic.fr

SC-600 Humidity SensorOhmic Instruments Co.(410) 820-5111www.ohmicinstruments.com

SNAP network protocolHigh Tech Horizonwww.hth.com

Page 22: circuit-cellar2002-05.pdf

20 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

n December 12,1901, scientist and

Nobel Prize winnerGuglielmo Marconi was

able to transmit across the Atlanticocean for the first time in history. Onecentury later, wireless communica-tions are ubiquitous. Anyone can pickup a cell phone and talk with a friendlocated on a different continent. Voicecalls are only one of the options; thelatest cell phones can send faxes,exchange text messages, e-mails,music, and even connect to theInternet. In other words, whatever theorigin of your information, if it can bereduced to small data packets it can bedelivered to a mobile phone.

This circuit connects to the serialport featured by many cellular phones.Its function is to provide an input andoutput port capable of being remotelycontrolled using another mobile.Control takes place by means of shortmessage service (SMS). When themobile phone receives a predefined textmessage (e.g., “Activate burglar alarm”or “Start backup pump”), the circuitautomatically recognizes it as a com-mand and switches the output accord-ingly. Besides switching the port on oroff, you can pulse it for a short period(e.g., “Reboot remote server”).

Additionally, you can use thedevice to relay the status of the inputport, automatically sending a mes-sage every time the input changes. Toget input status at any time, thedevice can send back an SMS based onthe status of the input as a response toa request message.

SMS messages are simple and con-venient; they can be entered, stored,and read directly on the cell phoneitself. Incoming messages are complet-ed with the time of reception andstored automatically in the mobilephone’s memory. By means of one ofthe various services offered by net-work operators, they can be convertedto faxes, e-mails, and even voice callsspoken by a synthetic voice. As anadditional benefit, the service is fairlypriced because it doesn’t require pre-cious real-time bandwidth.

The potential applications arecountless. You can use it to make anextended range remote control, opera-ble from anywhere in the world. Forindustrial purposes, it can monitor ifa machine is running or if somethreshold is surpassed. The technicalstaff is alerted automatically and canremotely operate an immediate coun-termeasure. Commercial applicationsare numerous as well. All of thecomponents of a home automationsystem can be conveniently con-trolled and monitored from a cellphone. To enhance its wide applicabil-ity even further, the circuit is smalland battery-operated.

INFORMATION GATHERINGAs an engineer, that little golden

connector on the bottom of my cellphone always attracted me. After a lit-tle Internet browsing, I found the con-nector pinout of my Ericsson T10s.The signal names confirmed myexpectations: audio input and outputto connect an external hands-free,mute-control, flash memory-program-ming signal, battery, external power,and serial RX and TX.

I would have connected it immedi-ately to the PC COM port, but theconnector on the mobile is too smallto get a reliable contact without riskof damaging the phone. I, Alberto,decided to buy a ready-made data

Tiny Planet—A One-Bit,Wireless I/O Port

oClaudio and Albertotook a closer look atthe connector on a cellphone and designed acircuit that wouldallow users to keep intouch with machineryand hardware any-where in the world.Staying in touch withproducts can be justas easy as staying intouch with people.

Claudio Lanconelli &Alberto Ricci Bitti

FEATUREARTICLE

Page 23: circuit-cellar2002-05.pdf

Issue 142 May 2002 21

the fourth message, a one means ithas been received and read. It is27 bytes long and is in ProtocolDescription Unit (PDU) format.

The PDU format is complex; it con-tains many subfields packed togetherusing different encoding. Among otherthings, it also holds service centernumbers, origin numbers, nationcodes, a time stamp, and a descriptorof the character set used.

For more detailed information, seethe “SMS Data Dissected” sidebar. Forour purposes, it is sufficient to knowthat the text bytes are on the right-most position. Storing a signaturefrom the last six bytes of the message,the device will be able to recognizeincoming messages.

At this point, you are able to down-load messages from the mobile phone.The next command frees preciousmobile phone memory, deleting theseventh message. The last step is tosend an SMS message. This proved tobe the more difficult part, because Ihad to find a workaround in order toavoid building a PDU from scratch.The trick is to ask the user to sendthe message manually, during thefirst setup. In this way, the mobileunit will complete the PDU with allof the required fields, it will pack thetext and numbers, and will storethem in the sent messages memory.At a later time, a simple command isall that is required to resend the mes-sage from memory.

cable, and in the meantime, continuedsearching for more information aboutthe data protocols.

One of the aspects of the Internetthat I like most is its capability toseek information straight from thesources. I subscribed to the developerzone on Ericsson’s main web site, andafter some unsuccessful navigationfound an interesting message in theforum. This time I was surprised.

To start with, similar to modems,cellular phones can accept AT com-mands (more precisely, an extensionof the AT command set). Besides SMSmanagement, the extension handlesmany functions, including mobileidentification, address book manage-ment, signal strength level, call wait-ing and forwarding, error report, bat-tery charge monitoring, ringing tones,volume, plus nonstandard commandsintroduced by manufacturers.

But the real surprise was to discoverthat the standard rules that governGSM cell phones (including the ATmodem command set extension) derivefrom the European TelecommunicationInstitute (ETSI), which published themonline. The rules applicable here areETSI GSM 03.40 and ETSI GSM 04.11.I immediately downloaded the relevantstandard and started deciphering it.

SERIAL COMMUNICATIONTrial and error with the phone con-

nected to the PC helps understandingthe extended AT command set usedby the cell phone. After setting

HyperTerminal to 9600 bps, no parity,8 bits, and 1 stop bit (a lucky guess), Istarted typing in commands. Listing 1states the commands and responsesfrom the cell phone (in italic).

Using the technique demonstratedin the first command, I selected thecommands relevant to the application,manually simulating the intendedalgorithm. [1] I saved you the pain goingstraight to the conclusion. First, youtell the phone which memory to use forsuccessive commands. This instructsthe mobile unit to use internal memo-ry “ME” in place of the “SM” memo-ry from the subscriber identity mod-ule (SIM) as default memory.

Next, a message can be read fromthat memory specifying its number. In

Figure 1—The only active parts of the circuit are the ATtiny2L and a transistor. A voltage regulator is unnecessary.

www.circuitcellar.com CIRCUIT CELLAR®

Listing 1—The microcontroller issues these commands. When connected to a PC through a data cable, aGSM phone resembles an ordinary modem accepting specialized AT commands.

ATOK

AT+CPMS="ME","ME"+CPMS: 7,15,7,15,7,15OK

AT+CMGR=4+CMGR: 1,,270791934329005000040C9193433728501400001060314104350809D02A735A043DAB54OK

AT+CMGD=7OK

AT+CMSS=1+CMSS :96OK

Page 24: circuit-cellar2002-05.pdf

Besides being simple for the micro-controller, this technique is simple foryou too. I like to call it “set up byexample.” To set up the system forwhich text to send, phone numbers touse, and commands to recognize, justsend the information once manually(as usual, using the mobile unit), thenpress the Configuration button to makethe machine learn them automatically.

Another advantage of using onlyfour among the many AT commandsavailable is an improved compatibili-ty. Manufacturers introduced minordifferences while implementing thestandards. Although it has been testedwith the Ericsson T10s only, theunmodified circuit should work withany other mobile device that supportsthe same command subset.

CIRCUIT DIAGRAMWhen I told Claudio about how easy

it would be to control things using a

The serial stream enters the chipthrough PB4. Diode Z1 and R4 cut thenegative fraction and limit inputswing. Conversely, the output streamfrom PB2 drives transistor Q1. On thecollector, a negative voltage is derivedfrom the input stream. In this way,the data output to the cell phone is atrue bipolar signal. The output streamalso is used to drive an LED; it is con-nected straight to PB2 and flashes atevery transmission.

The PB0 pin is connected to a jumperthat tells the software to disable auto-matic notification of input changes. Itis pulled up internally, and resistor R6is used to resolve conflicts during in-system programming. R6 can be omit-ted if the ISP takes place with thejumper removed. The pins are assignedto functions that don’t impede ISP.

The input goes to pin PB3, which ispulled up internally; the output comesfrom pin PB1. Both have a small protec-

22 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

cell phone, he agreed that the subjectwas worth a try. We decided to use thesmallest processor and as few externalparts as possible. The circuit makes themost of a ATtiny12L and a transistor,and is remarkably simple (see Figure 1).

Atmel’s ATtiny-12L is an 8-pinmicrocontroller with 512 words offlash memory code, 32 registers, and64 bytes of EEPROM. Three AA cells,for a total of 4.5 V, power the circuit.The ATtiny12L has an internal brown-out, therefore, it can run safely withoutrequiring a voltage regulator. Apartfrom VCC and GND, all of the eightpins are available thanks to an internaloscillator running at a respectable speedof 1 MHz. With 1 MIPS at our disposal,the serial communications can be han-dled entirely in the software. Precisetiming is not sacrificed by means ofan adaptive algorithm that adapts seri-al port speed to the internal clockvariations as the battery discharges.

SMS DATA DISSECTEDConnecting to a mobile phone

and issuing a few AT commandsis straightforward. However,exchanging SMS data requiresfamiliarity with the composi-tion of the Protocol Data Unit(PDU), which is required by orgiven in response to most SMS-specific AT commands. Youhave to be prepared for minorchanges depending on the man-ufacturer’s implementation ofthe standards.

A PDU looks like a longhexadecimal string, represent-ing the number of the networkoperator’s SMS central service center address (SCA).The SCA is chained to the packet used in the SMStransport layer (often referred as Transport ProtocolData Unit, or TPDU). The latter includes many sub-

fields in addition to the message text. Most data ispacked to save bits.

A nice way to get a copy of both sent and receivedPDUs is to send yourself a simple SMS, connect the

01 80 11 00 0A 81 43 37 28 90 55 00 00 A7 0B C8 20 93 F9 04 5D 9F 04 5D 9F 52 26 11

ID MR DA PID DCS VP UDL User data

SMS—Submit TPDUSCA

PDU Returned by the AT+CMGL command

07 91 93 43 29 00 50 90 04 0C 91 93 43 37 28 90 55 00 00 20 10 31 61 55 61 04 0B C8 20 93 F9 04

ID PID DCS UD

SMS—Deliver TPDUSCA

PDU Returned by the AT+CMGL command

5D 9F 52 26 11

OA SCTS UDL

Figure s1—SMS data is stored in phone memory along with the information required by the GSM transport layer. The resulting record is referred to as PDU.

Subfield Name Definition LengthSCA Service Center Network operator’s service center number. Not required by all 1 or 2 to 12

Address phones. A hex value of 00 or 01-80 means “unknown”: the bytesphone will use the default number stored in its settings

ID TPDU type identifier SMS-DELIVER or SMS-SUBMIT identifiers and flags (e.g., request 1 byteof a status report or presence of VP field)

MR Message Reference Progressive number (0 to 255) 1 byteOA or Originating or Sender’s or destination phone number. Different number encoding 2 to 12 DA Destination Address from that of SCA is used. bytesPID Protocol Identifier Nature of data transported (fax, voice, etc.), used by the service 1 byte

center for a better routing DCS Data Coding Format of the data transported (7 or 8 bits, alphabet, etc.) and where 1 byte

Scheme to store it (phone memory, SIM module, or for immediate display) SCTS Service Centre Year, month, day, hour, minute, seconds and time difference with 7 bytes

Time Stamp respect to GMT VP Validity Period How long the network operator service center will hold the message 0, 1, or 7

if undelivered (A7 = 24 hours) bytesUDL User Data Length Length of data prior to encoding (e.g., 11 7-bit characters fit into 10 bytes) 1 byteUD User Data The message data, “HALLO WORLD” 0-140 bytes

Table s1—You’ll need the definitions of the subfields.

Page 25: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 23

mobile unit to the PC, and then read themessage from its memory using the AT+CMGL command. The following exampleshows the PDU for the message “HALLOWORLD,” sent from the number ++39 3473820955 at 4:55:15 p.m. on January 13,2002. The mobile phone used was an Ericsson T10s andthe service center number was ++39 349 2000509 (seeFigure s1). The first packet is the SMS-SUBMIT, used forsending a message; the second is the SMS-DELIVER pack-et for receiving. The subfields are detailed in Table s1.

Phone numbers start with the length of the number,intended as field length in bytes for the service center(SCA) and digits for the remaining numbers (DA, OA).The second byte specifies the numbering plan: 80 is

unknown, 81 is anational number, 91 isan international num-ber. Then follow thedigits, swapped in pairsand each occupying anibble. This is how thephone number ++39 349200059 is encoded. Seehow the numbers arestored in Figure s2.

If the length is odd, the unused nibble (semi-octet inETSI language) is padded with “$F”. Some mobilephones don’t require the SCA or accept 00 or 01-80 asvalid values for the service center address. In that case,the phone will use the default service center number.

An SMS message, according to ETSI specification, canbe up to 140 bytes long (octets in ETSI terminology).The usual GSM alphabet requires only 7 bits per charac-ter (septet), allowing for the packing of up to:

Let’s go over an example of how 7-bit data is packedbetween successive bytes. The 7-bit binary encoding ofthe string GSM is G = 1000111, S = 1010011, and M =1001101. Let G0 be bit 0 of letter G, G1 be bit 1 of letterG, and so on. Then, the PDU will pack data as is shownin Figure s3. Note how the last three spare places arepadded with zeroes.

First byte Second byte Third byte Fourth byte Fifth byte Sixth byte Seventh byte Eighth byte(length) (format)

0 7 9 1 9 3 4 3 2 9 0 0 5 0 F 9

Figure s2—The digits are stored in nibbles. The format differs for SCA and DA/OA numbers.

First byte

Second byte

Third byte

S0 G6 G5 G4 G3 G2 G1 G0

1 1 0 0 0 1 1 1

M1 M0 S6 S5 S4 S3 S2 S1

0 1 1 0 1 0 0 1

zp zp zp M6 M5 M4 M3 M2

0 0 0 1 0 0 1 1

Figure s3—To save space, text (7-bit)data is packed among successive bytes.

!"

#$%&'

$(!

) (%(%

*+,-$((..'

Page 26: circuit-cellar2002-05.pdf

24 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

tion resistor connected in series.The RESET pin is pulled up withan external resistor, because theinternal pull-up has a high value.Conversely, lowering inputimpedance removes the risk ofpicking up noise emanating fromthe intense electromagnetic fieldof the mobile phone.

HOW THE CODE WORKSThe code was written in

assembly on the AVR Studio assem-bler. The algorithm at the heart of theTiny Planet project is simple. Duringsetup, the four messages used as com-mands and the two messages used asresponses are stored in the phonememory, where they can be readback by the controller issuing theappropriate extended AT command.For every command message, the set-up routine extracts a unique 6-bytesignature from the last message bytesand stores it in EEPROM.

The system expects that every mes-sage be stored in a fixed position, asshown in Figure 2 (to ensure this,

delete all of the messages from themobile phone prior to setup).Outgoing messages are in positionsone and two, which indicate a lowinput and high input, respectively.Incoming command messages are inposition three (request to report theinput status), four (command to pulseoutput), five (command to set output),and six (command to clear output).Position seven is kept free for incom-ing command messages.

During operation, the device repeat-edly checks the message memory inposition seven for the presence of anew SMS. When it finds a new mes-

sage, it compares its signatureagainst all of the stored ver-sions. If one of the signaturesmatches, the relevant com-mand (i.e., pulse output, setoutput, clear output, or send-back input status) is executed.Using signatures instead of thefull text allows the system tosave EEPROM, and makes mes-sages of arbitrary length possi-ble. The system is safe, as well,

requiring an exact match of the lastsix characters to accept a command.

The Send Input Status command aswell as a level change of the inputpin when the autosend jumper isopen, causes a message to be sentout. It is neither necessary to recre-ate the outgoing message fromscratch nor store it in EEPROM. It’ssufficient to resend the first or sec-ond message from the mobilephone’s message storage, accordingto the status of the input pin. At theend of the cycle, the message iscleared from memory and the systemis ready for a new command.

Photo 1a—How do you mount a 50-mils part on a 100-mils breadboard?Programming is done in-system via the strip socket. b—After you’ve fin-ished programming the unit, you can place it in a small plastic box.

a) b)

Page 27: circuit-cellar2002-05.pdf

MBasic Software

Whether your just learning or a professional, Programming PICmicro®MCUs has never been easier ! MBasic is much simpler than C orAssembly. MBasic creates a one click solution that allows you toexperiment and test code changes on-the-fly! Bring your projects to lifequicker and easier with MBasic for PICmicro® MCUs !

ICD - In Circuit Debugger

Stop wasting time strategically planting debug statements throughoutyour entire program. MBasic includes a built-in ICD (In CircuitDebugger ) FREE. Watch variables, SFRs and RAM values as eachline executes. MBasic’s ICD is so easy to use, even the first time usercan have it up and running in minutes !

MBasic and Assembly Language

Seasoned Assembly programmer or just learning ? MBasic allows aneasy mix of BASIC and Assembly. Instead of spending weeks writingyour program, have it done in days !

Syntax

A complete set of easy to use commands ! Serin, Serout,If..Then..Elseif..Else..Endif, Do..While, While..Wend, OWin, OWout,ADin, Pulsin, Pulsout, PWM, Xin, Xout and more! Plus easy acces toall PICmicro built-in hardware peripherals.

Math

MBasic is the only BASIC compiler that supports 32 bit floating pointand integer math. This includes 32 x 32 bit divides and multiplies.

MBasic Pro Only $229.95

Includes Printed Manual and CD-ROM with MBasic.

ISP-PRO Programmer

- Uses PC Serial port (USB w/ adapter)- Very Simple to use- Free Software updates- Complete with Windows IDE!- Easy in-circuit programming- Supports PIC, Scenix, I2C and more!- Firmware upgrades Free!- RJ-11 / 10 Pin Header- Includes RJ-11 Cable

Solderless Development

- Completely Assembled Board- In Circuit Programmable (ISP)- Solderless Bread Board- Built in RS232 (w/ Max232)- Built in Power Connector- Removable Oscillator- Documentation- Auto Disconnect for RB3, RB6, & RB7- Available in several models

Development Kit

Includes: - MBasic Pro Compiler - 2840 Development Board - ISP-PRO Programmer - PIC16F876-20 - 10Mhz Resonator - Serial Cable - Power Supply - CD-ROM and Manual

Download MBasic

Lite FREE !

Starting At $159.95Starting At $59.95Only $59.95

Learn to Program PIC Microcontrollers in easy to use BASIC

Optional ISP-PRO

Items Available

- Plastic Enclosure- 40 Pin Zif Adapter- Universal Adapter

Try before you buy !

PIC

MIC

RO

MC

U® TO

OLS

www.basicmicro.com

!"

#"$%&'M i crocont ro l l e rs M ad e Easy™

MBASIC is a registered trademark of Basic Micro Inc.

PICmicro is a registered trademark of Microchip Inc.

Join our on-line PIC forums, information and help FREE!!!

Page 28: circuit-cellar2002-05.pdf

26 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

RUNNING ON BATTERIESThe software implements low-

power techniques, which extend bat-tery life to more than a year of con-tinued use using AA cells. TheATtiny12 is perfectly suited to run onbatteries. Most of the time the con-troller is in Sleep mode with only thewatchdog on. In this condition,power consumption is only 200 µA.Control is resumed when the watch-dog expires (a couple of seconds) orwhen the input pin changes, thanksto the ATtiny12’s capability of wak-ing up on a pin change.

When running, the required currentis about 1 mA for a period as short as20 ms. Every 10 short breaks (about20 s), the microcontroller starts alonger dialog with the mobile unit,requiring an extra 840 ms at 1 to 2 mA(shown on the left in Figure 3).

The circuit runs on the internaloscillator, so the clock frequencyvaries over the lifetime of the batter-ies. The serial port routines imple-ment an auto-baud algorithm thatadapts its timing as clock changes. Tosave another nibble of energy, thecalibration value is stored in EEP-ROM and the calibration is repeatedonly when needed.

Last but not least, the circuit mustbehave correctly when still connect-ed to a discharged battery. The proto-type passed the test brilliantly: theinternal brownout halted the con-troller as expected.

BUILDING THE PROTOTYPEThe circuit is made of a small num-

ber of parts, so we skipped the prepa-ration of a PCB and replaced it with abreadboard. All of the components arethrough-hole except the ATtiny12,which is a surface mount device. Butwho’s afraid of SMD? Just solder a rowof 50-mils pin strip to each side of theIC. In order to fit the 100-mils spacedbreadboard, gently bend the legs of thespider (See Photo 1). Fortunately theATtiny can be programmed in-system,so it doesn’t need to be removed.

Fitting the remaining parts was abreeze. And, the finished board looksspacious and clean. The circuit andthe batteries are enclosed in a smallplastic box. On one end of the box, wecut the holes for the Configurationbutton, LED, and connector for the

input and output (actually afour-pole RJ-45). You may wishto replace the autosend jumperwith a panel switch and placeit on the front panel. We foundthis unnecessary. On the oppo-site end of the box, we cut thehole for the D-type connectorfor the serial port.

After you place all of thecomponents and double checkthe board for errors, you maystart programming. We usedthe excellent PonyProg soft-ware written by Claudio. And,we powered the board with 5 Vfrom a bench supply.

The finished prototype iscompact and professional look-ing. The box is about the size

of the cell phone. Packed together, thebox and phone can be placed practical-ly everywhere (see Photo 2).

USER INTERFACEThe device is simple to use. You

can customize the text messages forboth commands and readouts (seePhoto 3). Plain text messages like“Activate burglar alarm” work well.Just make sure that the at least oneout of the last six characters is differ-ent for every command.

To prepare your system for setup,first switch on the mobile phone andthen connect it to Tiny Planet using asuitable data cable. This is the slavephone, to differentiate it from themaster phone, used to issue commands.

To set up a new set of messages,send them in the usual way using thecell phones for editing. Use the fol-lowing sequence of tasks. First, beginfrom the slave mobile: delete all of themessages currently in memory, sendthe message for the input low condi-tion (e.g., “The input is low”) to themaster, and then send the message forthe input high condition to the mas-ter. These messages must be sent evenif you aren’t going to use the inputport feature of the Tiny Planet.

Next, it’s time to move to the mas-ter mobile phone, which you use toissue commands. Issue the followingcommands in the order given. First,send the message for requesting theinput status (e.g., “What is the inputstatus?”) to the slave. Second, sendthe message for pulsing the output(e.g., “Pulse output”) to the slave.Third, send the message for clearingthe output (e.g., “Switch output off”)to the slave. Fourth, send the mes-sage for setting the output (e.g.,“Switch output on”) to the slave.Again, all of the messages must besent even if you aren’t planning touse a specified command.

When all six messages are received,press the Configuration button. TheLED will flash until setup is complete.That’s all there is to it! If your applica-tion doesn’t require automatic notifi-cation of the input changes, rememberto close the autosend jumper. Whenthe system is running, the LED flashesonce every 20 to 25 s.

Photo 3—One of the best features of this project is that you cancustomize text messages.

Photo 2—The prototype is connected to an EricssonT10s GSM cell phone. Packaged together, the phoneand package can be placed practically anywhere.

Page 29: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 27

SOFTWARETo download the code, go to ftp.circuitcellar.com/pub/Circuit_ Cellar/2002/142/.

RESOURCESEuropean TelecommunicationsStandards Institutewww.etsi.org

Compatibility table for variousphonesgatling.ikk.sztaki.hu/~kissg/gsm/at+c.html

PonyProg Free ProgrammingSoftwarewww.lancos.com

REFERENCE[1] Ericsson Enterprise, “T28 AT

Command Online Reference,” rev. R1A.

SOURCESATtiny12L MicrocontrollerAtmel Corp.(408) 441-0311www.atmel.com

T10sEricsson Enterprisewww.ericsson.com/mobilityworld/

LESS IS MOREI like clean designs with great poten-

tial because of (not despite) their sim-plicity. The Tiny Planet project is asimple, flexible, portable solutionthat’s useful for a wide range of appli-cations. It doesn’t use a voltage regu-lator and makes profitable use of everyfeature of its components, includingEEPROM, brownout, internal oscilla-tor, watchdog, wake up on pin change,in-system programming, sleep modes.The code is dense, including powermanagement and an adaptive data gen-erator in just 417 out of the 512 wordsavailable. There is still enough spacefor adding new features or to modifythe behavior to suit your personaltaste. For example, you may want todirect the same alarm to three differ-ent phone numbers instead of one.

Making designs assimple as possibleimproves every aspectof a product. Theresult costs less, is eas-ier to manufacture, hasa smaller size (even inits actual handcraftedform!) and costs less topackage and ship. Alean bill of materials isalso the best insurance

from parts shortages. All of theseaspects contribute to increasing bothprofitability and added value.

The user interface we developed isremarkable as well. Most of thework is carried on the mobile phonein a common way, so a push buttonand single-page user manual is allthat you need to run it. Comparethis to a PC running the internation-al software required to set up mostindustrial GSM modems.

The characteristic I like most isthat this little, inexpensive circuitallows anyone to start experimentingwith a mobile phone, discovering adynamic world that opens new, excit-ing, and unparalleled possibilities. Aworld discovered 100 years ago byMarconi’s invention, that ever sincehas made our planet very, very tiny. I

Claudio Lanconelli is the author ofPonyProg, a powerful programmer forseveral microcontrollers and serialEEPROMs. He has several years ofexperience designing hardware andsoftware for embedded systems.Some of his interests include homeautomation, Linux, and networking.You may reach him at [email protected] or visit his web site atwww.lancos.com.

Alberto Ricci Bitti holds a degree inComputer Science from University ofMilan. He has 10 years of experiencedesigning and writing software forembedded systems. In his free time,he enjoys competing in design con-tests, and has won several prizes.Currently he is a designer for Eptar,an industrial controllers and instru-mentation firm. You may visit hisweb page at www.riccibitti.com orcontact him at [email protected].

Figure 3—The prototype can run on three AA cells for more than one year.

#8: Free

#7: Incoming messages go here

#6: Command: set output

#5: Command: clear output

#4: Command: pulse output

#3: Command: request input status

#2: Outgoing message when input = 1

#1: Outgoing message when input = 0

Signature: command = on

Signature: command = off

Signature: command = pulse

Signature: command = request

Figure 2—To compare variable length messages without RAM, messagesare reduced to signatures. To check if a new SMS is valid, its signature iscompared against the authorized set. The 6-byte signatures for each of thefour commands are stored in EEPROM.

Page 30: circuit-cellar2002-05.pdf

28 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

ne of myfavorite engineer-

ing topics to discussis electromagnetic com-

patibility (EMC). In past articles, I’vetalked about the various aspects andexplained how understanding EMC willaffect your design decisions. In thisarticle I would like to look at EMC ina more practical way and discuss howyou can bring it under control.

Every electronic circuit is not onlysusceptible to electromagnetic inter-ference (EMI), but is also a source ofunwanted emissions. These excessemissions can interfere with otherequipment. So, when consideringEMC, you have to consider both thesusceptibility to and the emissions ofinterference signals at the same time.

On the up side, many of these inter-ference signals are well outside theoperating frequency bandwidth ofequipment. And if you design circuitsthat are immune to interference,which is usually your primary con-cern, the unwanted emissions oftentake care of themselves, falling wellbelow permitted levels.

Electromagnetic emissions comprisean electric field (e-field, expressed involts per meter) and a magnetic field(h-field, usually expressed in amperes

per meter). Knowing the operatingimpedances, you can convert the cur-rent per meter into voltage per meterfor consistency. That’s what I’ll coverin this article.

Typically, effects of a 0.3 A/m h-field created by a transformer during abulk injection testing equates to200V/m e-field. Rarely are you facedwith a pure electric or magnetic field.The magnetic component usually pre-vails in the low frequency rangewhereas the electric component domi-nates in the high frequency range.

To test equipment for compliancewith design requirements, interferencein frequencies from 10 kHz up to about400 MHz is injected into the cables(bulk injection) through a current trans-former while electrical fields from100 kHz to as high as 40 GHz are radi-ated by an assortment of antennas. [1]

Understanding that there are twodifferent fields, magnetic and electric,is critical because different methodsof protection are needed for each field.For example, wire shielding is electro-static, and has little effect in magneticfields. For some protection you canreduce interference by twisting thewires. Keep in mind that twisting thewires helps with low-frequency mag-netic and electric fields, but starts tofail when the wave length of high-fre-quency electric fields approaches thepitch of the twist.

HOW MUCH PROTECTION?The maximum emission levels are

prescribed by legislation and you’reonly option is to comply. But howmuch immunity to interference do werealistically need? What is the threatlevel we should expect?

First of all, the level of protectiondepends on the criticality and theoperating environment of the equip-ment. Susceptibility to interference inan entertainment appliance may belittle more than a nuisance, but anaircraft fly-by-wire system that’s fre-quently exposed to high intensityfields (such as those emitted fromradar antennas) must be steady underall circumstances. Opinions abouthow much interference is encounteredin real life have been constantlychanging as new evidence and test

Working with EMC

oTeamwork involvesgive and take. How-ever, when it comes toEMI, every circuitwants to give, butnone of them want totake. George explainssome differencesbetween magnetic andelectric emissions andhow your next projectcan be designed tohandle both.

George Novacek

FEATUREARTICLE

Page 31: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 29

0.4 V. Such a conductor can be any-thing from a 100′ wire run to a com-ponent lead that is a fraction of aninch long. Figure 1 shows the voltageinduced in a conductor in free air. Ona 1-m length of wire placed in the2000 V/m e-field, there will be 2000 Vinduced above 150 MHz. This fre-quency corresponds to the half wave-length represented by the length ofthe wire. Even if a conductor run,such as a PCB trace, was only 10 cmor 0.4″ long, the induced voltage at150 MHz would still be a serious200 V. And, taking it down to 1 cm or0.4″, you still have 20 V to contendwith. Such voltages are certain tocook any electronic componentexposed to them.

If you accept the 0.4 V as the maxi-mum voltage tolerable, you have toreduce the interference by:

What can you do? How do you dropthe interference by 74 dB? There areseveral options, so let’s take a closerlook at them.

INTERFERENCE REDUCTIONThe most obvious area to explore is

moving the conductors from free air

results come to light. To the credit ofthe aerospace industry, only a handfulof malfunctions evidently caused byEMI have been recorded; they dateback to the times when a 1 V/mimmunity was considered adequate.

For years, 200 V/m was the maxi-mum threat level required by militarystandards (MIL-STD-461/462), althoughother military documents tend to sug-gest that some operational environ-ments significantly exceed this levelof field strength. [2] So what was somagical about 200 V/m? Where didthe value come from? The unofficialstory is that for years the U.S. ANSIC95.1 standard was used to establishthe maximum RF radiation hazardlevel for personnel. Therefore, it wasassumed that a vehicle would not bedriven in an environment exceedingthe field intensity considered unsafefor humans. In free space, this e-fieldintensity happens to equal 196 V/m.

There was also a practical considera-tion for military and aircraft equipmentmanufacturers to settle at 200 V/m.EMC testing is expensive and evennow generating electric fields inexcess of 200 V/m is no easy task.

Over the years, the widely acceptedthreat profile has changed. For mostavionic equipment today, the maxi-mum interference no longer exceeds100 V/m at frequencies up to 200 MHz.

That’s the good news. However, thethreat level increases significantlyabove 500 MHz and never comes backdown. How much does the EMI fieldstrength increase? The increase instrength depends on the criticalityand potential exposure of the equip-ment, but a requirement for severalthousands volts per meter of averagefield strength is not unheard of. Formodulated fields, you may have todeal with a 20,000-V/m peak.

DEFINING THE PROBLEMGenerating an accurate mathemati-

cal model for EMC analysis is next toimpossible, so the best approach tosolving EMI issues is to consider theworst case scenario. Often you willsee that the potential interference lev-els are so high, you can safely assumethat by providing adequate immunityfrom them, the protection will also

work the other way around and suffi-ciently attenuate the interferenceinternally generated.

For starters, let’s assume our equip-ment will be exposed to a 2000 V/m e-field in the frequency range of 400 MHzto 40 GHz. What are the undesiredeffects of such exposure? The firsteffect is the misinterpretations oflogic levels in digital devices (micro-processors, memory, or logic circuits).This can happen when the interferingvoltage is about 0.4 V.

The second effect is that when itcomes to analog devices, most controlsystems have bandwidth limitationsof just a few kilohertz. Thus, the RFsignal by itself will rarely affect thesystem. However, at 0.4 V, bipolarjunctions begin to conduct and enterthe non-linear operating region. Afterthe PN junction voltage has beenexceeded, it may start acting as amixer or an amplitude demodulator.The resulting parasitic signals oftenfall within the operating bandwidthand the system fails. Using unipolardevices such as MOSFETs (whichdon’t exhibit the nonlinearity of thebipolar junctions) can go a long waytoward taming the EMI.

To cause functional upsets, theinterfering field must induce voltageor current into the conductor that isconnected to a device input, whichresults in a voltage greater than about

0.1m 1m 10m 100m

Vol

tage

indu

ced

in w

ire [d

B]

Frequency [10 kHz to 10 GHz]

Induced 1V in 1V/m e-field

1.E + 01 1.E + 02 1.E + 03

20

0

–20

–40

–60

–80

–100

–1201.E + 04 1.E + 05 1.E + 06 1.E + 07

Figure 1—Use this graph to determine an interference voltage induced on a wire of given length in free air from10 kHz to 10 GHz. Because it is standardized for 1 V/m, other field strengths will convert directly to their respec-tive voltages. The effects of different wire lengths can be calculated by establishing their half wavelength frequency,from which to lower frequencies the signal drops at –20 dB/decade.

Page 32: circuit-cellar2002-05.pdf

The solution is to use a double-braided cable, the attenuation ofwhich is shown by the dark bluetrace. Its attenuation is also affectedby the resonance, where it deterioratesto –55 dB. Overall, you can rely on aminimum of –60 dB effectiveness.Needless to say, double-braided wiresare expensive and heavy, but if youneed to work in the high intensityfields, that’s the price you have to pay.

It’s absolutely imperative thatimmunity against magnetic fields betaken into consideration as well.Figure 3 shows the results of a studyof different interfaces, published byBoeing some years ago. Case A is thebaseline. You can see that the stan-dard braided shielding provides noattenuation to a magnetic field.

Case B is an example of a typicalmistake made when an unbalancedpair is twisted. Because the returnwire is grounded at both ends, the cur-rent returns through the ground. Theloop area is the wire to ground and noarea reduction is achieved by twistingof the two conductors.

Case E is a coax cable working witha balanced load. In this case, the looparea is determined by the mechanicaloffset between the inner wire and geo-metric center of the shield (i.e., by theimperfections of the coax). Imperfec-tions are rare in quality cables.

Cases F, G, and H illustrate howineffectual the braided shield is inprotecting against magnetic field.

30 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

to the proximity of ground. For exam-ple, wire harnesses are usually run introughs or close to the ground body,such as the aircraft fuselage. The mul-tilayer PCBs should have groundplanes. Up to –60-dB attenuation canbe achieved by running the conductor1.4 mm above the ground. That’sroughly 0.060″, the typical thicknessof a PCB base material. This arrange-ment reduces the interference voltageinduced in the PCB trace by a factorof 1000, or –60 dB.

Interconnect cables are usually sev-eral feet long and farther from theground. Tests are typically performedwith harnesses and cables 15 mm(0.6″) above the ground plane, provid-ing about –46 dB, which is 200× atten-uation as compared to free air. Thusyou can reduce the hypothetical inter-ference voltage from 2000 V to 10 V.

This discussion assumes that youunderstand and provide adequategrounding and bonding. Failing that,your guess as to how the system willreact to EMI is as good as mine. Formore information, please refer to myprevious articles. [1, 3]

Sometimes further attenuation canbe obtained by taking credit for theshielding effect of the location wherethe system is placed (such as the air-craft fuselage). Although there used tobe a tendency to expect about –20-dBattenuation caused by the effects of avehicle body, it is generally not a goodidea to rely on it. Recent studies haveshown that at microwave frequencies,such attenuation degrades. At some

frequencies and locations, resonancecan, in fact, cause an amplitude boostof up to 20 dB.

In summary, you can reasonablyexpect –46 dB attenuation of EMI sim-ply by good multilayer PCB layoutand the cable’s proximity to ground.This leaves you approximately –28 dBshort of the necessary 0.4 V. And keepin mind, it’s good to have an extra12 dB as a safety margin. So ,wheredo you get the additional –40 dB?

WIRE SHIELDINGShielding provides only a partial

answer because, contrary to the popu-lar belief, shielding effectiveness is farfrom constant. First, Figure 2 showsthe results of measurements performedon a high-quality aircraft harnesses. As

you can see, single-shieldattenuation above 1 MHz ishighly inadequate.

The area between 10 MHzand 100 MHz frequencies isgreatly affected by the cablelength. In this particular sit-uation a resonance at cablelength equal to λ/2 is obvi-ous, with shielding effec-tiveness deteriorating downto a measly –15 dB between60 and 70 MHz. At higherfrequencies, especiallymicrowaves, where you usu-ally encounter strong electricfields, the attenuation barelyhovers around –20 dB.

0 dB Reference

57 dB

6 dB

49 dB

6 twistsper foot

79 dB

18 twistsper foot

2 dB

71 dB

64 dB

64 dB

A B C

D E F

G H I

Figure 3—There are many ways to interconnect system compo-nents. But, when the interference comes from a magnetic field,shielding is useless. Twisted-wire pairs are the best solution.

Atte

nuat

ion

[dB

]Frequency [kHz]

Dual BraidSingle Braid

0

–20

–40

–60

–80

–100

–1201.E + 01 1.E + 02 1.E + 03 1.E + 04 1.E + 05 1.E + 06

Figure 2—Shielding effectiveness of a wire is not constant. This diagram shows the results of an actual measure-ment from 10 kHz to 1 GHz on a high-quality aircraft harness with one and two shielding braids used.

Page 34: circuit-cellar2002-05.pdf

32 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

Case I shows the improvement gainedby tighter twisting of the wires.

One often overlooked design aspectneeds to be mentioned here. Whathappens if the shield fails? Even if it’sjust one braid on a double-braidedcable? What happens if the harnessmoves away from the ground plane?These situations are difficult to detectand consequently, such failures couldlay dormant for a long time. You must

make sure that should theshielding lose its effective-ness as a result of corro-sion, mechanical damage,or any other reason, expo-sure to a high-intensityfield will cause a safe shutdown of the system and nopermanent damage. Toassure that, systems areoften high-intensity radiat-ed field (HIRF) tested withshielding degraded or com-pletely removed.

With the cable shieldingcorrectly designed andworking, the expected

–60-dB attenuation will bring theinterfering 10-V signal to 10 mV,which is well below the 0.4-V limit.

CABINET SHIELDINGJust as wire shielding will reduce

interference voltage induced in thewires, so a proper cabinet will shieldthe internal electronics from the EMIthreat. Again, –60-dB attenuationshould be expected, but this is often

degraded by ventilation holes, seams,drainage holes, and such. This degra-dation becomes critical at microwavefrequencies. For example, at 1.2 GHzthe ARINC connector with a 9″perimeter offers 0 dB, and at 120 MHza mere –20 dB of blockage of externalsignals. Ventilation holes of 0.1″ diam-eter degrade shielding of a 6-GHzinterference voltage to only –20 dB.

To achieve the desired –60-dB atten-uation you have to EMI-seal the box,make up for some deficiencies by low-pass filtering of I/O lines, use a dual-cavity design, or all the above. Sealingthe box requires that the cable shield-ing become an extension of the box.That means proper connector backshell termination of the shielding,dual-braided, twisted pairs cables, foilshields, and EMI gaskets in all seams.And, as I’ve already mentioned, properground bonding and avoidance ofground loops is an important part ofthe overall system wiring design.

LET’S BE PRACTICALUnless you’re involved in the

design of safety-critical systems, it’sunlikely that your system will everencounter e-fields in excess of a fewvolts per meter. Most industrialrequirements do not exceed 20 V/macross the entire spectrum.

You’ve already seen that by employ-ing good multilayer PCB layout prac-tice and routing the interconnectcables close to ground you can counton –46-dB attenuation. With 0.4 V asthe maximum allowed interferencevoltage, you should be able to design asystem using only single-shieldedinterconnect cables, low pass I/O fil-ters, and a nonmetallic cabinet withimmunity up to about 100 V/m.

With such a design, the unwantedemissions can still come back to biteyou, especially if the PCB contains afast microprocessor, switching powersupplies, communications links, andsuch. Depending on the certificationlevel requirements, such situationscan be quickly fixed with a conduc-tive coat on the plastic enclosure, alocal shield over the offending compo-nent, a ferrite bead on the cable, or ametal cabinet. Unless your circuitsradiate a lot of energy in UHF and

Photo 1—A dual-cavity box design provides immunity to the mostadverse environment found on aircraft. Notice the box within the boxconcept. The lid has been removed from the clean cavity.

Page 35: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 33

microwave bands, even a layer ofchicken wire will do wonders.

For demanding applications requir-ing immunity in excess of 200 V/mand especially tough immunity andemission measures (above 500 MHz),the cabinet design becomes critical.Although you can solve this problemusing a sealed design, it’s easier saidthan done. With the need for lightningand ESD protection, ventilation andbreathing holes or even displays,switches and connectors, cabinet seal-ing becomes too onerous. The safeassumption is that above 1 GHz, youmust consider the e-field inside thebox to be the same as outside.

The solution is a dual cavity designwith low-pass feedthrough filters. Sucha design is shown in Photo 1. As youcan see, it’s a box within a box. Theouter box, also called the dirty cavity,contains connectors, transient suppres-sors for lightning and ESD protection,and low pass LC filters which then feedthe signals into the inner clean cavity.

Figure 4 shows a typical topology ofa signal line. The LC pi filters have atheoretical slope of –60 dB/decade,usually starting at 1 MHz. Because oftolerances and impedance mismatch,you can’t count on a better than–60 dB total attenuation. This isenough to get rid of interferencepicked up by the short PCB traces andcomponent leads inside the dirty cavi-ty, which you consider open to the e-field. It further attenuates interferencepicked up by imperfectly shieldedinterconnect cables and, most impor-tantly, wipes out the narrow spikesthat are the remnants of the clampedlightning and ESD transients due tofinite speed of those devices.

REFERENCES[1] G. Novacek, “Testing 1, 2…”,

Circuit Cellar Online, July 1999.[2] O. Hartal, “Electromagnetic

Compatibility By Design”, R&BEnterprises, WestConshohocken,PA, 1996.

[3] G. Novacek “The Shocking Truth About EMC,” Circuit Cellar 117–118, April–May 2000.

George Novacek has 30 years of expe-rience in circuit design and embed-ded controllers. He is currently thegeneral manager of Messier-DowtyElectronics, a division of Messier-Dowty International, the world’slargest manufacturer of landing-gearsystems. You may reach him at [email protected].

No less important is the fact thate-fields generated inside the cleancavity cannot radiate into the dirtycavity and can only propagatethrough conduction. With the LC pifilters in the way, e-fields will be wellbelow the permitted levels by thetime they get outside.

A FEW CLOSING REMARKSBringing EMI under control is not as

difficult as it may appear at first.However, the need to keep electromag-netic compatibility in mind from thebeginning of the design process cannotbe overstated. A little attention duringthe early phases of the design will pre-vent huge cost, performance, andschedule nightmares later on.

While concentrating on HIRF, I inten-tionally avoided grounding, lightning,and ESD protection because differentissues need to be considered. Theseissues deserve a separate article, but Ihasten to state that when you have agood design that provides solid HIRFimmunity, the addition of lightningand ESD protection will be simple. I

Pin 1R1 R3

Dirty Clean

F1Filters

Pin 2R4

R2F2

TranszorbsT1 T2

C1 C2

Figure 4—Here’s a look at the typical topology of anI/O line. It provides lightning and ESD transient protec-tion. The residual lightning and ESD pulses as well asthe remaining interference signals are attenuatedbefore entering the clean cavity by the LC filter.

RESOURCER. Goldblum, “The Continuing

Saga of MIL-STD-461/462,”R&B Enterprises, WestConshohocken, PA, 1998.

Page 36: circuit-cellar2002-05.pdf

34 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

ho could forgetPatricia Neal as

Helen Benson in TheDay the Earth Stood Still

uttering the words, “Klaatu baradaNikto” in order to activate the mightyrobot, Gort? How about those nastyflying dessert plates from Earth vs.The Flying Saucers?

Hollywood special effects haveinspired generations of animation androbotics enthusiasts. My own favoritesci-fi flicks gave me the idea of con-structing a low-cost, small-scale DIYanimation system. Similar animationsystems are available commercially(for storefront displays, etc.) but canbe quite expensive.

Although such a system could bedeveloped on a PC or laptop, aportable animation system that fitsnicely on a medium to large robotplatform is also possible. In fact, I’mcurrently using a robot built fromantique Erector sets as a test platformfor this project (see Photo 1). Later, Ihope to integrate the system intosome of my other robot platforms.

The works of Walt Disney, GeorgePal, Ray Harryhausen, and GeorgeLucas provided the inspiration for myinterest in an animation system, butthere are several books and articles

that provided technical inspirationand guidance for the project. [1–3]

FACTOR 1: COSTBecause cost is one of the major fac-

tors for a project of this nature, I usedlow-cost or surplus components (orbuilt my own) whenever possible.Although new relatively inexpensiveboards such as RC servo and DCmotor controllers are available com-mercially, the project costs can besubstantially reduced if a DIYapproach is used for most of the sub-system components.

I elected to build the RC controllerfrom designs freely available on theInternet. The controller uses an inex-pensive PIC16C84 microcontroller.Still, I was tempted to buy the com-mercial Mini SSC II and MotorMindboards (discussed later) because oftheir compact size and specifications.I may go with the commercial boardsin the future for additional devices inmy animation system.

If cost is not an issue and youwould like to get the animation sys-tem up and running quickly, the onlyboard that you may want to build isthe PIC-based joystick controllerboard. The rest of the hardware maybe purchased in assembled form fromsources listed in this article.

SYSTEM HARDWAREThe five major components of the

system are shown in Figure 1. Theheart of the system is the joystickcontroller board. The joystick con-troller is required to record the joy-stick positions/commands and button

Behind the Scenes

wHollywood is one ofthe biggest marketsfor automation sys-tems, but beneath themakeup lies a numberof engineering chal-lenges. Daniel takes ashot at a DIY anima-tronics project thatinvolves a controllerboard, motors andcontrollers, sensors,and a host robot.

Daniel Ramirez

ROBOTICSCORNER

Part 1: Controlling an AnimatronicsSystem

Photo 1—I’m currently using my animation system onmy RC servo propelled AntiqueBot in order to make itdance on the floor.

Page 37: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 35

ton toggle switches used for Record,Play and Calibrate functions. Theboard can easily fit into a small proj-ect box for added protection, or it canbe mounted on the robot platform asshown in Photo 4. The two joysticksconnected to two DA15 D shell con-nectors allow you to independentlycontrol two actuators (servos, DCmotors, stepper motors), and fourrelays (connected to the trigger andfire buttons). The number of actuatorsand relays can be increased if they areslaved to one another or anothermethod is devised to multiplex themwith select control lines.

A 24LC16B serial EEPROM is usedas the primary storage device andprovides storage for up to 2048 bytes,which is more that enough to controlmy slow moving robot platforms.The storage capacity can be easilyincreased with additional serialEEPROMs and minimal changes tothe software for longer, smoother andmore complex animations.

HOW IT WORKS This month, I’m going to cover the

mechanical and electronic functions ofthe animation system. Next month,I’ll go over detailed information onhow the firmware works and provide acomplete functional description.

To build the joystick controllerboard, use the schematic shown in

Figure 2. Parts placementand board fabricationtechniques are not crucial.Wire wrap, point-to-point,and PC board constructioncan all be used for thisproject. I chose to use thePC method of construc-tion for the joystick con-troller board to minimizenoise and to keep boardsize to a minimum.

Start by soldering thepin headers and IC sock-ets onto the Radio Shackprototype board or PCboard. Next, solder the0.1-µF bypass capacitorsas close to the IC socketpower pins as possible.Don’t clip the leads

because they make handy

status (used for training). It computesthe motor commands based on thecurrent position of the joystick ormotion input device and also playsthe commands back to the currentlyselected motor controller.

The second component needed is amotion-training device such as a joy-stick, mouse, trackball, variable resis-tor, or flexible resistor that will serveas a teaching pendant. The currentdesign uses the time constant method(similar to the Basic Stamp’s rctimefunction) to read the position of theselected input device. The firmwaremust be changed to handle resistiveanalog input devices such as a variableresistor or sensor, by taking advantageof the PIC’s A/D hardware.

The third major component can beany combination of H-Bridge motorcontrollers, RC servo controllers,motion controllers, and relay driverboards. An RC servo controller boardsuch as the SERVO84 or Mini SSC-IIis required to drive the various RCservos. An H-Bridge motor controlleris needed when controlling small DCmotors used in toys. A heavy-dutyPWM H-Bridge motor controllerdrives large geared DC motors such asthe ones used in my GardenBot robot(see Photo 2). A motion controller isan expensive commercial board usedin automation, CNC, and commercialrobots where high precision, repeata-bility, and reliability arerequired. The relay con-trol board is for drivingrelays and solenoids.

The next componenthandles sensor feedback.I designed an optionalsensor controller that Iintend to integrate intothe animation system inthe future. [4–5] The sys-tem will be used for sen-sory feedback and to readolder analog joystickslike those used in theRadio Shack ColorComputer. Other typesof sensors (e.g., videocameras) can be used too.

The last main compo-nent needed is a robot,RC Toy, or animation

prop to be animated. Photo 3 shows acomplete animation system configura-tion including the PIC joystick con-troller board, the SERVO84 Board, twojoysticks, and a tilt/pan video plat-form that can be used for home securi-ty or Webcam applications.

JOYSTICK CONTROLLER BOARDThe joystick controller can recreate

movements by storing the motioncommands to a serial EEPROM or to ahost PC/laptop for diagnostics and cal-ibration applications.

The PIC18C452 used for the joy-stick controller board is a great bar-gain at $16 from DigiKey. The onlyup-front cost is the WARP13 or PIC-START programmer required to pro-gram the PIC16C84 and PIC18C452microcontrollers, and a UV eraser toerase them. I included the firmware inhex format (see the Software sectionat the end of the article), so no assem-bly or compilation is required. I usedMicrochip’s 30-day demo PIC18Ccompiler to develop the firmware, butyou would only need it if you want tolearn PIC18C, in order to customizethe animation system application tosuit your needs.

The joystick controller board shownin Figure 2 is a 3″ × 4″ board that’sused to interface up to two joysticks,four joystick buttons (two trigger andtwo fire buttons), and three push-but-

Figure 1—There are five major components used in this animation system.

Page 38: circuit-cellar2002-05.pdf

the 5-V power supply is required bythe joystick controller board and theSERVO84 controller board. Thisarrangement keeps the motor powersupply separated from the controllersto avoid power glitches.

To protect the hardware from shortcircuits, I included an appropriate fusebetween the main battery and elec-tronics and motors in my power sup-ply design for GardenBot. The fuserating depends on the power require-ments for all of the electronics andactuators used in the animation gear. Ialso used a high-current rated toggleswitch to cut power to the motors incase of an emergency.

BUILDING OPTIONAL BOARDSThe joystick controller board can

work with many commercial motioncontrollers as long as they use theserial RS-232 (USART) interface or thepopular I2C interface. But similar DIYboards such as the SERVO84 RC servo

controller board can be easi-ly put together with theinformation given below.

If commercial RC servo orDC motor controller boardsare not used, then followalong as I briefly explainhow to build the RC servomotor controller used forthis article. Mark Sullivan’sSERVO84 controller is thecontroller that I use formost of my RC servo proj-ects. The SERVO84 wasdesigned for a PIC16F84 ICservo controller applicationfor robotics platforms.Sullivan’s code is highlyoptimized and can controlup to eight RC servos usingsimple RS-232 commands.

I designed my version ofthe SERVO84-based RCservo controller by usingMark’s free PIC software(available at mks.niobrara.com/microtools.html) andreverse engineering his codeto build the board and seehow he used the PIC16C84I/O pins. This board hasworked great for my RCservo robotics applications.

36 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

wire wrap or point-to-point posts.Solder other discrete components suchas resistors, capacitors, and diodes asdesignated in the schematic. Screwany PC standoffs to the prototypeboard and glue or solder the RS-232connector directly to the PC board.

Now it is time to check the circuitfor shorts or open lines. Use yourdigital voltmeter to check continuityon all power, ground, and logic sig-nals to ensure that they follow theFigure 2 schematic.

Before populating the joystick con-troller board and the optionalSERVO84 board with the ICs, powerthe board by connecting a 9-V batteryto the positive and negative power ter-minals of the 5-V power supply, andcheck to see if the power LED lightsup. If it does, check for 5 V at the VDD

pin of each IC and V at the VSS pins.After this has been done, you can pop-ulate the board with the ICs and fire itup for the first time.

THE POWER SUPPLYThe schematic for the 5-V power

supply circuit is shown in Figure 3.The power supply is used for the joy-stick controller board and the optionalSERVO84 Board. Check for 5-V outputwhen the 9-V battery is connected tothe power input terminals. Also checkfor 6 V used to power the RC servos(when the SERVO84 is used), andcheck for 12- or 24-V motor powersupply connections.

Try to isolate the 6-, 12-, and 24-Vmotor power supplies from the 5-Vlogic power supply used by the joy-stick controller board and any motorcontroller boards. Include bypass andfilter capacitors and diodes as requiredto suppress voltage spikes generatedby collapsing electromagnetic fieldsfrom the DC motors (if used).

The test platform uses a surplus 6-Vlead acid battery to power the RC ser-vos and the Polaroid 6500 sonar rangerboard. A separate 9-V battery used for

Figure 2—Use this diagram to assemble the joystick controller board. Parts placement and fabrication techniques are not crucial.

Page 39: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 37

The SERVO84 works similarly tothe SSC-II by accepting simple 3-byte servo position commands fromthe serial port from the joystick con-

troller and maintaining the properPWM waveforms every 20 ms,required to keep the RC servos posi-tioned correctly. This board, in

effect, acts as a coprocessor to theStamp to alleviate the extra process-ing required to refresh each RC servoon the joystick controller. TheStamp is then free to perform moreimportant tasks and also increase itsresponse to external events.

Control of up to eight RC servosusing the SERVO84 controller isaccomplished by sending simple com-mand strings via the serial interface.For example, sending “A10”, CR,translates to move servo “A” to posi-tion 10 (where CR is a hard carriagereturn); sending “B20”, CR, translatesto move servo “B to position 20. TheScott Edwards Electronics Mini SSC-IIcontroller described later uses a simi-lar syntax to control up to eight RCservos. Commercial DC and steppermotor controllers also use serial com-mands to ramp up a motor, position astepper or servo and follow trajectoryprofiles. The embedded joystick con-troller software needs simple modifi-cations to the I/O to support the com-mands. Listing 1 shows how RC ser-vos can be controlled using theSERVO84 controller.

The SERVO84 controller board iseasy to make and not expensive ifyou have the tools required, includ-ing a PIC programmer. I use theWARP13 programmer for all of myembedded PIC programming tasks,because it works directly withMicrochip’s MPLAB, which is alsofreely available as a download fromthe Microchip site.

After you’ve assembled or pur-chased the optional boards, connectall the system modules as shown inFigure 1. Be sure to connect all groundand VCC lines between each moduleand make sure that the 5-V and the 6-V RC servo terminals are connected.Check power to any other optionalmodules including the 5 and 6 V forthe SERVO84 board.

CONNECTIONSTwisted-pair or shielded wire con-

nects the various system boards usedfor the RS-232 connections and theI2C connections in the system. TheRC servo connectors can be assem-bled by soldering thin stranded wiresto 0.1″ pin headers that mate with

Listing 1—This PIC C function is similar to the Stamp BSX rctime function that is used to read the joy-sticks. The ReadJoystick function reads the selected joystick using the rctime function and returns theraw x- and y-axis counts for it.

void ReadJoystick(byte JoystickID, word *XCount, word *YCount)

byte PinValue;byte State;

State = 0;

if (JoystickID == JOYSTICK_1)

//Get counts for Joystick #1//Read Joystick X axis using RC circuit code

XJoystickDir1 = OUTPUT;//Set X joystick #1 pin to output

XJoystickPin1 = 0;//Discharge the capacitor

pause(5);//Allow time for discharge

//Make the selected BS2 pin an input//input(Pin);XJoystickDir1 = INPUT;

//Set X joystick #1 pin to inputWriteTimer1_16(0);

//Reset timer 1while(XJoystickPin1 == State);

//wait for Pin to equal state

*XCount = ReadTimer1();//read timer 1

//Read Joystick Y axis using RC circuit code//Make the selected BS2 pin an output to charge capacitor for CR

circuit time//low(Pin);

YJoystickDir1 = OUTPUT;//Set Y joystick #1 pin to output

YJoystickPin1 = 0;//Discharge the capacitor

pause(5);//Allow time for discharge

//Make the selected BS2 pin an input//input(Pin);

YJoystickDir1 = INPUT;//Set Y joystick #1 pin to input

WriteTimer1_16(0);//Reset timer 1

while(YJoystickPin1 == State);

//wait for Pin to equal state

*YCount = ReadTimer1();//read timer 1

Page 40: circuit-cellar2002-05.pdf

38 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

the RC servo connectors. Make surethat the connectors are keyed withthe ground or positive voltage con-nections so power is not connectedwith the wrong polarity. Doing thiswill surely destroy an RC servo as Ifound out.

Mechanical movements that han-dle repetitive motor actions (such asa tilt/pan platform) should be con-nected using stranded wire. If possi-ble, these wires should be coiled toavoid breaking them.

Large DC motors or stepper motorsmay require connections with heavygauge wire, otherwise you will expe-rience burnt spaghetti syndromewhen they are powered. Improperconnections are a definite fire hazardand should be handled accordingly. Afuse, appropriately rated for the cur-rent drawn by the motors, connected

in series with the main power linesis also a good idea.

NOISE IMMUNITYNoise can be a factor when using

RC servos for animations. Sources ofnoise include the RC servos them-selves, the antenna affect of theservo wire connections, and spikesinduced by other DC motors andstepper motors.

The affects of noise are due in partto the sensitivity of the internal elec-tronics. Noise generated by a powersupply spike can cause the servomotor to move unexpectedly. Noisepicked up by the thin RC servo wirescan also cause the RC servos to movewithout warning. This could be a safe-ty concern when these servos are con-nected to a mechanical actuator thatcould injure you or someone standing

Listing 2—Here’s the code to customize the interface commands for various kinds of motion controllers.

*****************************************************************DisplayJoystickReadingsdisplays the x- and y-axis joystick readings. Scaled joystick positions are sent back to the host via the serial port and also sent to the LCD display (if con-nected). These commands can be sampled and saved by the host ormaster controller for play back later (record/play), in order toimplement a teaching pendant.*****************************************************************void DisplayJoystickReadings(byte JoystickID)

//Send joystick servo commands directly to the SERVO84 controller here

//Move servo "C" left wheel

printf("C");dec(XJoystick[JoystickID]); printf("\r");

//Move servo "G" right wheel

printf("G");dec(YJoystick[JoystickID]);printf("\r");

//Move servo "B" platform

printf("B");dec(XJoystick[JoystickID]);printf("\r");

//Move y-axis servo "D" forward/reverse (F-R)

printf("F");dec(YJoystick[JoystickID]);printf("\r");

Page 42: circuit-cellar2002-05.pdf

40 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

nearby. For this reason, make surethat no one is close to an RC servoactuated mechanism. These sameissues also apply to powerful DCgeared motors and stepper motors.

The best way to minimize noise isby using capacitors to filter the powerlines and by also using short lengthsof twisted-pair wire to connect the RCservos to the controller.

THE BATON The joystick is used as the anima-

tion system’s teaching pendant and isused to train various robots and propsin a symphony of complex motionsequences. These sequences are digi-tized by the PIC using the C languageequivalent of the BS2 PBASIC rctimecommand, as shown in Listing 1. Forthis project, I implemented some ofthe features from the teaching pen-dant used on my Heathkit Hero 1robot (see Photo 5).

These days, the PC’s game port isbeing abandoned in favor of the USBport for joysticks and game steeringwheels. This is too bad because thegame port is such a useful device forgame and sensor input. On the brightside, finding a good deal on theseolder joysticks isn’t difficult. For thisproject, any RC-based input devicecan be substituted for the joystick aslong as it meets the IBM PC joystickinterface specifications for the gameport adapter.

Other types of devices such as amouse, flexible resistors (used in theMattel Power Glove), and poten-tiometers could also be used as inputdevices. For some of these inputdevices, the PIC’s A/D hardwarewould have to be used to digitize thepositions. The sensor controller

board can be used by the animationsystem specifically to digitize thepositions and to provide sensoryfeedback from limit switches, tem-perature sensors, and such.

To begin training the animation sys-tem, I just toggle switch S1 to theRecord position and start makingmovements with the teaching pen-dant. The Record LED remains lituntil the EEPROM memory buffer hasbeen filled and the Record switch isswitched off. If the switch it is not setto Off, it will start recording at thebeginning again, overwriting the previ-ous animation sequence. Next, toggleswitch S2 to the Play position, and theanimation sequence will repeat. Theservos or DC motors will be activeduring both of these operations whilethe live action is taking place. ThePlay function will remain in an infi-nite loop unless it is switched off.

The Fire and Trigger LED indicatorschange state when a joystick Triggeror Fire button is pressed (toggled).These LEDs are handy when debug-ging the hardware or verifying if a tog-gle switch or button command hasbeen accepted. They light up duringstart-up indicating that the joysticksare calibrated. They also light up asindicated whenever the Record, Play,or Calibrate switches are turned on.

To bring the animation system tolife, the joystick controller simplytakes the positions read from the joy-

Photo 2—I’m in the process of integrating the anima-tion system into my GardenBot robot, which will beable to learn lawn boundaries when used to seed thelawn this spring.

Photo 3—Here’s a snapshot of a tilt/pan video platformmade from old Erector set parts. The platform includesthe PIC animation controller board, the SERVO84board, and a joystick.

Page 43: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 41

sticks and maps them to com-mands suitable for the motorcontrollers using sets of equa-tions. The first equations areused to compute scale factorsfor the x and y joystick posi-tions that will be used to mapraw joystick positions toscaled joystick positions oractuator commands to obtaintheir widest dynamic range.The window coordinates areentered during calibration andthe minimum and maximumjoystick positions and scale factors aredetermined when the joysticks arecalibrated:

XScale[JoystickID] = (int) ((float)(XJoystickMax – XJoystickMin) /(float) (XWindowMax[JoystickID] –XWindowMin[JoystickID]))

YScale[JoystickID] = (int) ((float)(YJoystickMax – YJoystickMin) /(float) (YWindowMax[JoystickID] –YWindowMin[JoystickID]))

The following set of equations mapsthe selected joystick raw x and ycounts to scaled joystick positions oractuator commands each time the joy-stick is sampled during an animationand sends them to the selected RCservo or DC motor controller via theserial RS-232 (USART) or I2C inter-face. I take advantage of the PIC’sfloating point capabilities to performall scaling calculations.

XJoystick[JoystickID] = (word) ((float)(XJoystickRaw[JoystickID] –XJoystickMin) / (float)XScale[JoystickID] + (float)XWindowMin[JoystickID] )

YJoystick[JoystickID] = (word) ((float)(YJoystickRaw[JoystickID] –YJoystickMin) / (float)YScale[JoystickID] + (float)YWindowMin[JoystickID] )

Digital filtering of the joystick read-ings and motor commands is possible,although I found no need to do it forthis application. If the joysticks orinput devices are purely resistivedevices that cannot use the Stamprctime function, then some form offiltering will be necessary.

The section of code shown inListing 2 shows where to customizethe interface commands for variouskinds of motion controllers. The list-ing shows how commands are sent toSERVO84 controller via serial RS-232interface.

The joystick controller uses thetimers of the PIC to measure an RCtime constant to determine the PCjoystick positions. This is similar tothe Stamp BSX rctime functionshown in Listing 3, which is used toread the joysticks.

The joystick controller uses thePIC’s I2C pins to write calibration data(and record or play animation scripts)to a 2-KB serial EEPROM (24LC16B).This arrangement works similarly tomodern CD players, televisions, andVCRs that allow daily and weeklyprogramming of music and channels.

The controller also uses the PIC’sserial port (USART) for user inputfrom the host and to send com-mands to the motor controllers thatare networked to it. The host modeis mainly used during debugging andcalibration, but the USART couldalso provide more storage capabilitywhen used in conjunction with a PCor laptop host.

The port D I/O lines are polled todetect if a calibration, record, or playswitch has been toggled, or a joy-stick trigger or fire button has beenpressed. The controller also usesLEDs connected to port D I/O linesas visual cues and turns them on oroff depending on the state of theRecord, Play, and Calibrate switches.Pressing the joystick trigger and firebuttons also causes correspondingLEDs to be toggled on and off.

Photo 4—The star of the show in my animation system is the joy-stick controller board shown here. It can easily fit into a small proj-ect box for added protection, or it can be mounted onto the robotplatform itself.

Page 44: circuit-cellar2002-05.pdf

42 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

PWM HARDWARE The PWM hardware of the

PIC18C452 is not used because all ofthe motor controllers that I’m work-ing with are serially driven. TheMCIPC-24 motor control board fromDiverse Electronics generates thenecessary PWM signals by using thePWM of the on-board Stamp BS2.The joystick controller simply sendsthe Stamp the motor commands andit takes care of forwarding them tothe MCIPC-24.

I2C MASTER AND SLAVEThe I2C interface is used to store

data in the serial EEPROM by takingadvantage of the built-in I2C hard-ware of the PIC18C452 and the PICC I2C library. The I2C Master modeof the PIC works well in both the100-kHz (slew off) and 400-kHz(slew on) modes.

There is one aggravating problemthat I have encountered and wouldlike to solve. I would like to takeadvantage of the Slave mode and useit for the main communications inter-face in place of the RS-232. ThePIC18C452 is supposed to support theSlave mode with the C library func-tions, but I have not been able to getthem to work properly using PIC C.

It took some reading, but I wasfinally able to get the Microchipapplication working on a PIC16F877device. [6] I was able to send data tothe ’F877 via the I2C interface frommy application. I have tried to get the

same application to work on aPIC18C452, but to no avail.

After some searching on theInternet, it would appear that I’m notthe only person having these problems.It seems like there are many design-ers having similar problems with theI2C Slave mode using Microchip prod-ucts. Although I have not tried JeffBachiochi’s I2C DC motor controllerboard design, I can see from his articlethat he has solved this problem usinga PIC16C73. [2] In Jeff’s article, heincludes complete assembly instruc-tions and the software. At this point,I’m thinking of assembling Jeff’s boardand trying it out with my animationsystem. In theory, I can connect it tothe PIC’s SDA and SCL lines with thePIC18C452 configured as the master.

MOTOR CONTROLLERSTo control actuators such as RC

servos, DC motors, and relays, thenecessity arises for using a motorcontroller of some type. The type ofcontroller needed depends on thekind of animation or control requiredas well as the power and size require-ments of the selected DC motor orRC servo. For instance, DC motorcontrol requires the use of an H-Bridge controller, a PID controller, oran electronic speed controller (ESC).Stepper motor control requires a step-per motor translator and an H-BridgeIC for unipolar stepper control. You’llalso need a dual H-Bridge IC for high-er torque bipolar steppers.

The main feature that allows anyof these controllers to work with myanimation system is that they mustinclude a serial RS-232 or I2C inter-face, which sends motor commandsto the controller and receives diag-nostic information (status or posi-tion) from it. The command streammust be customized for each con-troller in the firmware, as I’ll demon-strate next month.

The following motor controllersand H-Bridge drivers are ones that Irecommend for use in this project.Most of this information is availableon the Internet, but I have collectedsome of it here for your convenience.My comments are based on what Ihave read in magazines and on the

’Net regarding various controllerspecifications and determining thesuitability of working with my joy-stick controller board.

STEPPER MOTOR DRIVERSA number of DIY stepper motor

controllers can be built around thePIC or Stamp microcontrollers. Youcan use the micros to directly drivethe stepper motor coils using discretecomponents such as power transis-tors and diodes, or by using a highvoltage, high current Darlington tran-sistor array such as a ULN2803.Gordon McComb’s book has a wholechapter dedicated to stepper motorcircuits that can be made from dis-crete components. [1]

Another method is to use a special-ized stepper motor driver IC likeAllegro’s UCN5804 which has workedwell for me over the years. [7] The’5804 is a good example of a special-ized device that replaces a handful ofdiscrete components and is afford-able. It is capable of driving any 5-, 6-,or 8-lead small to medium sizedunipolar stepper motors.

The UCN5408 will operate motorsat up to 35 V and currents of up to1.25 A, all in a 16-pin DIP package. Italso supports the wave drive format(one-phase), two-phase, and half-stepmodes for unipolar and bipolar step-per motors.

Stepper motors may also be drivenusing a board like the Little Step-UStepper Controller sold by HVWTechnologies ($68). The board sup-ports various stepper motor controlformats and features such as velocityand acceleration profiles found inmore expensive boards.

Photo 6—In fact, I use the 24-Vt MCIPC-24 motorcontrol board shown in this photo to control the twoSwiss-made 24-V geared DC motors used to movemy GardenBot.

Photo 5—My Hero 1 robot also uses the animationcontroller system to improve the performance over theoriginal teaching pendant.

Page 45: circuit-cellar2002-05.pdf

The Magnevation motordriver kit (P/N: R121-MTR-DRV-KIT) is a good place tostart. The kit is sold byAcroname for $65 and con-tains all of the parts needed tomake your own H-Bridgemotor driver board. The boardwas originally designed for theOOPic controller as an acces-sory, but it’s easy to adapt theboard for use with other con-trollers. This board is designed

to use a National H-Bridge (included)that allows for 3 A of continuouscurrent capacity. National also sellsthe bare PCB if you already have theseparate parts. [12]

The Devantech 50-V, 20-A H-Bridgemotor driver (P/N: R133-MD03) is alsosold by Acroname. For $77 you get amedium power motor driver, designedto supply power beyond that of any ofthe low power single chip H-Bridgesthat exist. Its main features are ease ofuse and flexibility. It also includes aPWM, RC mode, and an I2C interface.Up to eight modules can be daisy-chained together by specifying aunique address to each. It measures113 mm × 52 mm × 30 mm. [13]

Electronic speed controllers can befound in RC electric model airplanemagazines and they usually runbetween $50 and $200, depending onmake, size, and model. The power effi-ciency and size for these types of con-trollers is amazing. They’re handy forcontrolling the small DC motors usedin functional scale models.

The MotorMind controller is a com-pact board measuring 1.6″ × 1.2″ ×0.4″. According to the specs it can han-dle voltages up to 30 V and continuouscurrents of up to 2 A using PWM. Theboard also includes a built-in tacho-meter capable of measuring up to65,528 Hz. This controller could be con-nected to my animation system usingits 2400-bps serial RS-232 interface.

With a few minor changes to theMotorMind serial motor commandoutput, and by specifying the windowparameters used for scaling the motorcommands during calibration, itshould work fine with the animationsystem. As of now, though, I have nothad a chance to try it out yet. The

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 43

There are more advanced(more expensive) steppermotor drivers used for precisepositioning in plotters, scan-ners, automation, robotics,and scientific applications.The PIC-STEP made by J.R.Kerr is a good example of amidrange stepper motor driv-er. The PIC-STEP Step andDirection outputs can be con-nected to popular steppermotors and drive them withstep rates of up to 50,000 steps persecond. It’s also suitable for use withmicro-stepping stepper motors.

H-BRIDGE CIRCUITSPlenty of designs for light and heavy

duty H-Bridges can be found on theInternet. Several of these look inter-esting, but I have not tried them yet.Application notes from Allegro andNational Semiconductor provide a fewadditional designs for H-Bridge motordrivers. [7, 8] I have used some of thesedesigns for driving DC motors andstepper motors in my own projects andthey have worked well for me.

For this project, I needed a smallmicrocontroller such as an AVR, PIC,or Stamp to drive the H-Bridge toprovide the necessary PWM controlsignals to the H-Bridge and provideserial communications to theautomation controller. The motorcommand format should be made assimple as possible.

The Dallas Personal RoboticsGroup (DPRG) has an interesting H-Bridge design that includes a PCboard. [9] The purpose of the DPRG’sH-Bridge project is to create a PCboard with two H-Bridge circuitscapable of driving motors with sever-al amps of power. The board mustalso be able to interface similar to anL298, be able to be controlled by anon-board MCU, and allow an addition-al serial interface.

The Seattle Robotics Society (SRS)has many articles on robotics andelectronics in their monthly onlinepublication called the SRS Encoder. Ifound an article titled “A Few WordsAbout Motors…” that contains adesign schematic for driving steppermotors with the L293D. [10]

Another way to achieve greaterpower-handling capacity is to use theMIT Handyboard system for drivinghigh power motors. The board uses aTexas Instruments SN754410quadruple half-H driver that com-bines the protective diodes of theL293D chip with the greater currentcapacity of the L293B chip. TheSN754410 is a plug-and-play replace-ment for the L293D.

The high-current H-Bridge driver issuitable for driving high-power DCmotors or stepper motors. The driveris capable of driving one motor withthe maximum current rating of 25 Aat 3.5 V to 17 VDC. The HandyboardH-Bridge driver kit is fully assembled,tested, and available for $38.Specifications of the MIT Handyboardsystem are located on the Web andcontain a PCB pattern and componentplacement diagram for a dual H-Bridgeexpansion board originally intendedfor the MIT Handyboard. [11]

The board is based on theLMD18200 from National Semicon-ductor. The motor battery can be from12 to 55 V, and the H-Bridge can sup-ply a constant current of 3 A and apeak current of 6 A.

DC MOTOR CONTROLLERSSmall DC motors are neatly con-

trolled using an H-Bridge or commer-cial boards. Again, there must be asmall microcontroller driving theDIY H-Bridge to provide the neces-sary PWM control signals to the H-Bridge and provide serial communica-tions with the automation controller.If a commercial motor controller isused, then it should have a serialinterface so it can be interfaced to theautomation system.

Figure 3—Use this schematic to build the 5-V power supply that’s neededto power the joystick controller board and the optional SERVO84 board.

Page 46: circuit-cellar2002-05.pdf

44 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

amount of servo travel from 0° to 90°to 0° to 180°. The board should workwith the joystick controller withminor changes to the serial RC servocommands as shown in the file ani-mate.c located with the other soft-ware for this project on the CircuitCellar ftp site.

The Mini SSC II seems to be quitepopular and is being used in manyinteresting applications. If the MiniSSC II board is used with my anima-tion system, small changes will needto be made to the firmware. Thesechanges will be described in Part 2,of this article. The changes are neces-sary to make the command streamconform to the SSC-II’s servo com-mand syntax.

board can be purchased for $30 from anumber of distributors or directlyfrom Solutions Cubed.

LARGE MOTOR CONTROLLERSLarge DC motor controllers used to

drive heavy-duty geared DC motorsrequire a high current driver board orH-Bridge. Photo 6 shows how I used a24-V MCIPC-24 motor control boardin my GardenBot. I avoided purchas-ing a second MCIPC-24 by using tworelay control cards to switch themotors’ direction and enable eachmotor separately.

The Diverse Electronic ServicesMCIPC-24 costs $40. The companysells other heavy-duty PWM H-Bridge boards for 12- and 24-VDCmotors with up to 30 A of current.The MCIPC-24 requires a motorinterface card to be built or pur-chased from Diverse ElectronicsServices in order to step up the PWMvoltage from the micro to therequired PWM level of 4 to 8 Vrequired by the MCIPC-24.

MOTION CONTROLLER BOARDSThese boards usually include some

form of PID control with a built-intachometer for position and velocityfeedback, along with the ability tospecify trajectory and motion profiles(ramp, trapezoid, sine, etc.). Theseboards are used for CNC and automa-tion applications that require accuratepositioning and repeatability. For thisreason, they are more expensive thanother motor controllers. Thesemidrange boards can cost from $130to $200, and yet they provide thefunctionality of high-performanceboards costing much more.

RC SERVO CONTROLLERSRC servos can be controlled by

using the pulsout function of aParallax Stamp BSX microcontroller,however, you are limited to two orthree servos because of the executionspeed of the PBASIC interpreter. Forthis project, I used the SERVO84 thatwas described earlier in the article tocontrol the servos.

Another option is the Mini SSC IIserial servo controller designed byScott Edwards and sold by his com-

pany for $44. It is a compact andwell-designed surface mount boardthat measures 1.4″ × 2.1″ and is idealfor animatronics and robotics appli-cations such as my project.

This servo controller works simi-larly to SERVO84 in that it acceptssimple 3-byte servo position com-mands via the serial port from thejoystick controller. The Mini SSC-IImay be networked with other MiniSSC-II controllers to independentlycontrol up to 255 RC servos via theserial RS-232 interface. Each nodehas its own unique address thatkeeps the controllers from interferingwith each other.

Another nice feature of this con-troller is its ability to control the

Listing 3—This section of code shows how the joystick data is read and processed. Using C functionsthat I developed, the joystick can be used as a pendant to train various robots, toys, and props with asymphony of complex motion sequences.

void Record(byte JoystickID)

JoystickButtonStateStatus_T LocalButtonStatus; //Local Button Statusword i; //Local loop index //Set start address of available serial EEPROM //EEPointer = EEStartAddress;//Write animation data to EEPROM

for (i = EEStartAddress; i < (MEMORY_SIZE - 6); i += 6)

//Turn on the Record button LED indicating "RECORD"RecordLED = 1;//Read both the x and y joystick pots using the RC circuitReadJoystick(JoystickID, &XJoystickRaw[JoystickID],

&YJoystickRaw[JoystickID]); // Read joystick #1 x and y axis counts//Scale the joystick x and y axis raw pot valuesScaleJoystickReadings(JoystickID);//Display joystick status informationDisplayJoystickReadings(JoystickID); //Store the latest joystick position and button state to

EEPROM or send back it to the hostStoreJoystickValues(JoystickID, i);//Process joystick readings//ProcessJoystickReadings(JoystickID);//Save current joystick positions and button states

OldXJoystick[JoystickID] = XJoystick[JoystickID];OldYJoystick[JoystickID] = YJoystick[JoystickID];

//Delay for sampling period during recording

pause(SamplePeriod[JoystickID]);

ExitRecordLoop://Turn off the Record button LED indicating "END RECORD"RecordLED = 0;

Page 47: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 45

REFERENCES[1] G. McComb “Robot Builder’s

Bonanza,” 2nd ed., McGraw-Hill Professional Book Group,2001.

[2] J. Bachiochi “DC Motor Controlfor the I2C Bus,” Circuit Cellar62, September 1995.

[3] S. Edwards, “The Juggler’sDelight: PIC-based Controller for up to Eight Servos,” issue51, The Computer ApplicationsJournal, October 1994.

[4] D. Ramirez, “Robot SensorController Board—Part 1”Circuit Cellar 135, October2001.

[5] ———, “Robot SensorController Board—Part 2,”Circuit Cellar 136, November2001.

[6] S. Bowling, “AN734: Using thePICmicro SSP for Slave I2C TMCommunication,” DS00734A, Microchip Technology Inc.,2000.

SOURCESMotorMindSolutions Cubed www.solutions-cubed.com/Products/MotorMindB/motormindB_main.htm

MCIPC-24 Diverse Electronic Services(570)-735-5053 members.tripod.com/~divelec/hbridge.html

PIC MicrocontrollersMicrochip Technology Inc.(800) 344-4539www.microchip.com

Basic StampParallax Inc.(888) 512-1024www.parallaxinc.com

H-Bridge DriversAllegro MicroSystemswww.allegromicro.com

[7] Allegro “UCN5804: BiMOS II Unipolar Stepper-MotorTranslator/Driver,” AllegroMicroSystems, Inc., 2002. At www.allegromicro.com/datafile/5804.pdf

[8] National Semiconductor Corp.,“LMD18200 3A, 55 V H-Bridge,” 1999.

[9] Dallas Personal Robotics Group,H-Bridge Driver project,www.dprg.org/l298.html.

[10] Seattle Robotics Society, “AFew Words About Motors…”,www.seattlerobotics.org/encoder/sep97/motors.html.

[11] Specifications of the MIT Handyboard system are located at www.mcmanis.com/~cmcmanis/robotics/h-bridge/h-bridge.html.

[12] Magnevation motor driver kitinformation, app notes,schematics, and related infor-mation can be found at www.magnevation.com.

[13] Devantech H-Bridge drivermotor, Additional app notesand schematics, and technicalsupport for this board can befound at www.robot-electronics.co.uk/htm/md03tech.htm.

Author’s Note: Thanks to my wife,Pamela, for her time and assistancewith this article.

Daniel Ramirez is currently a seniorsoftware engineer with over 10 yearsof experience working on real-timeembedded systems. His hobbiesinclude travel, golf, treasure hunting,and robotics. You may reach him [email protected].

HARDWARE IMPROVEMENTSFuture hardware improvements to

the animation system include using aPIC to transmit joystick informationto a robot using the Sony IR remotecontrol protocol with a 40-kHz modu-lated IR LED transmitter and a SharpIR receiver. I would also like toimplement an RF transmitter andreceiver combined with a Holtekencoder and decoder to send remotecontrol commands to the robot orradio-controlled prop (e.g., two RCcars could be independently con-trolled from each joystick). This appli-cation could also be used in securityapplications for manipulating atilt/pan camera platform.

Other ideas include integrating mysensor controller board. It would workas a coprocessor to the animation sys-tem using the I2C or USART interfaceto provide sensory feedback to the ani-mation system. The I2C bus may beused as a high-speed bus to communi-cate with the PC host or other PICprocessors. This would be helpful inadvanced robot designs that takeadvantage of multiprocessing or net-worked processors.

On of the last improvements I’d liketo make is to integrate a PIC-basedrelay controller board that I recentlydesigned into the animation system soI can switch high-power relays, sole-noids, valves, and muscle wire.

ANIMATING IT ALLUsing the animation system

described in this article, I have inte-grated many commercial and DIYmotor controllers into my variousanimation projects. Although I wasonly experimenting with it initially,I’ve discovered that I can carry out anumber of complex animations withthis system.

Although this series of articles willbarely scratch the surface in the fieldof animation and special effects, I feelthat this article and next month’s area good introduction.

One area that I’ve yet to explore isobtaining sensor feedback during ani-mations. For instance, the MattelPowerGlove provides a sense of 3Dimmersion for the operator using it.Contact and limit switches can also

be used to enhance animations bypreventing actuators from exceedingspecified travel limits. Vision sys-tems have been used successfully inindustry for automobile automation.A true tele-presence applicationwould tightly couple the sensor orvision system with the animationsystem, but describing such a systemis beyond the scope of this article.

In Part 2, I’ll describe the details ofthe firmware and will also show howthe animation system works (includ-ing customizing the serial commandstream for various commercial andDIY controllers). I will also giveexamples of more applications usingthe controller. See you next monthwith more information on the excit-ing world of animatronics. I

Page 48: circuit-cellar2002-05.pdf

46 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

urface-mountdevices are typical-

ly used to minimizecircuit board real estate.

As a result, the boards give you littleworking space between components torework anything. Component gaps aresmall and the leads (and lead pitches)are fine. If you’re developing prototypesor working in a small board shop repair-ing boards populated with surface-mount devices, you might not have thespecialized equipment used for remov-ing and mounting SMDs. Experienceshows that you can, however, do thejob by hand. All you need are basichand-soldering skills for through-holesoldering and a set of hand-solderingequipment. It is possible to effectivelyreplace SMT devices or install socketsand complete other reworking taskswithout special manufacturing tools.

In this article, I’m going to showyou an example of a reworking job.The project involves the removal,cleanup, and replacement of a typicalcomponent, a thin quad flat pack(TQFP). I’ll provide a complete list ofthe hand-soldering equipment you’llneed and a step-by-step explanation ofone way to approach the task. If youhave other equipment or other skills,you might choose a different approach.

I want to note how important safetyis before getting into the project. Inaddition to the normal precautionsassociated with doing close work,such as wearing proper eye protection,always do circuit board rework in awell-ventilated area. Prolonged expo-sure to solder fumes and solvents canbe hazardous. And remember, if youuse solvents, don’t work in areas wherethere are exposed sparks or flames.

EQUIPMENT LIST Doing any work well requires that

you have good tools. Based on myexperience, the equipment list (avail-able to download from the CircuitCellar web site) should give you theright tools to get started. Other mate-rials or tools may work fine, and forother types of components you mightfind other tools are needed. So, feel freeto substitute and experiment. I recom-mend using organic solder, at least inpart because of familiarity. The impor-tant thing is that you use a solder thatyou’re comfortable with, one that willflow well and make good solder joints.Consistency is the critical factor.

In addition to the basics, you’ll findit extremely useful to have a boardvise to hold the circuit board steady.A dental pick, with a 90° bend, provesuseful in positioning loose pads andgeneral probing. Compressed dry air ornitrogen to dry the board speeds thework. And, to provide a truly carefulinspection, it’s wonderful to have anoptical inspection stereo microscopeof 30× to 40× magnification.

THE JOB AT HANDThe rework task breaks down into

three major steps: part removal, boardcleanup, and soldering in the newdevice. You will replace a TQFPdevice that has 48 pins and a 0.5-mmlead pitch. The device’s leads are con-figured in the standard gull wingshape associated with JEDEC-standardquad flat packs (QFP).

The first step is to mount the boardin some sort of holder or vise asshown in Photo 1. If you don’t have aPCB vise, you’ll need to firmly posi-tion it in some way that it is heldsteady while you work on it. This isextremely important considering the

Hand-Soldering Fine-Pitch QFP Devices

sJohn walks us throughthe basics of workingby hand and explainssome techniques thatcan be used forreplacing SMTdevices or installingsockets. His practiceexercise shows usthat most componentsaren’t too compact forhand soldering, atleast not yet.

John Taylor

FEATUREARTICLE

Page 49: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 47

melts, smoothly move thetip to the next lead, andthen the next, making it acontinuous process for theentire side of the IC.

Be sure not to hold theheat on any one lead longerthan necessary. The firstlead will take the longest toheat, but this also heats thewire, which will help meltthe solder on the otherleads. Excessive heat candamage both the IC deviceand PCB pads. You’ll needto practice this technique toget a sense of how fast youcan move the soldering iron

tip. Removing the leads on one side ofa 48-pin TQFP should take about 5 s.

While you are learning, watch forsigns that you are using too muchheat. The most common indicationsare melted plastic on the IC, brownscorch marks on the circuit board, orcircuit board pads begin lifting.

After you’ve removed all of theleads for one side, wet the leads onthe next side with flux and repeat theprocedure. You’ll find it a good idea tocut off the dirty part of the wire wrapwire or use a new piece for each side.

If you are removing a defective IC,or do not need to save the IC beingremoved, you can use a little moreheat (800°F (425°C) in this example),ignoring the fact that this results insome melted plastic and missing gullwing leads. You can see this kind ofdamage in Photo 3b. If you want tosave the IC being removed, however,then you’ll have to minimize the heatyou apply to the leads to just barelyenough to free the lead from the PCB.

small amount of roomyou’ll have to work in andthe narrow margin forerror with a hot solderingiron. It will prove difficultto work carefully and accu-rately if the board is mov-ing around; you can domore damage than good.

To finish preparations,warm up the soldering sta-tion to 700°F (370°C) andclean the solder tip. Makesure that you grounded theESD mat and wrist strap.Because you’ll be workingwith high heat that couldeasily damage the board orother components, it’s a good idea topractice the following procedures on apiece of scrap before working with anexpensive prototype. You’ll quicklydevelop a sense of how fast to movethe solder tip and how long it takes tomake the solder flow. You want todevelop a smooth touch and an intu-itive sense of how quickly you needto move the solder tip over the leads.

When you’re comfortable with theprocess, begin by wetting all of theleads with flux to enhance the initialsolder wicking cleanup. Now, wick upas much solder as possible from theQFP leads like you see done inPhoto 2a. Be careful not to scorch thePCB with prolonged solder heat.

Next, strip approximately 3″ ofinsulation from a 12″ piece of 30-gaugewire wrap wire. The actual length ofthe wire is not critical, because thispiece will simply serve as a tool forlifting leads. However, the wire needsto be long enough so that you canhandle it easily. You’ll want to experi-

ment with different lengths of wire tosee what works best for you. Feed thewire behind and under the leads (seePhoto 2b) along one side of the IC,and then anchor it with a solder tackto a nearby via or component on thePCB (see Photo 2c).

The wire, with one end anchored,will serve as a pry bar that puts pres-sure on the leads as you apply heat.Grasp the unanchored end of the wirewith your tweezers rather than yourhand. The tweezers will provide morecontrol and, besides, the wire is goingto get hot. Make sure you grasp thewire close to the device. Apply the sol-dering iron tip to the device lead thatis closest to your tweezers and beginpulling the wire away from the QFP,slightly upward from the surface of theboard (see Photo 3a). As the soldermelts, gently continue pulling thewire away from the QFP and move thesolder iron tip to the next pin awayfrom the tweezers. The wire will pullthe leads free as the solder melts. As it

Photo 1—Securing the PCB in a board vise is the best way to hold it steady.

Photo 2a—Apply solder flux and then wick the excess solder from the pins. b—Feed the stripped wire wrap wire behind and under the QFP leads. c—Anchor one end of thewire to a nearby component or via.

a) b) c)

Page 50: circuit-cellar2002-05.pdf

48 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

CLEANING UP THE PCBEven if you are careful, removing

the IC leaves the PCB in a bit of amess. Although installing an IC on anew PCB would require little morethan brushing the pads with isopropylalcohol and drying the board, withthis project, you have other work totake care of first. Excess solder andflux have to be removed and any dam-age you’ve inadvertently done to thePCB needs to be repaired.

The first step is to clean the solderpads. You want them to be flat. A cleansolder pad will be a dull silver color, soyou should solder wick the pads untilthey are flat and dull. When you’redone, inspect them carefully. Youmight notice some that have becomeloose from the PCB (see Photo 4). Hereis where the dental pick comes inhandy. Use a pick or some other point-ed object to carefully realign the pad.

A large number of loose pads or lift-ing of a trace indicates that you areusing too much heat, leaving the sol-dering tip on a lead for too long atime, or are pulling too hard on thewire. Again, practice and experimenta-tion will tell you what are doing wrong.

SOLDERING A NEW QFPWith the pads cleaned and aligned,

you can begin aligning the new IC.Carefully place the QFP device on thePCB. You can use tweezers and aprobe to align it or use any other toolsthat suit you. Make sure not to dropthe part while you position the chip.Dropping it can easily damage theleads. Also, bear in mind the dangersof ESD on the IC. Double check the

pin orientation to make sure pin 1 is inthe right spot, and then align the partover the pads as accurately as you can.

Now, you need to secure the pack-age in place or it will move aroundwhile you’re soldering it. You don’tneed as much heat for this operation,so first adjust the soldering stationtemperature down to 700°F (370°C).Put a small amount of solder on thetip of the soldering iron. Hold thealigned QFP in place by applying pres-sure straight down with a pick orother pointed tool, and add a smallamount of solder flux to the cornerleads on two opposite corners of theQFP. After that, solder just those twoleads. For the moment, don’t worryabout any excess solder or whether ornot you have created shorts betweenthe leads. All you want to do is care-fully anchor the aligned chip with sol-der so that it doesn’t move.

When you have the device anchored,recheck its alignment. If the devicehas moved, use a pick or similar toolto adjust it, or if necessary remove itand start over. Now is a good time tobe fussy. Any misalignment at thispoint will cause problems later on. Ifthe alignment is fine, then you areready to solder the rest of the leads.

Photo 3a—Hold the tweezers close to the device and begin heating the lead closest to the tweezers. b—Removingthe device quickly can damage it because of the high heat.

Figure 1—Keeping the iron tip parallel to the pinsbeing soldered reduces solder bridges.

b)a)

Page 51: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 49

First, add a little more solder to thetip of the soldering iron and dispenseadditional flux over all the leads to getthem wet. Touch the soldering irontip to the end of each lead until solderbegins to run up the lead. Holding thesoldering iron tip parallel to the pinsbeing soldered helps reduce the frequen-cy of solder shorts, or lead-to-lead bridg-ing (see Figure 1). But again, don’t worryif you see some solder bridging. Youcan clean that up later, but, of course,there will be less to clean up if you’recareful. There’s always going to be atrade-off between how careful you canbe and how quickly you want to work.

As you go, periodically add smallamounts of solder to the solderingiron tip. After you’ve soldered all ofthe leads, wet them with flux again.This will enhance the solder wickingcleanup. Use the solder wick whereveryou see shorts and bridging.

It’s time to inspect the board close-ly. You’ll need at least 4× magnifica-tion to identify shorts and marginalsolder joints. A good solder joint willhave a smooth melt transitionbetween the device pin and PCB trace.Look for irregularities and rework anypins with defects. This is where it isconvenient to have a 40× stereo zoominspection station.

After the board passes the visualinspection, it needs to be cleaned again.Dip the bristle brush into isopropylalcohol and wipe in the direction of theleads. Use the alcohol liberally, brush-ing well between the device leadsuntil the flux disappears. When it isclean, dry the board with compresseddry air or nitrogen. If you don’t have

either available, shake off excess liq-uids and let the board air-dry for atleast 30 min. to give the alcohol underthe QFP a chance to evaporate. Whendry, the QFP leads should look brightand there should be no flux residue.Clean again if any flux remains.

When you’re satisfied with yourcleaning job, inspect the board forworkmanship. It will be easier to spotany problems on the clean board. Doany rework that appears necessary andclean the board one more time.

When you are finished, yourreworked IC and the surrounding PCBshould look as clean and pristine ascomponents installed in a standardmanufacturing process (see Photo 5).Don’t worry if your efforts fall a littleshort at first, your rework willimprove with practice. I

Photo 4—Make sure that you inspect the pads to lookfor any that have come loose.

Photo 5—When you are done cleaning, the QFP leadsshould be bright and shiny.

John Taylor graduated from ITTTechnical Institute in Austin, Texaswith an AAS in Electronic EngineeringTechnology. He is a product test engi-neering technician for CygnalIntegrated Products. His technicalinterests cover a wide arena. You mayreach him at [email protected].

PARTS LISTTo download the equipment list, goto ftp.circuitcellar.com/pub/Circuit_Cellar/2002/142/.

SOURCEEC1201A Soldering stationWeller(408) 878-9000Fax: (408) 878-2750www.palm.com

Page 52: circuit-cellar2002-05.pdf

50 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

he RobotConversion Kit

(RoCK) is a low-costmodule that can help you

transform an RC car into an autono-mous robot. In the previous issue, weprovided a general description of thekit, covering the functions the RoCKperforms and the top-level choices wemade to implement those functions. Inthis article, we’ll focus on the elec-tronic hardware and explain how weachieve the desired functionality.

We kept the following three goals inmind while designing the electrical

circuitry. For our first goal, we wantedto minimize cost and productiondelays by careful selection of compo-nents. Our second goal was to maxi-mize “buildability” by simplifyingconnections between the RoCK andthe mobility base, as well as by mak-ing the kit tolerant of common wiringmistakes. And lastly, we wanted tomaximize battery life through carefulattention to the power implicationsof design choices.

During its development, the RoCKexisted in three major versions. Thefirst version was a proof of conceptprototype. We developed this versionto gain familiarity with the AtmelAVR processor and to experimentwith possible user interfaces.

The second version became ourentry into the Circuit Cellar DesignLogic 2001 contest. Our entry, shownin Photo 1, was implemented using apin through-hole (PTH) design withcomponents mounted on both sidesof the PCB. With an eye toward com-mercialization, we evaluated thisdesign but decided it was too com-plex to be assembled by the averageuser and too expensive to be assem-bled professionally.

Electrically similar to the secondversion, we optimized the third (cur-rent) version of the RoCK for machineassembly. Version three makes exten-sive use of surface mount technology(SMT). Only a few PTH componentsare used and all but two of these com-ponents are mounted on the topside ofthe board. The PTH components can

RoCK Specifications

tIn the second part ofthis project, Joe andBen take the cover offof their prize-winninghardware and showus what makes theirrobot conversion kittick. After a closerlook, you’ll see whythe Design Logic2001 judges selectedthis project as one ofthe top submissions.

Joseph Jones & Ben Wirz

FEATUREARTICLE

Part 2: The Circuitry

Photo 1—The RoCK enables a builder to convert an RC car or other mobility base into an autonomous robot. Inthe photo on the left, the RoCK implements a robot built on a base borrowed from a tracked RC car. In the photoon the right (b), the RoCK controls a scratch-built robot. The wheels, gears, and motors were salvaged from anold toy and attached to a simple polycarbonate chassis.

a) b)

Page 53: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 51

ON-BOARD INTERFACEA DPDT switch controls power to

the RoCK. The switch enables boththe 9-V logic supply battery inside thecase and the motor battery associatedwith the user-supplied mobility base.

Four I/O lines configured as outputsconnect to the LED display. The LEDsare used to indicate robot status. TheLED enable line (*LEDEN) makes itpossible to multiplex the lines thatdrive the LEDs.

The beeper connects to the AVR’sPD6 line. An interrupt service routine(ISR) associated with Timer/Counter 0is used to toggle PD6 to produce asquare wave for the beeper. The timebetween interrupts corresponds to thehalf-period, H, of the desired beeper fre-quency. The RoCK configures Timer/Counter 0 for eight microsecond ticks.Thus, H is related to frequency (ƒ) by:

Timer/Counter 0’s 8-bit register canstore a number in the range of 0 to 255.Therefore, the lowest frequency thebeeper can produce is ƒ = 62,500/255 =245 Hz and the highest frequency(where H equals 1) is 62.5 kHz.

The RoCK restricts the set of tonesthat it actually produces to thoseapproximating the well-tempered

be wave soldered followingthe SMT step thus elimi-nating hand soldering andreducing assembly cost.

SYSTEMS OVERVIEWThe RoCK’s circuitry is

designed to support theultimate goal of the proj-ect—the creation of a low-cost, high-function,autonomous mobile robot.Light sensors enable aRoCK-powered robot to fol-low a light source or toavoid light and seek dark-ness. The obstacle detector,consisting of two infrared(IR) emitters and two IRdetectors, makes it possibleto sense obstacles and avoidcollision. If a collision doesoccur, the motor current-based collision detector alerts theRoCK so corrective action can betaken. The motor driver provides suf-ficient power to operate the kinds ofmotors commonly found in RC cars.

The user button and potentiometerenable you to configure the kit andadjust certain parameters. The batteryvoltage monitor alerts the user whenbatteries are nearly exhausted. FourLEDs and a piezoelectric beeper givethe RoCK the ability to inform theuser of other conditions as well. Theserial interface provides a high-levelprogramming channel for the RoCK.An advanced programming headerallows programming access to themicroprocessor’s flash memory. Theexpansion header gives you a way toconnect additional sensors and actua-tors to the RoCK.

Details of our implementation aregiven in Table 1. Every I/O pin avail-able on the microprocessor is assignedto a built-in sensor or is brought outto a header for user access.

THE CPUThe key to the high functionality is

the CPU—an Atmel AVR AT90S8535microcontroller. The AVR integratesmany useful functions into one lowpower, low pin-count chip. The RoCKtakes advantage of almost all the fea-tures that the AVR provides.

Several channels of the AVR’s ana-log-to-digital converter (ADC) are usedto monitor the light sensors, userinput, and battery voltage. The AVR’scomparator detects drive motor over-current. Timers built into the chip con-trol the pulse width modulation (PWM)of the motors, generate the tones sentto the beeper, and produce the 38-kHzcarrier signal needed by the IR obsta-cle-detection system. Serial I/O builtinto the AVR is used to connect theRoCK to a host computer for high-level programming and monitoring.Digital I/O lines drive the LEDs anddetect presses of the user button.

The AT90S8535 has 8 KB of flashprogram storage, 512 bytes of SRAM,and 512 bytes of software programma-ble EEPROM. The built-in tasks sup-plied with the RoCK are stored inflash memory; high-level programscreated by users are saved in EEP-ROM. The AVR internally provides allof the circuitry needed to store data tothe on-chip EEPROM. To enable usersto delete the built-in tasks and repro-gram the flash memory, an industrystandard 2 × 5 IDC in-circuit program-ming header is provided.

The CPU gets its clock signal froman external 8-MHz ceramic resonator.The resonator, chosen for its mechanicaltoughness and compact size, requiresno external capacitors or resistors.

Figure 1—At the heart of the RoCK’s circuitry is the Atmel AVR AT90S8535 microcontroller. The AVR provides a high degree ofprocessing power with substantial built-in hardware in a compact form.

Page 54: circuit-cellar2002-05.pdf

This creates a beeper excitation volt-age of approximately 9 V to –5 V, rep-resenting an increase in magnitude ofnearly 300% over direct TTL drive.

To select a built-in or user-pro-grammed task, you press the user but-ton and adjust the user pot. The userpot is connected to ADC channel five,and the user button is connected todigital I/O pin PA4. Both lines are partof the AVR’s port A. Port A lines canbe individually configured for eitherdigital or analog operation.

52 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

scale. That is, for a tone ofa given base frequency (ƒ0),the nth tone of a scale (ƒn)is given by:

The RoCK uses 532 Hz forƒ0. Given that only integervalues of half periods can bestored, the chosen base fre-quency produces a scalewhose tones closely matcha well-tempered scale.

Externally driven piezo-electric beepers are typical-ly rated for a drive voltageof greater than ±10 V. Thesound volume of such abeeper driven directly froma 5-V TTL output is sub-stantially less than the vol-ume produced when thefull driving voltage isapplied. Gear noise from amobile robot base can easily makethe sound from a piezoelectric beeperdriven by this method inaudible. Tocombat this problem, the RoCK usesa pseudo H-Bridge driver to create a14-VPP swing. This is accomplishedby adding a single external transistorand two resistors.

The microcontroller’s output stagecan be driven to ground or 5 V (seeFigure 2). In order to create a negativevoltage swing, an H-Bridge driver,which is capable of reversing the beep-

er’s terminal voltage, is required.With the microcontroller outputdriven low, Q5 is off and currentflows through R12 into the micro-controller’s pin. Thus, the beeper’slower terminal is at a voltage of 0 Vand the upper terminal is at approxi-mately 9 V. With the output drivenhigh, Q5 is turned on. Current flowsout of the microcontroller pinthrough Q5 to ground. The beepernow sees 5 V at its lower pin andclose to 0 V at its upper terminal.

Figure 3—The discrete component transceiver provides a low-cost RS-232 connection to a host PC.

PC transmit

PC TX

PC TX

PC RX

PC RX

AVR TX

AVR RX

AVR TX

AVR RX

PC receive

Stop

Stop+15V

+5V

+5V

+5V

+5V

+15V

+15V

–15V

–15V

–15V

–15V

Marking

Marking

a) b)

Figure 2—The RoCK’s minimal controls provide a straightforward user interface for robot configuration and task selection.

Page 55: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 53

The RoCK implements a novelhalf-duplex RS-232 level converter toenable serial communication whilereducing cost and board space. Giventhe RoCK’s modest communicationneeds, the limitations imposed byhalf rather than full duplex areinconsequential.

It’s a challenge to generate the nega-tive TX voltage required by theRS232C specification without anexpensive charge pump IC such as thevenerable Maxim MAX232. We solvedthe problem by looping back the TXvoltage from the host computer’s seri-al line. The host’s TX voltage is nega-tive in its marking (inactive) state. Forthis method to work, the host mustnot transmit at the same time as theRoCK transmits and the host mustignore the commands it sends whichare echoed back to it by the resistorR2. This scheme produces the halfduplex requirement. See the signaldiagram in Figure 3 for more detail.

A serial speed of 9,600 bps was cho-sen for the RoCK’s serial link. Thebaud rate (in units of bits per second)is set by the UBRR register. The serialspeed is given by the formula:

where ƒCK is the clock frequency.The ceramic resonator is specified

at 8 MHz ± 0.5% at 25°C. The res-onator has a temperature stability of±0.3% over its range of operation anda 10-year aging spec of ±0.3%. In theworst case with parameters at theirleast favorable extremes, the res-onator frequency is 8 MHz ±1.1%, or7.912 to 8.088 MHz.

Using a UBR register setting of 51,the maximum and minimum baudrates are given respectively by:

This is equivalent to a speed of9,600 bps +1.3/-0.9 %, absoluteworst case. These error rates areacceptable for reliable asynchronousserial operation.

POWER SUPPLY AND RESETThe original PTH version of the

RoCK used the common, inexpensive7805 linear 5-V regulator in a TO-92package. A 9-V battery powers thelogic supply. The conversion to sur-face mount components in the latestversion of the RoCK prompted us tosurvey modern SMT linear regulators.

Modern linear regulators are avail-able with dropout voltages lower thanthat of the 7805. Low dropout volt-ages are important because they trans-late directly into increased 9-V batterylife. Most low dropout regulators aremore expensive than the 7805; oftenthey require costly and sometimesscarce low ESR tantalum outputcapacitors. During our search we dis-covered the National SemiconductorLM2931AM-5.0. The LM2931 is a low

dropout regulator that requires only astandard electrolytic capacitor foroutput filtering. In addition, theLM2931 offers a quiescent currentlower than the 7805, is available inSO8 SMT package, and costs onlyabout $0.35 in quantity.

The RoCK provides a 5-V powersupply monitor that puts the micro-controller into reset when the 5-Vsupply dips below an acceptable level.The reset circuit helps prevent erro-neous operation of the microcontrollerduring low battery conditions.

LIGHT SENSORSThe RoCK uses cadmium sulfide

(CdS) photo-resistive elements, photo-cells, to detect light. Among opto-electronic devices, photocells are rela-tively slow to respond to changes in

Table 1—The RoCK’s major systems are implemented using on-chip hardware as summarized in the table. Labelsin the Ports/Signals column follow Atmel’s convention.

System Ports/Signals Description

On-board user interfacePower switch VCC/Batt+ DPDT switch enables logic and motor powerDisplay PC0–3 Four LEDs display robot status Beeper PD6 Interrupt-driven piezoelectric beeper produces

tones of arbitrary frequencyUser potentiometer PA5 (ADC5) Parameter adjustment knobUser button PA4 Momentary contact select switchSerial interface PD0–1 (RXD, TXD) RS-232 interactive connection to host computer

and high-level user programming facilityObstacle detection

Left IR detector PD2 38-kHz IR receiverRight IR detector PD3 38-kHz IR receiverIR emitters PD7 (OC2) Chip automatically generates 38-kHz modula-

tion for two series-connected IR emittersLight sensors

Left photocell PA0 (ADC0) Analog inputs enable detection of lightRight photocell PA1 (ADC1)

Collision detectionMotor current PB2 (AIN0) Analog comparator compares set point with

motor current to detect collisionCurrent set PB3 (AIN1)

Battery monitorsMotor power PA2 (ADC2) Monitor for motor supply battery voltage Logic power PA3 (ACD3) Monitor for logic supply battery voltage

Motor outputMotor PWM PD4–5 (OC1B, A) Chip automatically generates PWM for dual-

channel motor driverMotor direction PB0–1

Auxiliary IOUser digital PC0–7 Eight digital IO lines availableUser analog PA6–7 (ADC6–7) Two analog channels available

Advanced programmingProgramming header PB5–7 (MOSI, MISO, SCK) Enables user to program flash memory

Page 56: circuit-cellar2002-05.pdf

54 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

illumination. Rise times forCdS cells can exceed 35 ms.However, the fact that photo-cells are slow to respond elec-trically to changes in illumina-tion is of no consequencegiven that the robot is evenslower to respond physically tochanges in commanded veloci-ty. The robot responds slowlybecause of physical limitationsimposed by mass, motortorque, and so on.

Photocells are two-terminaldevices that change theirresistance in response to light—morelight means lower resistance. Each ofthe RoCK’s two photocells is connect-ed in a resistive voltage divider suchthat increasing illumination causesincreasing voltage on the signal line.The photocells are mounted at thefront of the circuit board; one isangled to the left and the other to theright. Thus, the differential signalbetween the left and right photocellscan be used to guide the RoCK towardor away from light.

OBSTACLE DETECTIONThe obstacle detection system is

composed of two IR emitters connect-ed in series and two IR receiver unitsconnected independently. Because cur-rent requirements arelow, the emitters are driv-en directly by AVR linePD7 (OC2). The activelow signals from the leftand right IR receivers areconnected to lines PD2and PD3 respectively.

The emitters shine IRradiation diagonally out-ward from the robottoward the left and right.If an obstacle is present,some of the radiation isreflected back into one orboth receivers. An activesignal from a receiverindicates that an obstacleis present on the sameside of the robot as thereceiver. Active signalsfrom both detectors sug-gest that an obstacle isdirectly ahead.

The IR receivers are the same asthose used for detecting remote con-trol signals for TVs and other con-sumer electronics devices. Thedetectors have a built-in lens, photodiode, automatic gain control ampli-fier, band-pass filter, and demodula-tor. To function properly, the IRreceivers must see an infrared signalwith a 38-kHz carrier modulated ataround 1 kHz. AVR Timer/Counter 2is used to generate the 38-kHz carriersignal automatically. Timer/Counter 2is configured to count up to a numbercorresponding to a half period of thedesired 38-kHz frequency. When thecounter matches this number, linePD7 toggles and the counter resets.Code in the RoCK’s main software

loop superimposes the 1-kHz modu-lation on the 38-kHz carrier signalby alternately activating and deacti-vating the connection betweenTimer/Counter 2 and line PD7. Theconnection is switched approximatelyevery 500 µs.

MOTOR DRIVERThe motor driver has been one of

the more difficult design challengespresented by the project. After someexperimentation, we settled on thefollowing specifications.

We required dual-channel with amaximum continuous current of500 mA per channel. The input volt-age range had to be 3–15 VDC.Another goal was minimal quiescent

current consumption. Wewanted a device capableof being interfaced to theAVR’s internal PWM gen-eration hardware. And, itshould provide bumpsensing and over-currentprotection. The lastrequirement regardedcost: less than $1.50 in1000-unit quantities.

One of the motor-driv-er IC favored by manyhobby robot experi-menters is the Unitrode/STMicroelectronicsL293D. The L293D isappealing because it canbe configured as a dualH-bridge driver, comesin a DIP16 package, andis available for less than$1.50. Also, the L293Drequires minimal exter-

Figure 5—A pair of IR detectors and emitters are combined to form a wide-angle collisiondetection sensor at the front of the robot. CdS photocells enable light level detection behaviors.

Figure 4—The RoCK implements a low drop-out linear regulator to maximize battery life. SW2 switches power to the logic sup-ply and motor driver. A voltage detector monitors the 5-V supply and resets the microcontroller during a low-voltage condition.

Page 57: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 55

nal parts. The first two versions ofthe RoCK utilized this chip.

The main shortcoming of the L293Dis quiescent current. In the worstcase, quiescent current draw is 60 mAfor the logic supply and 24 mA for themotor battery supply. The L293Dalone would discharge a standard 9-Valkaline battery in a few hours, whichwe deemed unacceptable. The L293Dalso failed to meet our minimummotor battery voltage requirement.With the L293D ruled out, wesearched for other ICs that might bet-ter fit the requirements for the com-mercial version of the RoCK. TheVishay Siliconix Si9986 came closest,matching all of our requirementsexcept cost—over $4 for a pair.

Frustrated by the lack of an appro-priate chip we decided to design amotor driver made of discrete transis-tors. We determined that a bipolartransistor design would be adequatefor our low current requirements. Abipolar-based design would also beless expensive and avoid other com-plications of a MOSFET design.Details of the discrete bipolar motordriver we settled on and the processwe followed to design it will be pre-sented in a future article.

The motor driver is protected fromexcessive current draw by a 1.25-Apositive temperature coefficient (PTC)fuse that can be reset. The fuse isover-sized to prevent nuisance tripsand it protects the motor driver fromtwo of three possible fault conditions.A fault condition opens the fuse onlyif the fault current flows through thefuse. This condition occurs when themotor leads are shorted together orwhen one of the leads is shorted tothe battery positive rail while thatlead is being driven low. The fuse willnot open if one of the motor leads isshorted to the battery ground while itis driven high. In this case the faultcurrent does not flow through thefuse. A shorted motor lead is the mostcommon fault condition. The chosendesign provides a reasonable level ofprotection against user faults, withoutexcessive complexity.

Total motor current is monitored todetect collisions. When the robot col-lides with an obstacle, the motors pro-

duce increased torque. This torqueresults in increased current draw inresponse to the additional load createdby the robot pushing against theobstacle. By monitoring the totalmotor current draw, the RoCK candetect collisions with obstacles.

Current draw is determined bymeasuring the voltage drop across thePTC fuse. Here’s how it works: thelarger the current drawn by the motor,the higher the voltage drop across thePTC. The initial resistance of the PTCis specified to be 0.07 Ω to 0.25 Ωdepending on whether or not the fusehas been previously tripped.

You can connect the RoCK to avariety of different-sized motors withvarying current requirements. Thus,to ensure reliable collision detection,the RoCK must provide the ability toadjust the current trip point. This isaccomplished by using a potentiome-ter voltage divider to form a user-setcurrent trip point reference voltage.The reference voltage is connected tothe negative AVR comparator input,and the voltage drop across the PTC isconnected to the positive comparatorinput. When the current exceeds theuser set point, the processor detects acollision. (Software filters out momen-tary over-current conditions.) DiodeD11 limits the voltage present at theAVR’s input to a value no greater thana pair of diode forward voltage drops.This design protects the AVR from thehigher-than-logic-level motor voltagethat could damage the AVR. ResistorR42 and capacitor C12 help filter outspurious current spikes.

LAST ITEMSEach of the logic and motor batter-

ies is connected in a voltage dividernetwork. The center tap of the volt-age dividers connects to lines PA2(ACD2) and PA3 (ACD3). Code in theRoCK’s main loop polls the ADC andstores the battery voltages for othercode to examine.

Expansion ability is provided via theAuxiliary I/O header. Eight digital I/Olines (PC0–PC7) and two lines thatcan be configured as digital I/O oranalog inputs (PA6 and PA7) are pres-ent on this header. Lines PC0 throughPC3 are shared with the LEDs.

The Advanced ProgrammingHeader enables the experienced userto program the RoCK’s flash memo-ry. Lines PB5, PB6, and PB6 plus*RESET are provided on the headerfor this purpose.

We’ve now seen many of the grittydetails of the RoCK’s electronics. Inthe next issue we’ll delve into what isperhaps the RoCK’s most distinguish-ing feature—its behavior-based pro-gramming scheme. I

Dual-channel motor driver

MOT_PWRPTC resettable fuseRmin = 0.07 ΩRmax = 0.25 Ω (Post trip)

MOT_CURRENTR42

100k

F1

SM

D12

5

C12

3

D112

1

Figure 6—The RoCK’s motor driver has built-in shortcircuit detection and also provides collision detectionthrough motor current monitoring.

Authors’ Note: We plan to offer RoCKfor sale. Please check our web site,www.wirz.com/rock/, for availabilityand additional information.

Ben Wirz also grew up in a small townin the Missouri Ozarks. He studiedphysics and electrical engineering atWashington University in St. Louis,and graduated in 1997. He is current-ly employed as a senior electricalengineer by iRobot in addition to run-ning his company, Wirz Electronics.You may reach him at [email protected].

SOURCEAVR AT90S8535 MicrocontrollerAtmel Corp.(408) 441-0311Fax: (408) 436-4200www.atmel.com

Joseph L. Jones grew up in a smalltown in the Missouri Ozarks. Hestudied physics at MIT and receivedan BS in 1975 and an MS in 1978. Hetook a trip around the world, workedat the MIT Artificial Intelligence Lab,and is now senior roboticist atiRobot Corp. You may reach him [email protected].

Page 58: circuit-cellar2002-05.pdf

56 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

ike a shark, Iam constantly on

the prowl. Sharks areat home in the water. I

swim the oceans of technology hopingto find yet another interesting and use-ful embedded device. Shark food comesin a wrapper of scales. My sustenanceis contained inside anti-static bagspacked in cardboard boxes adornedwith UPS and FedEx labels. If yourfins and teeth look like mine and yourfood comes from the back of a deliverytruck, you’ll definitely want to join meas I venture into Atmel-blue waters.

IN THE BEGINNINGMost manufacturers offer a starter

kit and as the name implies, it’s agood place to start if you’re not famil-iar with the company’s products. Itjust so happens that I have an AtmelSTK500 starter kit here on the Floridaroom bench. Since I began employingthe services of small microcontrollerson the Internet, I’ve been constantlylooking for microcontrollers withample amounts of RAM and programmemory that can house a robust C-based Internet application.

A lot of people talk about howthey’re able to stuff Internet protocolstacks into tiny microcontroller mem-

ory spaces. Even though the protocolstack can exist and work in the con-fined memory spaces, the dynamicdata payload that’s transferred fromthese micro-sized protocol stackimplementations is relatively small.There just isn’t enough SRAM payloadbuffer area to build a large dynamicmessage and just as little space left inthe program memory to “can” a set ofsimilar messages. The simple fact isthat you need substantial microcon-troller SRAM resources if you want todynamically send more than a fewcharacters per packet.

You may be thinking that I’ve lostit and that you can write code to pushthe message into the pipe on the fly orconjure up a code-decode data com-pression scheme and thus erase thebuffer memory constraint. That’s nice,but keep in mind that nothing is freein the world of embedded computing.To build those dynamic messages inan SRAM-constrained microcon-troller, you’ll use more program mem-ory bytes to compensate for the lackof buffer SRAM bytes. And that’s whymy eyes are on the Atmel ATmega16and the ATmega163.

Both devices contain 16 KB of self-programmable flash program memoryand 1 KB of internal SRAM. Anotherfeature that tickles my shark senses isthe ATmega’s affinity for applicationswritten in the C language. TheATmega16 and ATmega163 are medi-um-sized fish, but in deeper waterslurks the ATmega128 with 128 KB ofprogram flash memory and 4 KB ofSRAM. Right now I’m fishing with

Taking a Swim withAtmel’s STK500

lReady to dive in andtake a closer look at afew of the ATmegaxxxofferings from Atmel,Fred found no betterplace to start thanwith the starter kit. Hefound that there’splenty of processingpower and beforelong, he was into thedeep Atmel-bluerealm of embedded.

Fred Eady

Photo 1—The color-coding scheme on the AtmelSTK500 starter kit assumes you were present the dayyour kindergarten teacher taught the basic colors.Color coding the numerous sockets and programmingheaders eliminates some of the confusion, as theSTK500 is one busy piece of electronic equipment.

APPLIEDPCs

Page 59: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 57

button bank, and the 10-pin cables arealso used in high-voltage programmingmode. A 6-pin jumper cable is includ-ed to patch the 6-pin ISP programmingheader into the AVR socket farm. TheAT45D021 communicates using SPIand there are three sets of two-con-ductor patch cables to make that con-nection. The spare RS-232 channel isalso a two-conductor patch.

The peripherals and the mastermicrocontroller (an AT90S8535) canbe found at the end of the board thatsports the DE9 shell connectors. Thissection of the STK500 developmentboard is well populated. Withoutgoing into component-by-componentdetail, I can tell you that the mastermicrocontroller is responsible for gen-erating the VTARGET and AREF voltage

levels using PWM outputs that arepassed through low-pass filters to theadjust pins of a couple of LM317 lin-ear voltage regulators. A master clockfor the AVR targets also originates inthis area of the board.

The DE9 shell connectors implyserial communications capability, anda MAX202 does the RS-232 voltagelevel conversion that allows theSTK500 development board to attachto a desktop PC running AVR Studio.Atmel likes to call AVR Studio thefront-end software.

Although I’m primarily interestedin getting the ATmega16 online, Idecided to keep the AT90S8515 sock-eted and run the LED test. I pressedeach of the eight push buttons andwith each push got a different light

light tackle in a johnboat, so we’ll onlyconcern ourselves with the ATmega16,ATmega163, and AT90S8515.

The AT90S8515 comes mounted onthe Atmel STK500 and is loaded witha blink-the-LEDs test program. Youmay be familiar with the AT90S8515because it’s the microcontroller thatpowers iReady’s µInternet device.

My immediate goal is to bring fullC-based Atmel microcontroller capa-bility to the table and bring you alongfor the ride. As I get deeper intoAtmel waters, I’ll trade in the flat-bot-tom boat for an ocean-going model togo after the really big fish.

THE ATMEL STK500The meat of my Atmel STK500

starter kit is shown in Photo 1. TheAVR-supporting electronics are physi-cally and logically separated into threedistinct areas on the printed circuitboard. The most colorful area is where

the target AVRs reside.You can program a vari-ety of AVRs in thesecolor-coded sockets andthen run the freshly pro-grammed applicationwithout having to movethe target AVR.

Each family of AVRshas a different set ofprogramming pins andpossibly a different pro-gramming algorithm. Toaccommodate the pro-gram mode differences,the Atmel STK500development board

associates a color-coded set of pro-gramming header pins with a similar-ly colored set of target AVR sockets.The STK500 board has provi-sions for in-circuit serial pro-gramming (ISP), high-voltageserial programming, and high-voltage parallel programming.

High-voltage serial program-ming is used on the smallerdevices that don’t have enoughpins to be programmed with theparallel method. The “high volt-age” is actually 12 VDC and isusually applied to the RESET pinof the AVR. In addition to thetarget AVR sockets, jumpers toinclude or exclude target AVRoperating and reference voltages,oscillators, and crystals are alsofound in the color-coded area.All of the AVR socket signals arebrought out to expansion headers incase you have bigger plans than the

STK500 development boardcan handle on its own.

A set of eight LEDs andcorresponding push-buttonswitches are located at theend of the board oppositethe 9-pin D shell connec-tors. There are also headersfor target AVR I/O ports,the spare RS-232 port, andthe AT45D021 2-Mb Data-Flash. A collection of inter-connect cables is includedto patch in the AVR portsand peripherals. Two 10-pinjumpers are used to connectI/O ports to the LED/push-

Photo 2—The AVR Studio panel looks barren when there are no files orprojects open. However, its ability to interface and control the target AVR isdemonstrated by its invocation of the STK500 programming window. As wego further, the importance and power of the AVR Studio will become obvious.

Photo 3—The two larger ribbon cables are connecting theLEDs and push-button switches to the AT90S8515’s I/O portsB and D. The smaller ribbon cable enables ISP programmingusing the AT90S8515’s internal SPI interface.

Photo 4—All I needed to do was load a live file and almost all of theAVR Studio lights came on. The AVR Studio did not sense a hardwareemulator or STK and automatically reverted to Simulator mode.

Page 60: circuit-cellar2002-05.pdf

AVR Studio V.3.53 is designed to enablethe Atmel STK500 board without theneed for any additional software. AVRStudio also includes firmware to updatethe development board and AVR in-circuit emulators when necessary. AVRStudio checks the attached device’sfirmware level and prompts the user ifa firmware upgrade is required.

I’ll use some available resources tobring AVR Studio to life and demon-strate some of the concepts I’ve dis-cussed. The larger AVR Studio panelyou see in Photo 2 is the first thingyou see when you invoke the AVRStudio program. At this point, myAtmel STK500 development board isconnected to a PC via the RS-232CTRL connector on the board. As youcan see in Photo 3, I have alsostrapped the ISP6PIN header to thered SPROG3 header because theAT90S8515 resides in a red socket inthe AVR target area.

A mouse click on the AVR IC iconin the AVR Studio tool bar invokes theSTK500 programming window. As youcan see, I’ve chosen the AVR target tobe the AT90S8515. I’ve strapped theSTK500 development board for ISPProgramming mode and have selectedthat mode in the STK500 programmingmode panel as well. I’m not going toprogram the AT90S8515. Instead, I’mgoing to read the demo code it con-tains into a file called blinky.hex.

The final uploaded file locationis specified in the Flash panel of theSTK500 programming window. Aclick on the Read button in theFlash panel turns the green STK500board status LED yellow while thecontents of the ’8515 are read. Thedebug window containing the hexand disassembled code from the’8515 in Photo 4 confirms thatpush button number seven doesnothing in the blinky demo code.

AVR Studio opens up memory,processor cycles, I/O states, regis-ters, and even a terminal I/O win-dow. Now that you have a basicidea of how the AVR Studio andSTK500 board work together, let’smove beyond blinking LEDs andassembler mnemonics and swimtoward deeper water.

IMAGECRAFT AVR C COMPILERJust like many of you, I cut my

embedded teeth writing assemblerapplications. Then, one day I decidedto try C on an important embeddedproject and I’ve never returned to pureassembly coding. The problem is, withC you can choose the wrong compilerfor your needs. With that in mind, Ibegan searching for a suitable AVR Ccompiler on the Internet.

I wanted an AVR C compiler thatcould handle all of the AVR familieswithout having to purchase extra costmodules or build kludgy workarounds.It would also be good if the AVR Ccompiler supported the STK500development board directly. I don’t

58 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

pattern on the LEDs. On my sec-ond run through the push but-tons, I noticed that the seventhpush button did nothing. Whenthere’s potential trouble, it’s timeto go against the grain and readthe User Guide. The final pages ofthe guide hold the code for theLED demo, and there I found outthat push button number seven isnot included in the LED algo-rithm. Satisfied that my STK500development board was in goodworking order, I went to Atmel’sweb site and downloaded the lat-est version of AVR Studio.

AVR STUDIOAs of this writing, the latest ver-

sion of AVR Studio is V.3.53. TheAVR Studio is an integrated devel-opment environment (IDE) thatconsists of an editor, a project manager,an assembler and compiler interface, asimulator, and a debugger. The AVRStudio editor is capable of being cou-pled with almost any AVR compilerand C or assembler source code can beedited in the debugger source window.

If AVR Studio recognizes anythingthat is hanging off the PC’s serial port,the program automatically puts itselfin a mode to accommodate the serial-ly attached peripheral. For instance,AVR Studio can sense the presence ofmy Atmel STK500 development boardor an emulator and act accordingly.

To keep things simple, the interfacefor the AVR Studio simulator is identi-cal to the hardware emulator interface.

Photo 5—This small program demonstrates that there is power behindthe simplest of statements. It’s obvious that real embedded program-mers solving real-world problems wrote the ICCAVR C compiler.

Photo 6—The AVR Fp & Calc Tool program also calcu-lates the value to reload into the timer count registers incase you want to generate an interval with that method.I played with the Baud Rate Calc to get an idea of howfast I could run a serial port with a 32-kHz clock.

Photo 7—This is really simple to use. It even includesan option to automatically program the target part aftera successful compile.

Page 61: circuit-cellar2002-05.pdf

PCI/ISA/PCMCIA/PC104/

VME/cPCI format boards.Software drivers for most OS’s. CAN/Ethernet bridges, etc.

Saelig Company brings you unique,easy-to-use control and instrumentationproducts to USA, mostly from Europe,but now from worldwide. (Need USAsales help - overseas companies?)

Our customers commenton our unrivalled FREEafter-sales support.

“Hi - I’m Alan - you can email me [email protected] for freeadvice for your control ormeasurement problem.”

Saelig Co. Inc.585-425-3753 • Fax: -3835

www.saelig.com • [email protected]

• Plug directly into PC— self powered!

• Drive any RS422 or RS485 devices.

• Send control and data 100s of feet!

K422/K485, 25pin > 9pin . . . $69K2 9pin > 9pin . . . . . . . . . . $69

Isolate RS232/422/485 signals K4xx-ISOL 25pin

self-powered . . . . . . . . $139NEW! 9p-9p K3-ISOL - $129!

!"#$

• Store analog/digital/GPS or CANbus dataon FlashATA cards -read on your own PC!

• > 100 customizablesoftware modules—finish REALLY quickly.

• 8ch 10bit A/D, 33 I/Os, I2C, 2 xRS232, interrupts, sleepmode,pre-emptive multitasking, easy toattach LCD or keypad.

• CANbus adapter—recompile or logdata over huge network!

%&&'%((! ! "&&#&

" #)#ADC-10 8-bit $85 through ADC-216 16-bit $799—displayscope, spectrum and meter simultaneously. Connect to PC

parallel port and startgathering/displaying dataimmediately!

• EnviroMon temperature logging/alarm system standalone or with PC.

• TH-03 thermistor-to-PC converter

• TC-08 8x thermocouples

NOW!

GPS

Logg i ng

check out what’s new at www.saelig.com!

Industry-standard card for PC’s ISA/P-port/PCI versions2-6V I2C bus versions• Master, Slave or Bus monitor

• Control or program I2C devices

ICA90/93LV - PICA90/93LV PCI90/93LV

- from $299!

USB ic’sUSB <> RS232 easily!!

US232: USB <> RS232 cable $35

SMD PCB adaptersfor prototyping

“How to I 2C”

www.saelig.com

by Janzfor all com puters

DrDAQ plugs into a PC for usefuldatalogging at school, college,industry. Built-in sensors for light,sound, temp. or add pH sensor andrun one of the many suggestedscience experiments! - only $99!

%%*+"#%&&

www.drdaq.com

Customer l ist inc: Intel,Compaq, Philips, NEC,Kodak, Nokia, US Military,Microsoft, Dell, Xerox,Universities, T.I., Dalsa,Harris, Litton, Sony, J&J,Thomson, H-P, Agilent, etc.

NEW!!12-bit

100Ms/Sdual-chscope

adapter

ADC-212/100

$1015!!

,-.+'/+0%1-+

BASIC Tigers aretiny multitaskingcomputer systemsfor quick project

d e v e l o p m e n t .Powerful features and low

prices make Tigers a numberone choice for developers: super-fast

development cycle, high reliability products,>100,000 instructions/s, up to 38 I/O lines,A/D, D/A, I2C, SPI, , text/graphic LCD inter-face, up to 50,000 lines of BASIC, RTC/watch-dog timer. Easy connection and software forExpansion Modules for CANbus, TCP/IP fornet-access, opto-I/O, 64 analog inputs, 64 dig-ital outputs, high-current outputs, etc.

TIGER Starter Kits start from $159!

NEW! Euroquartz filters/crystals!

)#2"3#

BIT®

power & dataon two-wire

control network

2-year self-containedDATALOGGERS for volts, switch-

closures, events, flow, pressure, etc.See www.abidata.be for details

Page 62: circuit-cellar2002-05.pdf

60 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

plan to delve into the 8-pin AVRdevices so lack of support for thosedevices wasn’t a problem.

I didn’t have to look far.ImageCraft’s ICCAVR supports all ofthe AT90Sxxx and ATmega devicesincluding the FPSLIC, but not thetinyAVRs and ’1200, which are sup-ported by another ImageCraft product,ICCTiny. Having used other embeddedC compilers, I knew that I neededinline assembly capability and strongstring handling support. Because theAVR targets will be performing bit andbyte I/O operations, the AVR C compil-er I chose needed to have a good handleon that functionality as well. A robustset of AVR-specific library routines ismandatory seeing as I don’t want towrite all of the standard AVR I/O rou-tines from scratch or in assembler.

As it turned out, ICCAVR offeredmuch more than I expected. I optedfor the professional version as it con-tains a unique Code Compressor opti-mizer that could come in handy whenthe larger AVR TCP/IP implementa-tions come to call. The professionalversion also has some interesting fea-tures that are being developed for AVRStudio. These additions will be avail-able via a maintenance upgrade whenthey show up online.

The ImageCraft AVR C compiler hasits own IDE that supports long filenames and acts much like the AVRStudio IDE in that there is an integratedproject manager, C editor, ANSI termi-nal emulator, and an application builderto generate peripheral initializationcode. ICCAVR also supports symbolicdebugging in the AVR Studio.

The designers of ICCAVR realizedthe importance of efficient string han-dling in embedded microcontrollerapplications and included several fla-vors of the printf function to suit dif-fering environments. The bestICCAVR feature is the price. Even theICCAVR maintenance prices are waybelow sea level.

I figured I would forego discussingthe blinking lights as I enteredICCAVR territory, but the ICCAVRAT90S8515 demo program uses theLEDs to make its point as well. Again,I’ll use the AT90S8515 that’s alreadyon the STK500 development board.

Take a look at the AT90S8515 pro-gram 8515intr.c in Photo 5. At firstglance, the program seems simpleenough. What you don’t immediatelysee is the functionality packed intothese seemingly simple lines of text.The first line of code is a standardinclude statement referencing aninclude file filled with AT90S8515 I/Oand register definitions. What youdon’t see is a reference to anotherinclude file named io8515v.h.

The C header files io8515.h andio8515v.h have been designed todefine consistent global names forinterrupt vector numbers and use theAVR datasheet names for clarity. Forinstance, Listing 1 is a definition tablefor the AT90S8515 interrupt vectornumbers taken from the C header fileio8515v.h. The second line of code,

#pragma interrupt_handler timer:5

generates the interrupt vector codebased on the interrupt vector numberfound in io8515v.h. The pragmastatement also declares the functiontimer() as an interrupt handler.Knowing that the timer function isnow an interrupt handler, the AVR Ccompiler generates a reti (return frominterrupt) instead of a standard ret forthe timer() function turned interrupthandler and saves and restores all ofthe registers the timer() function uses.

The main() function simply sets upthe AT90S8515’s port B, loads Timer1with values for a 100-ms interval,enables the Timer1 Compare A inter-rupt, starts the timer, and runs forever.The timer() interrupt handler is calledevery 100 ms and simply incrementsthe value of port B, thus producing abinary counting pattern on theSTK500 development board’s LEDs.

Note here that the interrupt handlerfunction timer() is written entirely inC. Counting cycles to make delays orintervals is not one of my favoritethings to do when it comes to pro-gramming. Obviously, as you can seein Photo 6, Jack Tidwell and I havesomething in common. Thanks toJack, the values loaded into the com-pare registers to affect the 100-msinterval were not computed by hand.ICCAVR has a built-in calculationtool that does it for you. The AVR Fp &Calc Tool is shown providing thecompare register values for a 100-msinterval with the STK500 board’s 3.69-MHz target clock prescaled by 1024.

The window you see in Photo 7 isyet another reason I chose the ICCAVRAVR C compiler. After the LED-counting code was compiled, I clickedon Tools>In System Programmer on theICCAVR tool bar, selected the STK500development board on COM1, clickedon Chip Erase, made sure my targethex file was listed in the “ManualProgram Now!” panel and clicked on

Listing 1—Now, this is the way to handle code generation for interrupt vectors. I like the idea of using theactual datasheet names for the vectors.

//Interrupt Vector Numbers

#define iv_RESET 1#define iv_INT0 2#define iv_INT1 3#define iv_TIMER1_CAPT 4#define iv_TIMER1_COMPA 5#define iv_TIMER1_COMPB 6#define iv_TIMER1_OVF 7#define iv_TIMER0_OVF 8#define iv_SPI_STC 9#define iv_UART_RX 10#define iv_UART_RXC 10#define iv_UART_DRE 11#define iv_UART_UDRE 11#define iv_UART_TX 12#define iv_UART_TXC 12#define iv_ANA_COMP 13#define iv_ANALOG_COMP 13

Page 63: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 61

the Program FLASH/EEPROM button.A few seconds later, the AT90S8515on the STK500 development boardtook control of the LEDs and thefamiliar binary counting pattern wasblinking away.

A SURPRISE PACKAGEIt looks like I have a great start

toward developing embedded applica-tions with the Atmel AVR parts, but Iwant to clear something up. I failed tomention the differences in theATmega16 and the ATmega163 partsI will be using. Both parts are essen-tially identical with the exception ofthe inclusion of a JTAG interface onthe ATmega16.

The ATmega16 JTAG interface isIEEE standard 1149.1 compliant andincludes the boundary-scan capabilitiesset forth in the standard. The AVRJTAG interface opens debugger accessto everything internal to theATmega16. With the right hardware,you can read and program the flashmemory, EEPROM, fuses, and lockbitsof the ATmega16 through the JTAGport (see Photo 8).

The version of AVR Studio I down-loaded earlier is designed to work handin hand with the JTAG ICE. The JTAGICE also directly supports the STK500development board. I took a quicklook at the ICCAVR library and thereare support files for the ATmega16,ATmega64, and the ATmega323, all ofwhich offer JTAG capability.

JTAG ICE operation is a bit differ-ent than that of more familiar emula-tors. The standard microcontroller

emulator contains a special bondoutdevice that runs the code and emu-lates the actual micro in hardware.Special pins and sequences allow youto extract the register, CPU, I/O, andmemory debug data from the bondoutdevice. JTAG ICE does not contain abondout device. Instead, JTAG ICEuses the AVR on-chip JTAG port andthe AVR’s built-in, on-chip debugger(OCD) to control the emulationprocess. With JTAG ICE, the emula-tion is actually code running on thetarget AVR microcontroller. TheJTAG interface coupled with the AVROCD and AVR Studio gives you aview into the AVR microcontroller’sinner works in real time.

The JTAG ICE is an interestingpiece of equipment and deserves moreattention. Next month, I’ll go intodetail about the JTAG ICE and cookup some AVR Internet code to showyou that the union of ICCAVR, JTAGICE, and the ATmega16 isn’t compli-cated, it’s embedded. I

RESOURCEAVR StudioAtmel Corp.www.atmel.com

SOURCESATmega Series micros, STK500

starter kitAtmel Corp.(408) 436-4314www.atmel.com

ICCAVR C CompilerImageCraft Creations Inc.(650) 493-9326www.imagecraft.com

iReady µInternetiReady Corp.(408) 330-4500www.iready.org

Fred Eady has more than 20 years ofexperience as a systems engineer. Hehas worked with computers and com-munication systems large and small,simple and complex. His forte isembedded-systems design and com-munications. Fred may be reached [email protected].

Photo 8—The STK501 development board comes witha dedicated JTAG header. The STK500 developmentboard has no such header. A 10-pin male header withpigtails comes with the JTAG ICE to allow it to be con-nected to the STK500 development board and to anyJTAG-capable AVR. The JTAG port resides on fourpins of port C on the ATmega16.

Page 64: circuit-cellar2002-05.pdf

62 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

icroprocessors—you either love

them or you hatethem. If you hate yours,

it’s probably because it doesn’t do whatyou want it to. Naturally, the bugs arethe chip’s fault. Don’t you wish some-one would make a processor that actu-ally has the features you want?

Ta-da! Cue Aladdin music. Yourwish has been granted. Now, you candesign your own microprocessor with-out years of studying for your doctor-ate in Computer Science. You can berunning code on your own micro-processor before the end of this week.

PROCESSOR FACTORYAlthough building your own foundry

is out of reach for most engineers (itcosts more than $1 billion just toupgrade an existing chip plant), it’s easyto make a few of your own processorsusing low-cost FPGAs. Altera andXilinx both encourage this behaviorfor the obvious reasons. In fact, bothcompanies have entered the business ofsupplying soft processor core designsto encourage engineers to use moreFPGA chips. Altera’s Nios (see Figure 1)and Xilinx’s MicroBlaze (see Figure 2)are both free but only work, of course,in the parent company’s chips.

Why put a processor in an FPGA?Why not buy a real microprocessor chipand solder it down? If you’re going touse an FPGA for random logic anyway,you can eliminate the extra chip byputting the processor in the FPGA, aswell. You also could experiment withdifferent processors in your FPGA,evaluating various ones until you findthe right balance of performance, size,cost, and power consumption.

The most interesting prospect, ofcourse, is modifying the processor tosuit your own whims. Or, dare I say,even designing your own processorfrom scratch (the first CPYou)? Well,you can, and there are some good rea-sons why you would (or would not)want to try this at home.

A ONE-MAN SHOWFor most engineers, designing your

own processor architecture is a coolidea but not a practical one. A customCPU has zero software support—notools, no compiler, no debugger, andno one to turn to when bugs crop up.You’re on your own.

Using an existing CPU, on the otherhand, makes a lot of sense even ifyou’re going to embed it into an FPGAor high-volume ASIC. In fact, accordingto Dataquest, the business of embed-ding CPUs into other chips is growingat about 25% per year and stood atabout $20 billion in 2000. That’s nosmall potatoes. The average is 2.3processors per intelligent ASIC (thosewith any programmability) and rising.

There’s no shortage of processors tochoose from, either. From little-known 8-bit processors created as uni-versity research projects to popular 16-and 32-bit processors like the ’286,SPARC, ARM, or MIPS, the market isready and willing to supply you withmicroprocessor intellectual property(IP). Some are free (and worth everypenny), while others might cost you asmuch as a new Mercedes.

One high-end free core is LEON-1, aSPARC clone distributed by theEuropean Space Agency. This is a realSPARC processor, created with Sun’sblessing, but without floating pointcapability or anywhere near the per-formance of Sun’s current processors.Still, SPARC has good software tools

Design Your OwnMicroprocessor

mProblem with yourmicroprocessor?Complications withmicros are often thecase. But, what if youdesigned your ownthat did exactly whatyou needed it to? Jimprovides a tutorial oncreating a micro-processor. The bonus:You don’t have to beBill Gates to build it.

Jim Turley

FEATUREARTICLE

Page 65: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 63

don’t violate any hardware patents,which is where Lexra, picoTurbo,Shengyu Shen, and others may haverun afoul of the technology lawyers.

Although you can’t patent a proces-sor’s instructions per se, you canpatent the circuits that make thoseinstructions work. AMD, Transmeta,and other (now defunct) ’x86 clonemakers have laboriously worked outdifferent ways to get their processorsto work exactly the same as Intel’s,but without using Intel’s exact circuit-ry. For a CPU as complex and baroqueas Pentium, that’s no small feat.

Cloning RISC processors is far easi-er, although not nearly as lucrative.RISC chips have, by definition, areduced set of features so they’re natu-rally less complicated. That simplicitywas supposed to make streamlinedRISC chips faster than tangled CISCchips like Pentium, but Intel’s deter-mination prevented that fairy talefrom ever coming true. However, ifyou’re going to clone a processor,RISC is definitely the way to go.

You can get a facsimile of a MIPSprocessor from OpenCores. Its “MIPS-lite” core supports most MIPS instruc-tions from a few generations back (seeFigure 3). For the premier MIPS knock-off, though, you needed to go to LexraComputing Engines. Lexra’s MIPS coreswere close enough to the real thing towarrant two lawsuits from MIPS.Oddly enough though, neither suitalleged patent infringement, onlycopyright infringement. Until recently,Lexra dodged both suits and sold its line

(available for free) and a certain amountof appeal and prestige. LEON-1 is pro-vided with VHDL source code (yousupply the hardware compiler) and runsat 20 to 40 MHz in Xilinx or AlteraFPGAs. At that speed, it would proba-bly take you a week to boot Solaris.

At the low end (and also in the freecategory), are 8-bit processor designsfrom CMOSexod and Free-IP cores.Both designs have little 8-bit processorsyou’ve never heard of but come withfree tools to get you started. The Free-IP Project also has a 6502 core, in caseyou’ve been hankering to resurrectyour old Apple II. VAutomation alsosells its 8-bit V8 processor with freetools. For your money, VAutomationgives you real technical support andthe warm fuzzy feeling that theirprocessor really works. They even usethe V8 in some of their own products.The company also has a 6502 as wellas Z80, 8086, and ’186 cores. Now thatIntel and AMD are both out of theembedded ’x86 business, soft cores likeVAutomation’s may be your only wayto get low-end ’x86 processors.

CLONE RANGERSAny mention of the ’x86 architecture

often brings up the issue of cloning.How can these knock-off processorsexist? Are they legal? And, what lia-bility am I exposing myself to if I use

one? The answers are sometimesmurky, but the short version is: don’tworry about it. Cloning processors is along and honored tradition, and theones who got there illegally generallyaren’t around any more. Darwinianselection has culled the dubious ones.

Legal protection on processors is afunny thing. You can’t patent aninstruction set but you can copyrighta processor’s mnemonics as a work ofliterature. Even more bizarre is thefact that it’s illegal to print a program-mer’s reference manual that’s thesame as, say, Pentium’s, but it’s per-fectly okay to make a chip that runsPentium code. That is, as long as you

irq

irq#

Reset

Clock

Wait

Data in32

6

Clock enable

Instructiondecoder

Interruptcontrol

Operandfetch

General-purpose processor register file

ALU

Q

Control

QD

Programcounter

Effective address

32

32

4

Data out

Address

Read/write

ifetch

Byte enable

Figure 1—NIOS is a 16-bit processor Altera designed specifically to work in its own FPGA devices.

On-chipinstructionmemory

0–256 KB

Instruction bus controller

Machine status register

Program counter

Control unit

Instruction buffer

r31

Register file32 × 32 bit

r1

r0

Data bus controller

On-chipdata

memory0–256 KB

CoreConnect OPB I/F Interrupt

controller UART

Watchdogtimer

General-purpose I/O

Timer/counters

CoreConnect OPB I/F

Off-chipmemory0–4 GB

Shift/logical

Add/subtract

Multiply

Peripherals

Off-chipmemory0–4 GB

Figure 2—Xilinx’s MicroBlaze, like NIOS, is an FPGA-only processor that resides in the “soft logic” of an FPGA.

Page 66: circuit-cellar2002-05.pdf

box is a VHDL or Verilog descriptionof the CPU. Neither company sellschips, only the recipe for the proces-sor. Your freedom lies in your abilityto adjust the recipe to suit your tastebefore you send your chip off to thesilicon oven. You can make your chipsin FPGA if you’re looking at modestvolumes, or go to a big Asian foundryif you’re ready for millions of chipswith your logo on them.

Both ARC and Tensilica start youoff with a working 32-bit RISC corethat’s in the same league as ARM7,MIPS R3000, or most other mid-range32-bit processors. These cores startout small enough to fit into all butthe smallest parts from Xilinx orAltera. Both processors have the usualarithmetic (add, subtract, multiply),logical (shift, rotate, exclusive-OR),and flow-control (branch, jump,return) features that you’d expect tosee. In short, they’re completely func-tional RISC designs that crank outabout 1.1 Dhrystone MIPS per mega-hertz, just like any self-respectingprocessor should these days.

64 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

of mostly MIPS-compatible cores. Now,Lexra is officially MIPS licensed andconcentrates on network processors.

Along those same lines, there wereat least two unauthorized versions ofthe popular ARM architecture. A freeone was available through OpenCoresuntil last summer, when legal pres-sure apparently made it disappear.picoTurbo was also happy to sell youits version until it disappeared a fewmonths ago.

YOU-BUILD-IT INSTRUCTION SETSThe next giant step just beyond

building your own processor is design-ing your own processor. You can startfrom scratch and have all the glory (andall the headaches) for yourself, or youcan use one of the many do-it-yourself(DIY) kits that are available. Like Legoblocks, these DIY microprocessors canbe used to build an amazing array ofcompletely different products.

The two big leaders in the area ofuser-configurable microprocessors areARC International and Tensilica.ARC (not to be confused with ARM)

is the older of the two and has morecustomers. Tensilica is based inSilicon Valley and seems to be catch-ing on well. There are minor differ-ences between ARC’s ARCtangentand Tensilica’s Xtensa processors, butthey’re more alike than different.

Both are 32-bit processors that youcan tweak, twist, and modify to createyour own private custom 32-bit CPU.You don’t have to start from scratcheither, because both processors workright out of the box. In this case, the

Photo 1—ARChitect is a program that allows engi-neers or programmers to design their own CPU withonly a few mouse clicks.

Visit us on the web www.jkmicro.comCall 530-297-6073 Fax 530-297-6074

Ether6*10Base-T Ethernet

6 Serial Ports1MB SRAM

Rugged EnclosureOptional On BoardModem & 10Base-2

Starts at $369

µFlashTCP-EP*10Base-T Ethernet

2 Serial Ports7-34 VDC

Rugged Enclosure w/Industry Standard

ConnectorsStarts at $229

SoftwareDOS & Web Server On-Board

Royalty free TCP/ IP source code providedeRTOS available for Multi tasking applications

Borland C/C++ in Development Kits

LogicFlex*10Base-T Ethernet

46 Digital I /O’sProgrammable Xilinx CPLDHardware Clock/Calendar

Expansion Bus for PeripheralsStarts at $189

µFlashTCP*10Base-T Ethernet

2 Serial Ports10 Digital I/O’s3.75” x 2.50”

30% smaller than PC104Starts at $149

All products based on the Intel 386Ex with DOS, TCP/IP and Web Server software pre-installed.

NE2000 compliant 10Base-T Ethernet & DIP socket to accept an M-Systems DiskOnChip standard.

1403 Fifth St., Suite DDavis, CA 95616 USA

JK microsystems connects you with embedded control solutions. Our cost-effective DOS basedcontrollers are ideal for data acquisition, networking or industrial technology applications.

*

Page 69: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 67

But, that’s just the basics.On top of the baseline fea-tures, you get to select from amenu of predefined, pre-test-ed options to extend yourprocessor. Do you want afaster multiplier? Choose thatoption, and your chip will getsmarter (and bigger). Do youneed DSP features? Yeah,that’s in there. Do you wantbigger caches or more regis-ters? Go for it. Both compa-nies’ cores have a dozen or socanned options you canchoose from. Selecting themall might double the size ofyour basic processor core, butthat’s your choice.

Both firms use a familiar point-and-click user interface to configure theprocessor. ARC has a program calledARChitect and Tensilica’s interface isavailable through its web site (seePhoto 1). In either case, you click onthe options you want, and after a fewminutes, your custom processordesign is generated for you, completewith software tools to program it.

OH, MY VERY OWN INSTRUCTIONSYou don’t see what you want on the

menu? Now the real fun begins. Bothcompanies let you go beyond thecanned options and design your ownfeatures into the processor. You don’tlike the way the CPU handles over-flows? Change it. Do you want toencrypt your code with a couple offunny instructions nobody can figureout? The limit is your creativity.

You can extend the ARCtangentusing normal Verilog or VHDL todefine hardware extensions to theprocessor. When ARChitect configuresthe ARCtangent core, it stitches inyour custom instructions along withit. As long as you’re familiar witheither VHDL or Verilog, it’s prettystraightforward. Tensilica does essen-tially the same thing but uses its ownlanguage, called Tensilica instructionextensions (TIE). With TIE, you definewhat you want the new features todo, then upload the definition toTensilica’s web site. Your wishes areintegrated into the final design anddownloaded back to you.

The end result is a processor that’spart standard, part custom. Your CPUwill be binary-compatible with otherARC or Tensilica processors, but withadditions you define. What would youadd to 30 years of computer architec-ture that hasn’t already been done?Quite a lot, based on the evidence ofcustomers who have done this.

Most users look for performanceimprovements, either by collapsingfrequently used sequences of instruc-tions or by designing custom instruc-tions that do something unusual. Ifyou’re handling packed 8-bit pixels, aset of parallel SIMD add and multiplyinstructions would be helpful. Ifyou’re handling 24-bit audio samples,saturating arithmetic (math thatclamps at certain levels) is a boon.Encryption guys love bit insert and

extract instructions. Few ofthese operations appear inmainstream processors.

Other times, the goal is tocompress code size. RISC,by its nature, has lousy codedensity, but you can getsome of that back by defin-ing your own instructions.Other times, the objectivehas less to do with perform-ance and more with compet-itive business. Custominstructions can preventreverse engineering. Anyonecan disassemble code for astandard microprocessor. Allit takes is a few minuteswith a logic analyzer or ROM

burner. But if your processor has one ortwo custom instructions, disassemblingcode becomes much tougher. Even ifyour custom instruction is an NOP, noone knows that but you and sprinklinga few of them in your software willconfuse the most diligent code spy.

However, if designing your ownprocessor isn’t advanced enough foryou, try this out. New tools candesign the processor for you based ona vague wish list. They’re not perfect,and they’re still at an early stage. But,we’re gradually approaching the goalof a machine that executes the pro-gram “do what I’m thinking.”

SOFTWARE IN, HARDWARE OUTCeloxica has a hardware-design tool

called Handel-C (see Figure 4). It’s alanguage somewhat similar to Verilog

PC_next Memory_ctrl

Control

Regular_bank Bus_mux Shifter

ALU

Mult

PC

d_write

pc_sourcers_indexrt_index

rd_index

regular_source

regular_target

regular_dest

imm

_out

a_so

urce

b_so

urce

c_so

urce

bran

ch_f

unc

alu/shift/mult_func

a_bus

b_bus

c_bus

Address

d_read

opco

de

mem

_ so

urce

Figure 3—OpenCores’ contributors have developed an open-source microproces-sor that’s similar to a MIPS core.

VH

DL B

ehavioral model

CO–simulation

CO–simulation

ED

IF

EDIFED

IF

Input

RTL/VHDL

Hardwaresystem

Vendor placeand route tools

Compiler

Instructionset simulator

VHDLsynthesis

HDLsimulator

Handel-Csimulator

Embeddedsoftware

DK1Design suiteVHDL

External IPcores

Executablespecification

Figure 4—Celoxica’s Handle-C is similar to C, but instead of producing a program, it creates a circuit design.

Page 70: circuit-cellar2002-05.pdf

68 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

and, you guessed it, C. It’s more like Cprogramming than Verilog modeling.The idea is to let programmers definehardware, even if they don’t reallyknow what they’re doing. In fact,Celoxica considers it an advantage ifyou don’t have hardware design expe-rience. “Let Handel-C do the job, andyou won’t be disappointed,” they say.

This concept is certainly appealing.Theoretically you can throw sourcecode written in Handel-C at Celoxica’scompiler and what will emerge is nota program but a hardware descriptionof a circuit that executes that pro-gram. It’s a kind of hard-coded proces-sor tuned for exactly the program yougave it. Don’t bother looking underthe hood because you don’t want toknow what’s there. Dyed-in-the-woolhardware designers might gag at thecircuits that Celoxica’s tools produce,but that’s not the point. A hardwareengineer didn’t produce it; an auto-mated tool did. A company could the-oretically dispense with its hardwareengineers entirely and replace themall with C programmers armed with afew copies of Celoxica’s Handel-Ccompiler. That’s a scary thought.

In a similar vein, Agilent andSTMicroelectronics have teamed up toproduce a configurable processor withthe mellifluous name of ST210.(STMicroelectronics manufactures thechip, so they got to name it.) TheST210 is the first and, so far, the onlyexample of a concept the group calledPICO (program in, code out). The ideais to let automated tools make designdecisions, rather than relying on engi-neers or programmers. As embeddedsystems get more complicated, the rea-soning goes that hardware design is no

longer intuitive. Humans don’t alwaysknow what they want or what’s best.The ST210 is a 250-MHz, eight-way,super-scalar VLIW beast, so it’s a bitbeyond the means of most embeddeddesigners for the time being.

Along the same lines is Improv’s Jazzprocessor. Like ST210, Jazz more or lessdefines itself based on the program it’sasked to run. In Improv’s case, youdefine the problem using a complexcombination of Java programs and avisual-editing tool. From these, Jazzextracts what parallelism it can findand cobbles together the ideal processorfor what you’re trying to accomplish.

What all three of these approacheshave in common is that the hardwareis fixed. After the automated toolmakes up its mind about what theprocessor should look like, that’s it.From that point on, it’s a fixed pieceof hardware just like any other chip.

CHANGING RUN TIMES Elixent takes the concept one step

further. Yes, it has an automated toolthat defines the circuitry from a sourceprogram, but instead of creating aprocessor, it creates multiple hardwareimplementations and switches amongthem on the fly based on the workload(see Figure 5). Elixent combines the“software in, hardware out” conceptof Celoxica with the real-time recon-figurability of an FPGA. The result isa programmable chip that can trans-mogrify itself for various tasks.

Elixent enters the world of dynamicreconfigurability, or reconfigurablecomputing (RC). RC seems like a com-pletely reasonable concept: change thehardware on the fly to suit the appli-cation. After all, nearly all embedded

ALU R

RR

RAM-basedswitch box

4-bitBuses

4-bit ALU(+,&,?...)

4-bitRegisters

RAM8-bit Address

8-bit Data

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

ALU R

RR

Figure 5—Elixent combines configurable processors with field-programmable logic to create a constantly changingprocessor. Elixent’s tool switches implementations on the fly based on your workload.

Page 71: circuit-cellar2002-05.pdf

www.circuitcellar.com

Jim Turley is an independent analyst,columnist, and speaker specializing inmicroprocessors and semiconductorintellectual property. He is the formereditor of Microprocessor Report andEmbedded Processor Report and hostof the annual Microprocessor Forumand Embedded Processor Forum con-ferences. You may write to him [email protected] or visit his website at www.jimturley.com.

RESOURCESVAutomationARC International(603) 882-2282www.vautomation.com

CMOSexodwww.cmosexod.com/freeip.htm

Elixent Ltd.+44 117 917 5770

systems handle different tasks at dif-ferent times. One moment you’redecompressing audio streams, thenext you’re handling an interrupt, andthe next you’re accepting user input.It stands to reason that whenever onepart of the circuit is working the otherparts must be idle. This is often true,but there’s nothing you can do aboutit. Hardware systems have alwaysbeen created from a superset of all thefunctions required over the life of theproduct, rolled into one.

If RC takes off, that might change.For example, future generations of cellphones may use half the transistors todo 10 times the work. Fewer transis-tors may be all that’s needed, if noneare wasted on functions that aren’trequired right now. Transistors wouldsimply be on call; available for what-ever was required at the moment.

Programming such a beast would bea whole new challenge. How do youwrite code for a moving target?According to RC partisans, you don’t.In Elixent’s case, there is no softwareas we know it. The original programwas simply the input function, a wayto define what you wanted. The out-put function was the hardware itself,which has all the program informationit needs. Cue Twilight Zone music. I

Fax: +44 117 917 5779www.elixent.com

CIRCUIT CELLAR® Issue 142 May 2002 69

SOURCESARCtangent, ARChitectARC International(603) 882-2282Fax: (603) 882-1587www.arccores.com

Handel-CCeloxica (408) 626-9070+44 (0) 1235 863 656Fax: (408) 626-9079 Fax: + 44 (0) 1235 863 648www.celoxica.com

LEON-1Distributed by The EuropeanSpace Agency+33 1 5369 7654 Fax: +33 1 5369 7560 www.estec.esa.nl/wsmwww/leon/

ST210Agilent Technologies(650) 752-5000http://we.home.agilent.com

STMicroelectronics(617) 225-2066 Fax: (617) 225-7918http://us.st.com

Jazz processorImprov Systems, Inc.(978) 927-0555 Fax: (978) 927-0999 www.improvsys.com

XtensaTensilica (408) 986-8000 Fax: (408) 986-8919 www.tensilica.com

The Free-IP ProjectXESS, Corp.(919) 387-0076Fax: (919) 387-1302www.free-ip.comwww.xess.com.

Lexra Inc.(408) 573-1890Fax: (408) 573-1898www.lexra.com

OpenCoreswww.opencores.org/projects

Page 72: circuit-cellar2002-05.pdf

70 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

hen I think ofisolation, I think

of Robinson Crusoeand Friday or in more

recent times, Tom Hanks as ChuckNoland. When I think isolation in theelectronics context, I think of thetransformer. For years, transformershave been used to isolate signals.Magnetic properties transfer informa-tion without an electrical connectionbetween primary and secondary wind-ings. On most transformers, it’s theplastic bobbin that holds the primaryand secondary windings separated thatcreates the isolation barrier. Morerecently, opto devices have become apopular method of obtaining isolation.

As you can see in Figure 1, optodevices rely on light (or the absence oflight) to transfer information betweenthe physically separated primary (input)and secondary (output). Although thetransformer is inherently a bidirection-al isolation device, most isolation appli-cation requirements are unidirectional.

LIGHTSOLATIONOpto devices have the advantage of

operating down to DC whereas trans-formers are specified at some AC band-width. From an isolated control pointof view, transformers can’t be used

directly for steady-state isolation. Optodevices work well in this scenario. Anopto device does require a chunk ofcurrent to operate and the transferratio of input current to output currentwill usually require a trade-off of speedfor drive current. This trade-off is nota problem until you want to transferinformation at high speeds. Most optodevices have minimum TON/TOFF

times in the microsecond range. A new device in the isolation flurry

takes a step back into the magneticdomain. NVE Sensor Engineering usesgiant magneto resistive (GMR) sen-sors to transfer information using themagnetic fields produced by currentin a conductor.

MAGNESOLATIONYou may already be familiar with

Hall effect devices, which can be usedto measure the strength of a magneticfield. The Hall effect is the presence ofa voltage produced across (x-axis) acurrent-carrying conductor (y-axis) as aresult of exposure to a magnetic fieldpassing through the conductor (z-axis).This differs from the GMR effect.

The GMR effect is a change in athin film nonmagnetic conductivelayer’s resistance caused by an exter-nal magnetic field overcoming the par-allel but opposing magnetic couplingof adjacent magnetized layers (seeFigure 2). You’ll remember that thespin of electrons in a magnet arealigned to produce a magneticmoment. Magnetic layers with oppos-ing spins (magnetic moments) impedethe progress of the electrons (higherscattering) through a sandwiched con-ductive layer. This arrangement caus-es the conductor to have a higherresistance to current flow.

An external magnetic field canrealign all of the layers into a singlemagnetic moment. When this happens,

You’re Not Alone

wJeff hasn’tturnedinto aself-helpwriter, but

you can help yourselfby following along ashe outlines the chal-lenges and effects ofisolation. Knowingwhat the options arewill help keep yournext project on track.

LED

1″

Signal transmittedby photo stream

Galvanic isolationby bulk dielectric

A

Isolatedoutput

VCC

Photo detector

Figure 1—Optoisolators rely on physical separationbetween the LED transmitter and photo detector for iso-lation. Data is passed via photons (or the lack of).

Jeff Bachiochi

FROM THE BENCH

Dealing with Isolation

Page 73: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 71

for an isolated power supply circuit (seeFigure 7). C&D Technologies makes anisolation transformer specially designedfor the MAX253. The 78250 seriestransformer is available in 1500-V and4000-V isolation from Mouser.

I made prototypes of the circuits inFigures 6 and 7 to create an isolatedRS-485 transceiver for use with amicrocontroller. Notice the surfacemount IL-485 mounted on a dip headerin Photo 1. Pins 4, 5, 12, and 13 of theIL-485 are soldered to the header andthe other pins are wired to the appropri-ate dip header pins. Using a dip headerfor surface mount parts makes themeasier to handle and reuse elsewhere(after you get past the surgical wiring).

Although the IL-485 is only availablein the surface mount variety, the otherdevices are through-hole components. Imeasured typical required currents inthe isoloop IL-485 circuit in Figure 6 andfound the isolated RS-485 side requiredconsiderably less than 50 mA withoutany load on the twisted pair. Usingthe isolated voltage to supply the termi-nation load adds 50 mA to the loadrequirements of the MAX253 isolatedsupply. The MAX253 circuit easily sup-plied this current at just over 5 V afterthe Schottky rectifier drop, thanks tothe 1:1.31 winding of the transformer.No regulator is needed because this is

electron flow will be less effected(lower scattering) by the uniform spinsof the adjacent ferromagnetic layers.This causes the conduction layer tohave a lower resistance to current flow.Note that this phenomenon takes placeonly when the conduction layer is thinenough (less than 5 nm) for the ferro-magnetic layer’s electron spins to affectthe conductive layer’s electron’s path.

To put this phenomenon to work,NVE uses a Wheatstone bridge config-uration of four GMR sensors (seeFigure 3). Their manufacturing processallows thick film magnetic material tobe deposited over the sensor elementsto provide areas of magnetic shieldingor flux concentration. Various op-ampor in-amp configurations can be usedto supply signal conditioning from thebridge’s outputs. This forms the basisof an isolation receiver. The isolationtransmitter is simply coil circuitry

deposited on a layer between the GMRsensors layers and the thick film mag-netic shielding layer (see Figure 4).Current through this coil layer producethe magnetic field, which overcomesthe antiferromagnetic layers therebyreducing the sensor’s resistance.

NVE obtains isolation specificationsof 2500-VRMS using its manufacturingprocess. Unlike typical microsecondTON/TOFF times of optoisolators, isoloop-isolators are typically 1 ns, which ismore than 1000 times faster than itslight-based rival. The isoloop-isolatorsalso have identical TON/TOFF times,which produce no pulse-width distor-tion as is the case with many optoiso-lators having differing TON/TOFF times.

Propagation delays are less than 10 nswith inter-channel skewing of lessthan 2 ns. Isoloop-isolators have up tofour channels per package in a varietyof device direction configurations.These standard devices are great forbus isolation, serial ADCs and DACs,and communication isolation. Figure 5shows typical RS-232 isolation.Specialty devices include isolated RS-422 and RS-485 communicationstransceivers (see Figure 6).

POWER ISOLATIONIsolation can’t be achieved using a

common power supply. This need cre-ates a requirement for additional cir-cuitry beyond the signal isolation.There must be a separate power supplyfor the circuitry on each side of the iso-lation barrier. Often this will be moreexpensive than the signal isolation.

The simplest solution might be topurchase a DC-DC converter. In thiscase the converter is used as an isolatorinstead of converting from one voltageto another. Take your time choosing aconverter; if you aren’t careful youcan find yourself being locked into asingle-source manufacturer, especiallyif you choose a converter with a weirdpinout or physical size. An alternativemight be to build one directly on-board.

Both Linear Technologies and Maximspecialize in power products. Linear’sLT1424-5 is good to about 2 W. Forlower currents up to a 1-W converter,take a look at Maxim’s MAX253. Fewexternal components are required to usethe MAX253 as a transformer driver

High-resistance state

+ + B + +

• • B • •A

Magneticmoment

orientation

No external field

Low-resistance state

+ + B + +

+ + B + +A

Applied external field

Figure 2—In both a and b, the A layers are the non-magnetic conductive layer and the B layers are adja-cent magnetic layers of opposing orientation. a—LayerA is high resistance because of higher scattering ofelectrons flowing through it. b—An applied magneticfield realigns the magnetic moments in the B layers,resulting in a lower resistance in layer A because of adecrease in electron scattering.

Planarcoil

1″H

Signal transmittedby magnetic field

Galvanic isolationby thin-film dielectric

A

Isolatedoutput

VCC

VCC

GMR Resistors

Figure 3—In a GMR, isolator data travels via a mag-netic field through a dielectric isolation to affect theresistance elements arranged in a bridge configuration.

Spin valveresistors

Isolationdielectric

Magnetic field - H(HαIIN)

IIN

Field producing coil

Figure 4—The magnetic field produced by the fieldcoil of the input affects the spin of electrons in theanti-ferromagnetic layers, reducing the resistance ofthe bridge sensors.

Photo 1—Mounting an SMD on a DIP header makesit easy to work with.

a)

b)

Page 74: circuit-cellar2002-05.pdf

sary. Overlooking the more obvioussafety issues (such as distances betweendevices) in some applications increasesthe potential for ground loop problems.

GROUND LOOPSWhen equipment using different

power supplies is tied together (with acommon ground connection) there is apotential for ground loop currents toexist. This is an induced current inthe common ground line as a result ofa difference in ground potentials at eachpiece of equipment. (Note: improperhouse wiring can cause ground loopswhen the neutral side of the line, orthe ground, is not properly grounded.)

We normally think of all grounds asbeing of the same potential. If this wereso, there would never be a groundloop problem. Here at Circuit Cellarworld headquarters, I’ve measured aconsiderable difference between thegrounds of different outlets (and differ-ent phases) within the same room.

There are a number of reasons thatcould explain these findings. It doesn’ttake a large difference in potential tocause ground currents to flow througha common ground connection. Thepotentials (and currents created) arealso load related, so, most of the time,these currents will not be steady state.

If sensor circuitry is based on its ownground as a reference and the systemground is not the same, you can’texpect to be able to take accurate meas-urements. You’d think that making thecommon ground heavier might be thesolution. But, in many cases, this onlyincreases ground loop current. Breakingthis common ground is a better solu-tion. However, if the common ground

72 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

within the recommended range for theIL-485 (4.5–5.5 VDC) and well belowthe 7-VDC absolute maximum rating.

The 78253 transformer from C&DTechnologies is rated at 200 mA, sothere is plenty of overhead even with

a heavy RS-485 termination. Largespikes were seen on the isolated sideof the MAX253’s circuitry, but a serieschoke tamed them nicely (see Photo 2).

Are isolation techniques necessary?In many situations, they aren’t neces-

Photo 2—The upper trace shows 0.5-V spikes on theisolated output of the power supply. The lower traceshows the same output after a series choke.

Figure 5—The IL-712 contains Z isolators, which can easily be used with a MAX-232 for serial isolation. An addi-tional IL-712 will add isolation for hardware handshaking.

Page 76: circuit-cellar2002-05.pdf

902 Waterway Place | Longwood, FL 32750 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069

Visit our website @ www.micromint.com to see our complete line of OEM Solutions.

The embedded controller that’s out of this world.When engineers working on NASA’s Space Shuttle imagined the right embedded controller for their critical payloadexperiments, they turned to the one supplier with more solutions than any other supplier of embedded controllers in the world — Micromint.

With over 250,000 controllers in the marketplace, Micromint has been providing innovative, turn-key solutions to theOEM market for over twenty years- from design through production, as well as packaging and shipping the final product.Our broad line of embedded controllers and turn-key solutions can turn your imagination into reality.

Page 77: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 75

connection is broken, thedifferential in groundpotentials remains and willaffect any signal betweenthe two pieces of equip-ment. You need to isolatethe grounds as well as theother signals, otherwise yourun the risk of exceedingthe maximum or minimumallowable input specs.

To eliminate groundloop problems when con-necting devices usinggrounded supplies locatedon different circuits, do notmake a common ground connectionbetween the devices you want con-nected. Although this eliminatesground currents from flowing betweendevices, it creates a problem for thesignals, which are ground referenced.

Take communications interfaces forinstance. RS-232 circuitry must have aground connection because it is the ref-erence for the remaining signal lines.On the other hand, RS-422/485 usesdifferential signals not referenced toground. You can use this twisted pairconnection without a common groundunless there is a difference of morethan 7 V between them. The RS-485receivers can withstand up to a 7-Vground-referenced difference beforeexceeding the maximum or minimumratings. Would you gamble with circuitfailure over a 7-V spread? This is wheresignal isolation payoff comes into play.

When dealing with sensors, groundloop currents cause changes in an ana-log signal. These changes often looklike signal noise. A ground loop caneven be caused by a mechanical andelectrical (if uninsulated) connectionto a grounded object being sensed. To

eliminate all of the common groundloop problems between sensor andmeasurement circuitry, always powerand measure sensors with the samelocal supply. By measuring right at thesensor, lengthy leads will carry digitaldata (easily isolated) rather than ana-log data (difficult to isolate).

The available IsoLoop products willhandle most isolation problems. Be-sides the speed advantage over mostoptoisolators, the IsoLoop productshave a latching output. Because the out-put state is latched on magnetic fieldchange (controlled by the input to thedevice), even if the power is removedfrom the input side, the output side’slogic state would remain latched (mem-orized). This would require an extra setof latches when using an optoisolator.

NVE introduced its first GMR prod-uct in 1994. These days, GMR sensorscompete with Hall effect devices formany magnetic sensing applicationsand additional research continues onthe use of GMR materials for magne-toresistive random access memory(MRAM) technology. Can you say corememory? What goes around…. I

Figure 6—The IL-485 replaces the RS-485 devices when an isolatedtwisted pair network is needed.

Figure 7—Maxim’s MAX253 makes a great isolationsupply. C&D Technologies has a transformer specifical-ly for use with the MAX253.

SOURCEIsoLoop high-speed digital isolatorsNonvolatile Electronics Inc.(952) 996-1610www.isoloop.com

Jeff Bachiochi (pronounced BAH-key-AH-key) is an electrical engineer onCircuit Cellar’s engineering staff. Hisbackground includes product designand manufacturing. He may be reachedat [email protected].

Page 78: circuit-cellar2002-05.pdf

76 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

study byACNielsen in 2001

found that nearly halfa billion people world-

wide now have Internet access. Doesthat put more pressure on embeddeddevices to get on the Internet bandwag-on? You bet your bippy! My opinion isthat everything with an electron mov-ing wants to be on the Internet. Marketpotential is unlimited on the demandside. But, as Econ 101 reminds us, it’sonly realized to the degree that the sup-ply side delivers and the price is right.

For some time now I’ve been keep-ing a close eye on the bleeding edge ofembedded Internet technology. One of

the most interesting takes on the sub-ject was the Seiko 7660A chip I cov-ered in 1999 (Circuit Cellar 111).Exploiting hardware protocol technol-ogy from iReady set the ’7660A apartfrom the software-stack crowd.

Although I don’t think they’re ship-ping billions yet, the ’7660A hasappeared in enough designs to rein-force interest in, if not prove, thehardware protocol stack concept.

Frankly, I’ve been waiting for anoth-er hardware-centric shoe to drop. Waitno more. Say hello to the new chip onthe embedded Internet block, theW3100 from i2Chip (see Figure 1).

MII WAYGenerally speaking, the W3100 is

similar to the ’7660A. Both are madeup of the same four blocks: host inter-face, network interface, protocol pro-cessing, and buffer SRAM. However,going beyond a superficial comparisonreveals that the chips are actuallyquite different in terms of suitabilityfor a particular application.

The most compelling difference isthe choice of networking. The Seikochip was designed for dial-up accesswhile i2Chip targets Ethernet. The dif-ference in network speed (i.e., 56 Kbpsfor a modem versus 10 or 100 Mbpsfor Ethernet) percolates through allaspects of the W3100, starting withthe network interface itself.

The ’3100 incorporates the 802.3ustandard media-independent interface(MII). This spec originated with thedesktop Ethernet crowd as a way toallow a single Ethernet media accesscontroller (MAC) to work with the

I-Way the Hard(ware)Way

a

Tom Cantrell

DHCPProtocol engine

ICMP TCP UDP

IP ARP

DLC

MAC

MII Interface

DP

RA

M

MC

U In

terf

ace

RX

_CLK

CR

SR

XD

(3:0

)T

X_C

LKT

XE

TX

D(3

:0)

CO

L*S

ER

ISL

DP

LX*L

INK

*CS*WR*RD*INT

ADDR(14:0)DATA(7:0)

*RESET

64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

123456789

10111213141516

48474645444342414039383736353433

COLNCRX_CLKGNDRXDV/CRSRXD[3]RXD[2]RXD[1]RXD[0]NCVCCGND*LINK*SERIALDPLXNC

A[4

]A

[3]

A[2

]A

[1]

A[0

]V

CC

GN

DD

[7]

D[6

]D

[5]

D[4

]N

CD

[3]

D[2

]D

[1]

D[0

]

*CS

*RD

*WR

*IN

TN

CN

CV

CC

GN

DN

CT

X_C

LKG

ND

TX

ET

XD

[3]

TX

D[2

]T

XD

[1]

TX

D[0

]

RESETVCC

GNDNC

A[14]A[13]A[12]A[11]A[10]A[9]A[8]VCC

GNDA[7]A[6]A[5]

Figure 1—Following the iReady/Seiko 7660A, the i2Chip W3100 is the second hardware Internet chip to hit the street.

Getting onthe em-beddedInternetbandwag-

on is easy, but puttingan actual product onthe production line ischallenging. i2Chip’slatest offering lookspromising, but deliv-ery will be everythingfor this newcomer.

SILICONUPDATE

Page 79: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 77

various physical layer options. Forexample, a 10-Mbps setup can run thenibble-wide MII bus at 2.5 MHz (oralternatively, a single-bit bus at10 MHz) while 100 Mbps runs it at25 MHz. Note that the clocks aresourced by the physical interface(PHY), so the difference is transparentto the MAC (i.e., the ’3100).

I could say more about the MII, but Icovered it in last month’s article on theIntellon HomePlug powerline network-ing chip. The merit of the scheme isreinforced by the fact that it would bejust as easy to connect the ’3100 tothe Intellon chip as it is to connect itto a traditional Ethernet PHY.

All of the networking horsepowerpasses the bandwidth buck to the’3100 host interface and internalbuffering requirements, lest theybecome bottlenecks. Thus, the ’3100includes 24 KB of SRAM for on-chipbuffering, versus 10 KB for the’7600A. Because reception is alwaysmore dicey than transmission (the for-mer can’t be scheduled), the bufferbreakdown is asymmetric with 16 KBfor receive and 8 KB for transmit.

Similarly, the ’3100 can handle upto four sockets (i.e., a virtual full-duplex connection between a pair ofIP address and port designators)whereas the ’7600A can only handletwo. The difference could be key ifsimultaneous access by multipleclients (or a single client using multi-ple protocols) is required.

Both the ’7600A and ’3100 use asimple byte-wide host interface. Thedifference is that the ’3100 offersdirect addressing to the on-chip RAMand registers with a 15-line (A0–A14)address bus. Wait states shouldn’t be aproblem thanks to speedy accesstimes (22 ns for reads and a mere 10 nsfor writes). By contrast, the ’7600Awas able to get by with a much slower(but adequate considering modem linespeed) indirect addressing scheme.

Although the ’3100 runs on a 3.3-Vsupply, the I/O lines are 5-V tolerant,easing interface to existing designsthat use the higher voltage. Note thatpower consumption is a mere 2 mA(typical at 3.3 V), so Internet enablingan embedded gadget doesn’t have tobust the power budget. Contrast that

Listing 1—Thanks to the hardware assist from the W3100, a simple web server boils down to a few pagesof C.

//Create and initialize 4 Channels from W3100for(i = 0 ; i < MAX_SOCK_NUM; i++)

s[i] = socket(SOCK_STREAM,80,0); //Create and initialize HTTP Channel

SSTATUS[i] = SOCK_CLOSED; //Initialize channel status variables

if(INVALID_SOCKET == s[i]) goto PRG_END; //Fail to create channel, terminate program//Non Blocking Listen Command

if(SOCKET_ERROR == NBlisten(s[i])) goto PRG_END; //If it is error, terminate program

SSTATUS[i] = SOCK_LISTEN; //Change the channel status variable to Listen mode

//end for//Check the status of each channelwhile (1)

for (i = 0; i < MAX_SOCK_NUM; i++) if(SSTATUS[i] == SOCK_ESTABLISHED) Length = select(s[i], SEL_RECV);if(Length > 0)Length = recv(s[i], Data_Buf, Length);Con_Type = ParseReq(Data_Buf);Length = PrintHeader(TX_Buf, Con_Type);switch (Con_Type) case 'g':Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

case 'j':Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

case 'h':Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

case 'a':Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

case 'c':PutStringLn("EVB CONTROL");Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

case 'x':PutStringLn("EXIT");Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);break;

default :PutStringLn("DEFAULT");Length += DoHTML(TX_Buf + Length);Length = send(s[i], TX_Buf, Length);

if(Length == SOCKET_ERROR)GetLastError();goto PRG_END; //Terminate program

(continued)

Page 80: circuit-cellar2002-05.pdf

three-chip (MCU, W3100, PHY) designshown in the brochures. The MCU isa plain ’51 running at 24 MHz (i.e., 2-MIPS), and the PHY is a RealTek 8201.

There are a few more chips on theboard, but I don’t hold that against theW3100. To make life easier, the boarddesign includes external flash memoryand SRAM chips. It’s important tonote that these extra chips are a mat-ter of easing evaluation and generallywouldn’t be necessary in a productiondesign. Similarly, the board alsothrows in an RS-232 interface fordownloading and debugging.

78 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

with higher-end alternatives (e.g.,embedded PCs) that can easily consume100 times that amount of power.

PROTOCOL POWER TRIOLike the ’7600A, the ’3100 handles

IP with TCP and UDP. These are thefoundations of the Internet uponwhich the fancier layers of alphabetsoup (SMTP, HTTP, etc.) rest. As arefresher, recall that UDP is a relative-ly simple no-connection scheme thatdispenses with many of the fancierfeatures (flow control, reliable deliv-ery, etc.) found in TCP.

The block diagram seems to implythat the ’3100 also handles protocoltrinkets such as DHCP, ICMP, and ARPbut I found little reference to them inthe documentation. As best I can tell,they might require extra software, like-ly utilizing the so-called RAW optionthat bypasses the TCP and UDP layers.

Driving the chip seems straightfor-ward. Registers occupy a 512-bytechunk of the 32-KB address space (seeFigure 2). Just like setting up anaccount with an ISP, there’s a set of reg-isters that define the local IP, MAC andgateway addresses, and sub-net mask.

The remaining registers are dupli-cated four times, one set for each ofthe four sockets. To create a socket,start by initializing the registers thatdefine the destination IP address, port,and the protocol in use. After a socketis initialized, most of the actionswitches to individual command, pro-tocol state, and interrupt status regis-ters. When it’s time to move somedata, there are transmit and receivepointers that keep track of the SRAMaddresses for each socket’s packets.

PING-PONGGetting this far involves no more

than a review of the documentationon i2Chip’s web site. But, I learnedlong ago not to get too excited about a

chip until I can get my hands on thereal thing. As you can see in Photo 1,i2Chip has successfully made the tran-sition from paper-ware to hardware.

The 8051-based W3100 eval kit is areal-world version of the prototype

Listing 1—Continued.

//Check the status whether the client try to connect or not,//if client succeeded, update SSTATUS[I] to SOCK_ESTABLISHED//and accept to set up network information of client

else if(select(s[i],SEL_CONTROL) == SOCK_ESTABLISHED) //Connect OK?//Accept the client's connection requestif( SOCKET_ERROR == accept(s[i],&ChildAddr)) if(SCLOSED == GetLastError())PutString("Before Server accepted client, the client

already closed");PutHTOA(s[i]);PutStringLn("th socket");goto NEXT0;

goto PRG_END;

SSTATUS[i] = SOCK_ESTABLISHED; //Update socket status variable

NEXT0:

//Check the status whether client close the socket or not,//Release the allocated socket from W3100, and create and // initialize a new socket //for another client and update it to Listen mode/*else*/ if( select(s[i],SEL_CONTROL) == SOCK_CLOSED )

// If the client closed socket?PutHTOA(i);PutStringLn("th Socket are closed by Client");//Close the current using socketif(SOCKET_ERROR == close(s[i])) goto PRG_END;

PutHTOA(s[i]);PutStringLn("thSocket Closed");

//Initialize socket status variableSSTATUS[i] = SOCK_CLOSED;//Reallocate a sockets[i] = socket(SOCK_STREAM,5000,0);if(s[i] == INVALID_SOCKET) goto PRG_END;if(SOCKET_ERROR == NBlisten(s[i])) goto PRG_END;//Update socket status variable to Listen modePutHTOA(i) ; PutStringLn("th Socket Listened");SSTATUS[i] = SOCK_LISTEN;

Control registers

Not used

Transmission data buffer(DPRAM)

Receiving data buffer(DPRAM)

512 Kb

7.5 KB

8 KB

16 KB

0

513

8192

16384

32767

W3100 uses 8-bit × 512 address spacefor control registers and 8-bit × 24K addressspace for data buffers:

- 0 255: Space for control registers

- 256 512: Space for shadow registers

- 8192 16383: Data buffer for transmission

- 513 8191: Not used (this space can be used by other devices)

- 16384 32767: Data buffer for receiving

Figure 2—Connectingthe W3100 to a host isas easy as wiring upan SRAM chip. A full15-bit address busprovides direct accessto the on-chip regis-ters and buffers.

Page 82: circuit-cellar2002-05.pdf

80 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

Bringing the kit to life is as easy asconnecting the Ethernet and serial portsto a PC. The presence of an Ethernetlink LED on the board helps with theissue of crossover cables. You knowyou’re all set when the LED lights up.

The manual recommends verifyingthe installation using the DOS pingcommand (see Photo 2) before pro-ceeding. Naturally, it didn’t work atfirst. The manual makes no mentionof specific PC network settings, but Ifigured I’d have to fiddle with them.The key is to turn off DHCP and hard-

wire your PC’s IP address to let it reachthe board (see Photo 3), then ping away.

After the basic connection is provenwith ping, the next step is to run aloop-back test program that shovelsdata from the PC to the board and backagain. The EV board’s side of the pro-gram is supposedly loaded into the flashmemory, but if it is, my PC couldn’thook up with it. Time for plan B.

The CD that comes with the kitcontains copies of all the software(including source). So, I just changed ajumper on the board to switch programexecution from the flash-memory chipto the SRAM and used the mon-itor to download the loop-back.hex program. Despitesome glitches (the programprompts with an incorrect IPaddress) and a funky user inter-face, that did the trick.

I experimented with the loop-back program using differentsize files. For a huge file, theprogram reported a symmetric200 kbps in and out of the chip(see Photo 4). However, switch-

ing to smaller files (e.g., 4 KB–32 KB)affected both the symmetry and over-all throughput. The latter varied fromas little as 20 kbps up to 400 kbps.

I tried to explore this phenomenon,but must admit I got bogged down inthe source code, especially the PC-sideof things. The Microsoft toolchain gen-erates a bunch of bloatware in dozens offiles for the simplest task. After I finallyfound the part of the program that wasactually doing something, I had to con-cede that the code was somewhat overmy head, certainly in terms of deci-phering actual activity at the chip level.

Photo 2—The first step after connecting the EV board is to seeif the PC can find it using the ping command.

Photo 1—The EV kit proves that even a lowly ’51 canget on the Internet with a boost from the W3100.

Page 83: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 81

A bit of ASM would have gone along way to help see what was actuallygoing on, but only the source and objectfiles were provided and I didn’t haveeither of the C toolchains (Microsoft forthe PC, Keil for the ’51) to go further.

It’s not surprising that the character-istics of the data traffic would affectthroughput, but I’m left wonderingthe exact nature of the relationship,nevermind the proper strategy foroptimizing performance.

One clue is that, along with the200-kbps bulk throughput for the 2-MIPS ’51, i2Chip literature also men-tions a 400-kbps rate for a Dallas (nowowned by Maxim) ’51-based version ofdemo board. Because the Dallas chip isthree times faster than the standard ’51(i.e., 4 versus 12 clocks per instruction),it’s an indication that network through-put is heavily, but not completely,dependent on host MCU performance.

That’s rather disappointing becausean ostensible benefit for the hardwareprotocol approach would be to offloadthe host, and to the degree it does,decouple host and network perform-ance. Without further investigation,my conclusion is that blinding networkspeed (as you might expect from a hard-ware solution) isn’t what the W3100 isall about. On the bright side, I envisionmany of tomorrow’s low-cost, deeplyembedded Internet applications as hav-ing minimal bandwidth requirements.

THE PROOF IS IN THE SURFINGSocket-level programming is all well

and good, but for most people theembedded Internet concept is all aboutaccessing a gadget’s web page from astandard browser. The folks at i2Chipoblige with a simple web server demo.Download webserv.hex to the evalu-ation board, fire up your PC browser,and you’re ready to catch the wave.

Admittedly, the interface isn’t muchto write home about—no eye-candy,JPEGs, or multimedia. Just rememberthat it’s not about what the web pagelooks like, but rather that it came froma plain ’51 talking to a standard browser.

The example does demonstrate theability to accept input to a browserform and use it to control the ’51 (i.e.,set LEDs and display a message on aplug-in LCD). However, it does not

demonstrate the ability to shove datathe other way. A simple input device,even if it’s just a DIP switch, added tothe ’51 board and an upgraded demoto show how to deliver dynamic data(not just a static web page) help.

The guts of the web server code areshown in Listing 1. Interestingly, Ifound portions of the program con-sisted of previously published open-source code. There’s nothing wrongwith that and it gave my confidencein the W3100 a bit of a boost. Formal

verification, test suites, and the likeare nice, but running somebody else’sTCP/IP software on the chip is also avalid and useful real-world test.

AND THE VERDICT ISI must say that after getting under

the hood, I have mixed feelings.There’s no doubt that the overalli2Chip package and presentation isunpolished. The documentation isn’tgreat, the demonstration software is alittle awkward, and I’m left with

CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483

Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : [email protected]

EAGLE 4.0Schematic Capture • Board Layout

Autorouter

800-858-8355

Light Standard Professional

Layout

Schematic

Schematic +

Autorouter

Autorouter

Layout +

Layout +

Layout +

398$ 798$

399$

398$ 798$

49$ 597$ 1197$

199$

Prices

Pay the difference for Upgrades

EAGLE 4.0 Light is Freeware!EAGLE 4.0 Light is Freeware!

http://www.CadSoftUSA.comhttp://www.CadSoftUSA.com

Windows is a registered trademark of Microsoft Corporation

Linux is a registered trademark of Linus Torvalds

Windows®

for

and

You can use EAGLE Light for testing and fornon-commercial applications without charge. The FreewareVersion is restricted to boards up to half Eurocard format,with a maximum of two signal layers and one schematicsheet. All other features correspond to those of theProfessional Version. Download it from our Internet Siteor order our free CD.

The Standard Version is suitable for boards in Eurocardformat with up to 4 signal layers The Professional Versionhas no such limitations.

Frustration? No, thanks.Fun? Yes, please.

NeW

Version

Version 4.0 Highlights

New Library Management withComponent BrowserTechnology and Package variants forcomponentsDesign your own commands via UserLanguageUnlimited length for componentnames/valuesDesign Rules define pad/viadimensions and shapesNet Classes for Autorouter and DRCMinimum Autorouter grid: 0.02 mmSMD pads can be rounded or roundDifferent pad shapes for Top, Bottom,or Inner layers

Satisfied customers - the key to our success

that´s why every new EAGLE version is basedon the feedback from our customers

that´s why all our customers have access to ourhighly acclaimed, comprehensive support, freeof charge

that´s why EAGLE has no hidden costs forlibraries or modules which prove to beindispensable after purchasing

that´s why we really want customers to enjoyworking with EAGLE

that´s why EAGLE is one of the top-ratedprograms for schematic capture and boardlayout

FREE

Page 84: circuit-cellar2002-05.pdf

almost as many(but different)questions aswhen I started.

To be fair,i2Chip is a tinyoverseas start-up(a subsidiary ofSouth Korea’sWiznet). I’ll cutthem some slackfor that reason,but the market-place at large will

be much less for-giving. A good

chip is necessary, but byno means sufficient toguarantee business.

By the same token,i2Chips deserves plentyof credit for delivering aunique solution that hasthe appearance of actual-ly working. Competitorsmay hem and haw, butnobody can ignore thefact that i2Chip has

82 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

SOURCEW3100i2Chip, Inc.www.i2chip.com

Tom Cantrell has been working onchip, board, and systems design andmarketing for several years. You mayreach him by e-mail at [email protected].

managed to put a plain ’51 with a tinybit of code (webserv.hex is only11 KB or so) on the ’Net. Pardon thepun, but I’d say that stacks up wellagainst the typical 32-bit CPU andmegs of memory solution that manyothers are promulgating.

There isn’t, and likely never will be,one single universal embeddedInternet solution. i2Chip alludes to aforthcoming higher integration solu-tion combining MCU, W3100, andPHY on the same chip. I say bring iton and the more the merrier.

Hardware? Software? A little ofboth? For now, I’d say the answer is:all of the above. I

Photo 4—Transferring a 1-MB file, the W3100 delivered nearly 200-kbpsthroughput full duplex (i.e., it took about 40 s to send the file from the PCto the W3100 and back again.

Photo 3—To get started, keep things simple. Hardwire the IP settings on your PCto allow it to reach the W3100.

Page 85: circuit-cellar2002-05.pdf

www.circuitcellar.com CIRCUIT CELLAR® Issue 142 May 2002 83

Insert-ready sub-mini SBCs (small as 47x55 mm.) supporting thePhilips 8xC5918xC5918xC5918xC5918xC591, 89C51Rx289C51Rx289C51Rx289C51Rx289C51Rx2, XACxXACxXACxXACxXACx, XAGxXAGxXAGxXAGxXAGx, Infineon C167CxC167CxC167CxC167CxC167Cx,Motorola MPC555MPC555MPC555MPC555MPC555 & ST Microelectronic ST10F168ST10F168ST10F168ST10F168ST10F168

Low EMI designLow EMI designLow EMI designLow EMI designLow EMI design achieved via GND circuitry, 6 to 8 layer PCB, by-pass capacitor grid and short signal traces achieved via smallfootprint and use of 0402 SMD passive components

32 KB to 8 MB external SRAM & Flash (controller-dependent) FlashTools enable on-board in-system (ISP) programming RS-232, RS-485, I2C & CAN interfaces; ADC; Chip-Select signals Controller signals extend to standard (2.54 mm.) or high-density

Molex (0.625 mm.) header pins on two sides of the board,allowing the SBC to be plugged like a "big chip" into targets

Available in Rapid Development KitsRapid Development KitsRapid Development KitsRapid Development KitsRapid Development Kits including Development Board,AC adapter, serial cable and SPECTRUM CD with eval software tools(Keil, TASKING), FlashTools, electronic documentation and demos

www.phytec.com

phyCORE Modules:phyCORE Modules:phyCORE Modules:phyCORE Modules:phyCORE Modules:NEW GENERANEW GENERANEW GENERANEW GENERANEW GENERATIONTIONTIONTIONTIONSINGLE BOARD COMPUTERSSINGLE BOARD COMPUTERSSINGLE BOARD COMPUTERSSINGLE BOARD COMPUTERSSINGLE BOARD COMPUTERS

PHYTEC America LLC PHYTEC America LLC PHYTEC America LLC PHYTEC America LLC PHYTEC America LLC 255 Ericksen Avenue Bainbridge Island, WA USA 98110

(800) 278-9913

IDEA BOXTHE DIRECTORY OF PRODUCTS AND SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet. ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2″″ ×× 3″″ FORMAT. Call for current rate and deadline information. Send your disk and digital submis-sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or email [email protected]. For more information call Kevin Dows at (860) 872-3064.

Suppliers Directory now available online. Check out our web site www.circuitcellar.com to see who has what and how to get it!

Page 90: circuit-cellar2002-05.pdf

88 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

Dream P4Entertainer

1•80

0•A

•Dre

amer

ww

w.D

ream

Tech

.co

m

!"#$%&' #$($)* +, - ..' )*/!)0#1(2!34$(/& 5& 5%&. $-$. 6 &4 7'896"!:3!;2/4<

;9 5& 5%&4&" 6 $(2!34$(/&

Pentium 4

DreamTech

Dream P4845s

!"++ &)#$'#)* +, - ..' )*/!)0#1 5& 5%&4&"$(/.+$!&!4;$((&.= >63&" :3 7'8 7*?>!2"-@(2!34$(/&

!))#' #$($)* +, - ..' )* /))!)0#1 5& 5%&. $-$.(2!34$(/& 6 &4 ; &.= :3 7'8> =*?!;2/41.

1•51

0•35

3•18

00

!"#$%&'()'(*+,- .

/01

POWERFUL PENTIUM 4 ~ WITH INTEL 845WNMAIN BOARD & FAST PC/133MHz MEMORY!VALUE PRICED WITH 256MB RAM, 20GB HD,MOUSE, SOUND & MODEM!

DreamXP-Pro

2'))

FAST & RELIABLE WITH RAMBUS MEMORY,WINDOWS XP PROFESSIONAL & MORE!

BEST BUY! INTEL 845BG MAIN BOARD WITHINTEGRATED SOUND, 60GB HD & 256MB RAM.AVAILABLE UP TO 2.2GHz!

3

DESIGN YOUR DREAM P4!WITH INTEL MAIN BOARD,PROCESSOR & SOUND.

"#4*4,%5! 6

"#'*,%5! ! 7--

Page 96: circuit-cellar2002-05.pdf

Embedded Programming94 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

INDEX85 Abacom Technologies

10 Accutek Microcircuit Corp.

85 ActiveWire, Inc.

61,75 Advanced Transdata Corp.

69 All Electronics Corp.

85 Amazon Electronics

33 American Raisonance Corp.

9 Amulet Technologies

92 AP Circuits

90 Appspec Computer Tech. Corp.

84 Atlantic Quality Design, Inc.

85 Bagotronix, inc.

25,84 Basic Micro

81 CadSoft Computer, Inc.

91 CCS-Custom Computer Services

86 Cermetek Microelectronics Inc.

92 Conitec

11 Connecticut mircoComputer Inc.

91 Copeland Electronics Inc.

91 Cyberpak Co.

79 Cypress MicroSystems

C4 Dataman Programmers, Inc.

86 Dataprobe Inc.

86 DataRescue

83 Decade Engineering

89 Delcom Engineering

87 Designtech Engineering Co.

91 Digital Products

88 Dreamtech Computers

The Advertiser’s Index with links to their web sites is located at www.circuitceller.com under the current issue.Page

1 Earth Computer Technologies

48 ECD (Electronic Controls Design)

84 EE Tools (Electronic Engineering Tools)

82 EMAC, Inc.

73 ESC-Chicago

90 EVBplus.com

48 ExpressPCB

84 FDI-Future Designs, Inc.

89 Futurlec

84 Hagstrom Electronics

80 HI-TECH Software,LLC

91 HVW Technologies Inc.

86 ICE Technology

87 IMAGEcraft

86,92 Intec Automation, Inc.

86 Intronics, Inc.

68 Intuitive Circuits, LLC

49 JED Microprocessors Pty Ltd.

64 JK microsystems

38 JR Kerr Automation & Engineering

68 LabJack Corp.

80 Laipac Technology, Inc.

68 Lakeview Research

89,93 Lemos International

2 Link Instruments

93 Lynxmotion, Inc.

7 MaxStream

89 Micro Digital Inc

92 microEngineering Labs, Inc.

74 Micromint Inc.

84 MicroSystems Development, Inc.

87 MJS Consulting

66 MVS

86 Mylydia Inc.

38 Nav Masters

65 NetBurner

95 Netmedia, Inc.

87,90 OKW Electronics Inc.

93 Ontrak Control Systems

C2 Parallax, Inc.

83 Phytec America LLC

83 Phyton, Inc.

91 Picofab Inc.

90 Pioneer Hill Software

85 Prairie Digital Inc.

15 PSoC 2002 Design Challenge

89 Pulsar Inc.

91 R2 Controls

31 R4 Systems Inc.

39 Rabbit Semiconductor

82 Radiotronix, Inc.

85 R.E. Smith

10 Remote Processing

89 RLC Enterprises, Inc.

88 RPA Electronics Design, LLC

86 Rutex

59 Saelig Company

89 Scidyne

Extreme OSMC—Part 1: Open Source Motor Control ProjectUltra-Low Power Flash MCU MSP430 Design Contest WinnersSelecting the Best CAN ControllerAn Open-Source HCS ProjectBatMon to the Rescue—A Battery Monitor for R/C ModelsBehind the Scenes—Part 2: How to Build the SystemRoCK Specifications: The Goal of a New Machine—Part 3: ProgrammingI Above the Ground Plane: Invisible ComponentsI From the Bench: SmartMedia File Storage—A Windows Compatible DOS File SystemI Silicon Update: FPGA Power PlayI Applied PCs: Still Swimming with the STK500—Onto the JTAG ICE

Page Page Page

PREVIEW

143

ADVERTISER’S

Attention Advertisers:July Issue Deadlines

Space Close: May 10Material Due Date: May 17

Theme: Graphics & Video

3 Scott Edwards Electronics Inc.

88 Sealevel Systems Inc.

90 Senix Corp.

85 Sensory, Inc.

83 Signum Systems

87 SmartHome.com

38 Softools

23 Solutions Cubed

92 Spectrum Engineering

83 Square 1 Electronics

24 SUMBOX

41 Systronix

92 TAL Technologies

91 Tech Systems

C3 Tech Tools

90 Techniprise Inc.

32,72 Technologic Systems

93 Technological Arts

88 Tern Inc.

84 Timeline Inc.

83 Triangle Research Int’l Inc.

11 Trilogy Design

86 Vetra Systems Corp.

93 Weeder Technologies

91 Xilor Inc.

87 Z-World

85 Zanthic Technologies Inc.

Page 98: circuit-cellar2002-05.pdf

et’s face it. As technical magazines go, Circuit Cellar is a small fish in a big publishing sea. It’s not a David andGoliath struggle, mind you. It’s more like mutual coexistence. They do their thing and we do ours. One of the things we do really well is design contests. I could claim that it is merely the ability of a small business to

react quickly and tailor products to meet changing demands and interests, but the real credit goes to our involved reader-ship. Circuit Cellar readers have an insatiable appetite for innovative ideas and relish an opportunity to exhibit them. Our design contestshave evolved as a catalyst to construct those ideas and the magazine as a forum for their presentation.

Design contests have always been a big deal around Circuit Cellar, and in recent years, they have evolved into a major part of our edito-rial strategy. What is the fundamental ingredient to doing contests well? That’s simple. We enjoy it.

Most technical publishers treat contests as just another advertising endeavor. Rarely do they provide more than minimal contest manage-ment and contestant entries rarely involve physically building anything. This isn’t a failure on their part, it is merely a consequence of theirbusiness model versus ours. Certainly just treating it as advertising would be easier.

There was a time when we had one design contest a year. Demand from sponsors as well as readers has increased that to two a year. Infact, it can get a little insane around here because we’re always working on three contests at a time—past, present, and future. For example,we just finished the Texas Instruments contest and are now working with winners and entrants creating follow-up articles; we’re still runningthe present contest with Cypress MicroSystems; and, finally, we’re negotiating the contract and creating the ’Net presentation for the fall2002 contest. Crazier yet, we have five companies already interested in the spring 2003 slot. I once joked, “If you don’t see your favoriteprocessor now, wait a minute, it’ll show up.” That seems to be very true now.

Entrants and sponsors get a lot of value from participation. Contestants aren’t entering a lottery. Not winning isn’t the same as losingaround here. Because our real motivation is editorial rather than advertising, every project entry is evaluated by our editorial staff for itspotential to be turned into an article and published (we contact you separately for publishing rights). If you happened to be a winner, it’s con-sequential, not critical. Getting published in Circuit Cellar is based on the application value of your project, not on how it placed in a contest.If it’s a good design, I want it, period.

Being a winner in a Circuit Cellar contest can be good for your career, too. Companies looking to hire good designers view our contestsas an accurate test of your design credentials and your ability to finish what you start. More than a few contest entrants have received joboffers. In addition, some contestants have reported that being listed among our design contest winners provided the visibility they needed tolaunch their product. In our most recent TI contest, for example, one winner was approached by a marketing organization and his project isnow in full production. Regardless of the outcome, entering a Circuit Cellar contest can be a confidence builder.

With each successive contest, we try to make it easier for you to enter. To facilitate your ability to compete, recent contests have includedsamples and development kits shipped free to anyplace in the world. Of course, “sampling” for our current Cypress contest takes on a wholenew meaning when you realize that Cypress is providing a complete PSoC development system (worth about $50), and together with us,invested about $100,000 to put them into the right hands. We don’t want a little problem like not being able to find a PSoC in Beijing to keepyou from entering.

Next month, you’ll see the print announcement of the winners of our Texas Instruments MSP430 design contest. And the CypressMicroSystems PSoC 2002 contest has another month and a half before the projects go to the judges. But, as I’ve said many times before,don’t unplug your soldering irons yet. This fall, we are planning another Microchip Technology design contest for all of you PIC fans outthere. It’s our third outing with Microchip and we’ll try to make it our best yet. Reader involvement is the greatest encouragement I know. Ifyou are enthusiastic about a PIC contest, e-mail me and I’ll let Microchip know how you all feel.

Design contests have become an essential ingredient around here. With all of these present and future contests in the pipe, subscriberscan count on a lot of terrific projects covering a variety of great processors in the issues to come.

The Insanity of Success

INTERRUPT

l

[email protected]

96 Issue 142 May 2002 CIRCUIT CELLAR® www.circuitcellar.com

PRIORITY

Page 100: circuit-cellar2002-05.pdf

STILL THE WORLD’S MOSTPOWERFUL PORTABLE

PROGRAMMERS?

Dataman Programmers Ltd215 East Michigan AvenueOrange City, FL 32763Telephone (904) 774-7785Fax (904) 774-7796Home page: http://www.dataman.comEmail: [email protected]

$795inc 4mb ram

Orders received by 4pm will normally be despatched same day.Order today, get it tomorrow!

Surely not.Surely someone somewherehas developed a portable programmer thathas even more features, even greaterflexibility and is even better value formoney.Actually, no. But don’t take our word forit. Use the feature summary below to seehow other manufacturers’ products compare.

$1295

DATAMAN-48LV• Plugs straight into parallel port of PC or

laptop

• Programs and verifies at 2, 2.7, 3.3 & 5V

• True no-adaptor programming up to 48pin DIL devices

• Free universal 44 pin PLCC adaptor

• Built-in world standard PSU - for go-anywhere programming

• Package adaptors available for TSOP,PSOP, QFP, SOIC and PLCC

• Optional EPROM emulator

DATAMAN S4• Programs 8 and 16 bit EPROMs,

EEPROMs, PEROMs, 5 and 12V FLASH,Boot-Block FLASH, PICs, 8751microcontrollers and more

• EPROM emulation as standard

• Rechargeable battery power for totalportability

• All-in-one price includes emulationleads, AC charger, PC software, sparelibrary ROM, user-friendly manual

• Supplied fully charged and ready to use

S4 GAL MODULE• Programs wide range of 20 and 24 pin

logic devices from the major GAL vendors

• Supports JEDEC files from all popularcompilers

SUPPORT• 3 year parts and labor warranty

• Windows/DOS software included

• Free technical support for life

• Next day delivery - always in stock

Still as unbeatable as ever. Beware ofcheap imitations. Beware of falsepromises. Beware of hidden extras.If you want the best, there’s still only onechoice - Dataman.

Order via credit card hotline - phonetoday, use tomorrow.

Alternatively, request more detailedinformation on these and other market-leading programming solutions.

NEW MODEL

MONEY-BACK30 DAY TRIAL

If you do not agree that these truly are themost powerful portable programmers you can

buy, simply return your Dataman productwithin 30 days for a full refund