circuit cellar2002 03

100
7 9 25274 75349 03 > CIRCUIT CELLAR ® www.circuitcellar.com THE MAGAZINE FOR COMPUTER APPLICATIONS $4.95 U.S. ($5.95 Canada) EMBEDDED APPLICATIONS A PIC-Based iButton Reader High-Resolution Data Acquisition Creating A Web Link Monitor D/A Conversion Using One Pin #140 March 2002

Upload: tusaigon

Post on 07-Feb-2016

41 views

Category:

Documents


2 download

DESCRIPTION

mach dien tu

TRANSCRIPT

Page 1: Circuit Cellar2002 03

7 925274 75349

03>

®

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

A PIC-Based iButton Reader

High-Resolution Data Acquisition

Creating A Web Link Monitor

D/A Conversion Using One Pin

Page 4: Circuit Cellar2002 03

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 6: Circuit Cellar2002 03

LOGIN/REGISTER

SITE NAVIGATOR

Customize

Knowledge Centers

Product Reviews

Data Sheets

Guides & Experts

Ask Us

Circuit Cellar

Online Tools

App Notes

Webcasts

Careers

Resources

FAQ

g

DO YOU EXCEL IN ELECTRONICS?

Part 2: The Benefits of Using Excelby Aubrey KaganLast month, Aubrey took us through the basics of using Excel in the designprocess. In this second part of his series, we’ll see how we can benefit fromusing the program for working out worst-case scenarios, checking formulas,and getting a complete analysis of the circuit. And that’s just the beginning. February 2002

ARE YOUR CYGNALS CROSSED?

Taking a Look at Cygnal’s C8051F000by Fred EadyIn the Florida room, Fred finds himself in his usual predicament. He has new stuffhe’s not quite sure what to do with, but he’s dying to find out. It doesn’t take himlong to delve in and figure out the ins and outs of the C8051F000 and take usthrough the details. His prognosis: positive. February 2002

UPGRADING USING DATA PACKETS

Lessons from the Trenches—by George MartinDo you ever find yourself between a rock and a hard place? How about betweentwo hard and fast stem requirements? This month, George finds himself with asystem that needs to operate as fast as possible, and with as smooth anupgrade to the hardware and software as possible. Sounds sticky, but as always,he makes his way out of it with only a few adjustments along the way. February 2002

DAZED AND CONFUSED

Silicon Update Online—by Tom CantrellWith the start of a new year, we invariably resolve to try new things, at the sametime trying to remove some of the old clutter from our lives. This month, Tom dis-cusses one of his favorite topics, networking. He takes us through the good andbad of it, showing us that less cables (i.e., going wireless) doesn’t necessarilymean less clutter. February 2002

AN INTRODUCTION TO VHDL

Designing Hardware with SoftwareTechnically Speaking—by James AntonakosJames looks at designing a digital circuit using software, namely VHDL. You’llsee the benefit of using a simulated model in designing. And, with his detailedlook into the program, you’ll have no problem applying what you’ve learned.February 2002

THE MAGAZINE FOR COMPUTER APPLICATIONSCircuit Cellar Online offers articles illustrating creative solutionsand unique applications though complete projects, practicaltutorials, and useful design techniques.

RESOURCES

Each month CircuitCellar’s Resource Linksprovide helpful links andinformation on a variety offeatured topics.

• Win4Lin

by Brant Schroeder

• Digital Signal

Processing

by Brant Schroeder

Page 7: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 5

A PIC-Based Portable ID Reader for iButtonsMichael Collier, Ph.D.

High-Resolution Data AcquisitionMade EasyBrian Millier

A Web Link Monitoring SystemTom Petruzzelli

In-Circuit Emulator for the AT89Cx051 FamilyPraveen Deshpande & Prajakta Deshpande

Balancing D/A Conversion on One PinMariano Barrón & Javier Martinez

I APPLIED PCsReplacing Relays with Ladder LogicPart 1: Getting Ready for the ClimbFred Eady

I FROM THE BENCHSpy-Size Event LoggerJeff Bachiochi

I SILICON UPDATE SoC HopThe SequelTom Cantrell

COLUMNS

ISSUE

Task ManagerRob WalkerFun, Games, and Inside Information

New Product Newsedited by John Gorsky

Test Your EQ

Advertiser’s IndexApril Preview

Priority InterruptSteve CiarciaAutomobiles by Microsoft?

6

8

11

94

96

140

60

68

76

FEATURES 12

20

28

34

52

Page 8: Circuit Cellar2002 03

6 Issue 140 March 2002 www.circuitcellar.com

ll work and no play makes Jack a dull boy, or sothey say. But what happens when Jack’s idea of

fun turns out to be spending several months develop-ing a gadget or application? In that case, I’d say Jack

stands a good chance of winning $5000 in the Cypress MicroSystemsPSoC Design Challenge 2002 contest. Sure, a contest is supposed to besomething that you do for fun, but look at the top entries in our recentdesign contests and you’ll see that these contests aren’t exactly of thecounty fair pie-eating variety.

The contest administrator for Circuit Cellar gets the privilege of lookingover all of the entries for each contest and I’m always impressed with howthorough the majority of the entries are. I’ve heard plenty of firsthandaccounts about how much effort goes into these design contest projects(e.g., “I had to take a couple of days off from my day job so I could finishthe project before the deadline….”). It’s clear that among the top entries, agood amount of time is spent on the documentation and presentation of theproject. After all, if the judges can’t figure out what your project does, why itwas built, or if it works, how can they give you that perfect 10?

As I’m writing this column, the first remarks are coming in from thejudges of the Texas Instruments MSP430 contest that ended in December(official results will be posted on the Circuit Cellar web site in the first weekof March). Looking over the judges’ comments from the TI contest as wellas other recent design contests, it’s pretty easy to deduce the formula forputting together a successful entry. Here’s what it takes.

Obviously you need to apply solid design skills and maximize the featuresof the component, but don’t underestimate the importance of documentation.Imagine yourself as a judge, sorting through dozens of projects, having toopen five or six files for each project. Now imagine that you come to a proj-ect that has one Word file with photos, schematics, figures, and software list-ings all in one document that’s easy to read. Instead of spending most of theallotted time opening files and looking for chunks of random documentation,you spend the time scrolling along and getting a feel for the project.

We don’t expect you to be a document layout specialist, but a clear proj-ect presentation is like slipping the valet an extra $10. It’s a small price topay and it certainly won’t go unnoticed. (For the record, slipping the contestadministrator $10 to “look out for” your project is not the implication here.)

Now that you’ve got an insider’s tip, it’s time to put away your “winningisn’t everything” speech and get to work on your PSoC project. Jack may bedull, but I’m pretty sure $5000 could change that.

CIRCUIT CELLAR®

EDITORIAL DIRECTOR/PUBLISHERSteve Ciarcia

WEB GROUP PUBLISHERJack Shandle

MANAGING EDITORRob Walker

EDITORIAL PRODUCTION COORDINATORJennifer Huber

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

aFun, Games, and Inside Information

[email protected]

WIN A ZILOG EZ80 EVALUATION BOARD!FOR MORE INFORMATION ON THIS OFFER AND THE EZ80, GO TO

WWW.CHIPCENTER.COM/CIRCUITCELLAR/JANUARY02/C0102TS13.HTM

Page 9: Circuit Cellar2002 03

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 10: Circuit Cellar2002 03

NEWS

8 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

NEW PRODUCTEdited by John Gorsky

LOW CURRENT, HIGH-PERFORMANCE OP-AMPSThe MCP602x family of op-amps is designed for low-

current, high-performance applications. The family offersa cost-effective way to improve performance and increasethe operational life of battery-powered systems. Thesedevices are ideal forADCs, bufferingDACs and barcodescanning applications.

The MCP602x op-amps offer rail-to-railinput and output thatallows the full volt-age supply range tobe useful from 5.5 Vto 2.5 V. TheMCP6021 (single),MCP6022 (dual) andMCP6024 (quad) devices meet industry standard pinoutsin standard PDIP, SOIC, and TSSOP packages.

Featuring unity gain stability with a gain bandwidthproduct of 10 MHz, low noise (8.7 nV/rtHz), and a maxi-mum quiescent current (IQ) of 1.35 µA, the devices canbe used without costly, stabilizing circuitry. The low off-set voltage achieves low power consumption, minimiz-ing board-space usage and lessening design time andcomponent cost.

Pricing in 1000-unit quantities is $0.74 each for theMCP6021, $0.77 for the single with chip selectMCP6023, $0.95 for the dual MCP6022, and $1.38 for thequad MCP6024.

24-BIT ADC WITH ON-CHIP FLASH MEMORYThe ADS1218 from Texas Instruments is a 24-bit ADC

with on-chip flash memory. It is designed for industrialprocess control, portable instrumentation, and test andmeasurement applications such as weigh scales, tem-perature measurement, liquid/gas chromatography,smart transmitters, and pressure transducers.

Optimized for high-performance, low-power systems,the ADS1218 offers 24 bits of no missing code perform-ance, 22-bit resolution, and less than 1-mW power con-sumption. The precision on-chip voltage reference isaccurate to within 0.2% and has low drift (typically5ppm/C). Linearity error is guaranteed to be less than±0.0015% of full scale. The ADS1218 has 4-KB on-chipflash memory that is programmable over the 2.7- to 5.25-Voperating range, providing increased levels of customiza-tion for linearity, serialization, calibration, and data storage.

By combining such a high level of electronic circuitryon a small chip, the ADS1218 simplifies the design ofcomplex mixed-signal systems and reduces the need forexternal circuitry. The ADS1218 integrates an eight-channel multiplexer, programmable gain amplifier, inputbuffer, on-chip temperature sensor, burn-out currentsources, dual independent current DACs, on-chip voltagereferences, external differential reference inputs, selec-table data output rate, offset DAC, and eight program-mable digital I/O. The serial interface is SPI-compatible.

The unit comes in a 48-pin TQFP surface-mountpackage and costs $8.75 in1000-piece quantities.

bright CCT fluorescent backlighting and optionaltransflexive films for sunlight readability. The optionalhigh-accuracy, eight-wire touch screen is applied direct-ly to the LCD and matches the active and viewingareas of the display. The board measures 6.3″ × 4.3″ andrequires both 5 V (logic) and 12 V (backlight inverter).

Sample kits including the con-troller, display, and touch screencost $350 (color) and $250 (mono-chrome). The touch screen can beremoved on request.

LCD AND TOUCH SCREEN CONTROLLERThe CDS-1375 is an LCD and touch screen controller

that mounts directly to QVGA displays. It features anintelligent controller with an extensive command setthat allows OEM designers to simply and quickly createa GUI for color and monochrome 320 × 240 LCDs. It alsoincorporates serial communications, an eight-wire touchscreen controller, matching backlightinverters, all display voltages, and allmating connectors for direct mounting.

You can draw complex screens usingthe standard RS-232 serial interface byemploying the onboard processor’sgraphic primitive and font commands.An optional RS-485 interface for noisyenvironments is mounted on the board.

The CDS-1375 kit comes with achoice of several 5.7″ screens each with

Apollo Display Technologies, LLC(631) 580-4360Fax: (631) 580-4370www.apollodisplays.com

Texas Instruments(972) 644-5580Fax: (214) 480-7800 www.ti.com/sc/ads1218x

Microchip Technology Inc.(480) 792-7668www.microchip.com

Page 11: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 9

NEWSNEW PRODUCT68HC11E9 DEVELOPMENT BOARD

The Ep11E9 is a high-performance development boardthat combines a full-function, full-speed 68HC11Eseries hardware development system, an advanced train-er, and a versatile single board computer into one pack-age. The Ep11E9 offers the useful features of the Buffalomonitor and adds numerous enhancements at anextremely low cost.

For engineers, it’s a WICE in-circuit emulator system,a convenient prototype platform, and a single boardcomputer. For students, it’s a user-friendly microcon-troller trainer. You could use it tobuild a solid foundation of microcon-troller expertise and to create a realword application for a senior project.

The Ep11E9 includes user-friendlysoftware that runs on a PC underDOS and Windows. The board offerseasy file transfer, single-stepping,breakpoints, data watch for memoryand registers, symbolic debuggingcompatibility with most assemblersand compilers, jumper-free modeswitching and user program termi-nation with the Escape key.

The hardware includes a breadboard that doesn’t haveto be soldered, 12 extra output lines in ports F and G,two logic probes, three robot servo outputs, an LCD con-nector, 4 × 4 keypad connector, and a fast SPI expansionport. It also includes dual speakers, a four-digit LED dis-play, potentiometer, two debounced switches with high,low, toggle, and RS latch outputs, a 60-pin EVBU-com-patible connector, and six on-board pulse generators.

With its exclusive phantom monitor technology, theEP11E9 preserves all interrupt vectors including reset.

All on-chip RAM ($00–$1FF), EEP-ROM, and 28 KB of external emula-tion RAM ($9000–$FFFF) are availablefor user applications; there is no pre-empted chip memory. The deviceincludes an RS-232 cable for connectsto a PC serial port and there’s an ACadapter to power the board.

The Ep11E9 costs $99.

EVBplus.com(630) 894-1440Fax: (630) 894-9550www.EVBplus.com

Page 13: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 11

CIRCUIT CELLAR Test YYour EEQ

Problem 3—What are the four conditionsthat lead to a deadlock among processesthat are competing for resources?

Contributed by Dave Tweed

Problem 4—How is a wedge or trapezoidpattern on an oscilloscope used to evaluateAM transmitter performance?

Contributed by Dave Tweed

Problem 1—Why does the power dissipa-tion of Darlington transistors tend to behigher than that of single transistors inswitching applications?

Contributed by Dave Tweed

Problem 2—What is the frequency of oscil-lation of the following circuit? Assume eachinverter delay is T.

Contributed by Naveen PN

What’s your EQ?—The answersand 4 additional questions andanswers are posted at www.circuitcellar.comYou may contact the quizmastersat [email protected]

8 more EQ

questions

each month in

Circuit Cellar Online

A B C Y

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 03

12 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

dentificationtechnology is use-

ful in many forums.The iButton, also known

as the Dallas Chip, provides a meansof personal identification by generat-ing a unique binary number whenstimulated by a power source. In thisarticle, I’ll describe a reader that usesthe iButton to decode, check, display,and store ID numbers.

Although the individual iButtons areinexpensive, the reading and recordingsystems can be costly. This is why ateam of engineers at the NationalUniversity of Science and Technologyin Zimbabwe developed the readerproject. It is intended for use bypatrolling security guards or at check-points. You may also use the reader asa diagnostic tool for checking possiblemalfunction of individual iButtons.

A number of African universitiesalready use the reader for campussecurity and inventory purposes, suchas tracking equipment, tool manage-ment, inventory control, cafeteriaadministration, and library loans. Theunit is portable and battery-poweredto allow use by patrolling securityguards. The security team also canconnect it to the serial port of a per-sonal computer to display data. So

that you can build your own reader, inthis article I’ll provide the mechanicaldesign, circuit configuration, and soft-ware basis together with details of thecyclic redundancy check method usedto ensure accuracy.

The iButton provides a means of per-sonnel identification using a passiveelectronic circuit carried by the user.The chip is housed in a coin-sized pack-age that can be conveniently affixed toa key ring or integrated into a plasticidentification card. Each chip containsROM that is uniquely programmedwith a 56-bit number, providing 72,000trillion distinct identification values.

DETAILS OF THE iBUTTONTo provide identification, the

iButton is inserted into a socket on thereader equipment, which detects itspresence and provides the energy need-ed to drive the chip circuitry. [1] Whencontact is made, a series of code pulsesare sent back to the iButton. On receiptof these, the chip proceeds to transmita series of bits, each being synchronizedby signals from the reader. These bitsrepresent a unique identification num-ber, a product version code, and acyclic redundancy check value.

The circuit configuration involves abus network in which the chip con-nects to the reader by a single wire.This is normally pulled to logic 1 by apull-up resistor. Both the iButton andreader are connected to the bus in anopen-collector configuration. Thus,they can independently pull the busvoltage low to logic 0.

The device is a rugged data carrierwith 64-bit ROM that communicateswith the reader by means of a singlewire. The durable microcan is resistantto environmental hazards such as dirt,

A PIC-Based PortableID Reader for iButtons

iWe’ve seen homesecurity applicationsfor the Dallas iButton,but the practicality ofthe technology makesit a good candidatefor a campus securitysystem too. Designedfor an African univer-sity, this project pro-vides a cost-effectivereader for the iButtonsecurity system.

Michael Collier, Ph.D.

FEATUREARTICLE

16.25 mm

One-wire bus connection

17.35 mm

Groundconnection

Figure 1—The iButton has a sturdy housing about thesize of a coin. The central disk provides the one-wireconnection and the rest of the surface is grounded.

Page 15: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 13

onto the bus, thereby causing the idlestate voltage to be high and allowingany device to pull the bus low. ThePIC is particularly suitable in thisrespect in that it provides one outputpin in an open-collector configuration.This pin is used for transmission tothe bus. A second pin that’s program-med for input is used for reception.

The reader display consists of a 32-character LCD, the LM052L, pro-grammed to show alphanumeric char-acters. [3] The LM052L uses serialinput in the form of either commandsor data to control the representationon the screen. [4]

The circuit for the reader is shownin Figure 3. A potentiometer controlsthe brightness of the LCD. You usethe Next push button to move to thefollowing display item. A toggleswitch changes the mode from readingan iButton to the recovery of thestored ID numbers.

SOFTWAREAlthough the Dallas-One-Wire

(DOW) network operates in an asyn-chronous mode, the time parametersfor reading and writing operations arefairly restricted. The PIC software,therefore, uses a basic time period of10 µs derived from the system clockfor all timing. After the initial dia-logue between the iButton and thereader, the latter sends a series ofbytes instructing the chip to under-take a task. This usually involves out-putting the ID number stored in theROM of the iButton.

Take a look at the timing sequencein Figure 4, in which a reset pulsefrom the reader is acknowledged by a

moisture, and shock. The coin-shapedprofile is self-aligning with a matingconnector on the reader. Accessoriespermit the device to be mounted onplastic key tabs, photo-ID badges, orprinted circuit boards. Figure 1 showsthe physical dimensions of the device.

The protocol defines bus transac-tions in terms of the bus state duringspecified time slots that are initiatedon the falling edge of synchronizedpulses from the reader. All data is readand written with the least significantbit first. The 64-bit number generatedby the iButton comprises three com-ponents as follows: the family code(product version number) is bits 0through 7, the identification number(unique value) is bits 8 through 47,and the CRC value (computed inter-nally) is bits 48 through 63.

STRUCTURE AND OPERATIONFigure 2 shows the unit housed in a

130-mm × 80-mm × 40-mm plasticbox, which has external connectionsfor the power supply and serial con-nector. The LCD measures 2 × 16. Abrightness control knob for the screenand a Mode switch are provided on thefront panel together with a Next pushbutton for polling through operations.

At power-up, the LCD shows thatthe system is ready. When an iButtonis inserted into the socket, the equip-

ment attempts to read its ID number.If the read is successful, the ID num-ber and product code are displayed,but if not, an error message is gener-ated. Pressing the Next button causesthe system to revert to the readystate. If the Mode switch is toggledfrom Current to Stored, then theLCD panel will display one of thelast nine stored ID numbers. Pressingthe Next button again will scrollthrough the values previously storedin the nonvolatile memory.

For interfacing to a computerizedsecurity system, the reader has a stan-dard D-type connector for cabling tothe COM port of a personal computer.Whenever a new ID number is read,the value is transmitted through aMAX232 protocol converter to thehost. The software in the receivingcomputer compares the incoming datawith a look-up table to determine thename and status of the person repre-sented by the ID number. This infor-mation, other relevant personaldetails, the time, plus the location ofthe identification are displayed inwindowed format on the PC.

CIRCUIT CONFIGURATIONThe basic processing unit of the

reader is a PIC16F84 microcontroller. [2]With the one-wire bus, connecteddevices should be logically ANDed

Brightnesscontrol

Mode switch

LCD

Serial portconnection

Nextbutton

iButtonconnector

Figure 2—The reader unit is housed in a palm-sizedplastic box. Controls and displays are on the top face,with the serial connector on the side.

Figure 3—The reader circuit uses a PIC device to control reading the iButton, displaying results, and communicat-ing with the serial port. The unit’s LCD is controlled by a potentiometer.

Page 16: Circuit Cellar2002 03

14 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

The calculation of the CRC followsthe hardware model shown in Figure 5,which is comprised of a shift registerwith feedback through exclusive-ORgates to certain stages. A Dallasapplication note states that the algo-rithm behind this is capable of detect-ing almost all possible errors in the56-bit number. [6]

You can calculate the CRC in soft-ware by two methods. [7] One is toevaluate all possible CRC values forinputs in the one-to-255 range andstore them in a look-up table. Thismethod results in fast evaluation ofthe CRC, but the penalty is the large

presence pulse from theiButton. The reader thentransmits an 8-bit coderequesting the ID informa-tion, after which theiButton transmits the64 bits of relevant data.Synchronization of theiButton bits is achieved bysending a series of clockingpulses from the reader, thefalling edges of which stim-ulate the transmission of bits from thechip to the reader.

The DOW network uses an 8-bitCRC for validation of an ID number.[5] Experiments have shown that thereare mechanical contact problemswhen inserting the iButton into thereader, which means that severalattempts are usually needed before anaccurate reading is made. Therefore,the software takes the form of a loopthat repeatedly reads the value of thenumber and compares it to the CRCuntil a match is attained. A limit of10 tries is set so that faulty or falsechips can be detected.

amount of program memoryoccupied by the table. In thePIC16C84, the table woulduse one quarter of the memo-ry and present additional dif-ficulties because of the page-boundary complications withthe program counter.

The second method, whichis used in the reader, is to cal-culate the CRC value in realtime for each successive byte.

Although this uses marginally moremachine cycles, it reduces the code toa handful of instructions. The Parallaxassembly language subroutine for thisoperation is shown in Listing 1.

The storage feature is particularlyuseful for patrolling security guards.The ID numbers are allocated loca-tions in the 64 bytes of nonvolatilememory of the PIC. Of these, 60 bytesare used for storage of nine 7-bytenumbers and an additional byte con-tains a pointer to the ID currentlybeing displayed. Successive pressing ofthe Next button causes scrollingthrough these values.

Resetpulse

Presencepulse

Code bitsto iButton

111 1 0 0 1

iButton response

Synchronizing trailingedges for iButton bits

Reader pull-up/down

Figure 4—The reader always initiates dialogue. It stimulates responses from theiButton in the form of either a presence pulse or data bits.

Page 18: Circuit Cellar2002 03

A routine in the reader handles sig-nals for the RS-232 protocol used tocommunicate between the reader andcomputer. The operation follows amaster-slave arrangement, where thereader initiates all communication,thereby interrupting the computer tohandle the serial data. The hardwareconnection is straightforward.

DATA HANDLING AND DISPLAYThe data from the portable unit is

received via the serial port of a PC. Thesoftware resident in this equipment is

TEST RESULTSBefore the implementation of the

cyclic redundancy check, it was diffi-cult to obtain repeatable readings fromthe reader. However, the addition of theCRC feature and a routine to ignoreany readings of zero has increased thereliability of the readings to nearly100%. Several different iButtons weretested on the device, all giving accuratereadings over a wide time span.

The development team inserted adata-gathering routine into the pro-gram to check how many retries weretaken before achieving a valid reading.The average came to approximatelythree, although this increased when

16 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

written entirely inC. It commenceswith the look-upprocess whereby theID number is used asa reference to deter-mine the name, posi-tion, status, and stu-dent/staff number ofthe person owningthe iButton. Thisinformation togetherwith the time andlocation of the con-

tact is stored as a record in a disk file. Recovery of the information may be

achieved from the original computer orcampus Intranet (by any author-ized person). In this way, thesecurity department can obtainstatistics about the locations ofpeople and can trace the move-ment of an individual if required.The display takes the form of ascrolling window in which allrelevant information for a fixedperiod is available. A typical dis-play is shown in Photo 1.

Photo 1—The windowed computer display indicates details of personnel, times,and places. This information is derived from the iButton output plus look-uptables in the campus security database.

Figure 5—Regarding the hardware, the CRC algorithm used inthe DOW system is equivalent to an 8-bit shift register withfeedback between certain stages.

CRC value (8-bit parallel)

Data input (8-bit serial)

!"#$%&%''"(#$)*+

,)!'!!)%-'"),)!).)!*'!)-'")

)!&*/!&!)0!&,)1)#232-!&%

Page 19: Circuit Cellar2002 03

• Over 300 Bytes of RAM

• 256 Bytes of Data EEPROM

• External & Internal Interrupts

• 3 10 bit A/D Converters

• 2 Capture and Compare

• Internal Adjustable Vref

• + / - External Vref

• 3 Timers, 2 PWM

• UARTS, I2C, SPI

• Plus More!

More Power...The New Basic Micro Atom, offers more in the same

package you are already familiar with. Built-in features

like upgradeable firmware, Analog to Digital, Hardware

Serial, In Circuit Debugging, 32 Bit Math, 32 Bit Floating

Point Math and more !

The Atom includes powerful expanded BS2 syntax

compatible software with commands such as; OWout,

OWin, ADin, LCDwrite, If..Then..Elseif..Else..Endif,

LCDread, HPWM, Hserout, Hserin, Do..While,

Repeat..Until and more !

To order visit www.basicmicro.com or call

us at 734-425-1744 M-F 10 AM to 6 PM EST.

Development Kits

Only $149.95

Features• Graphical Debugging (ICD)

• More Software Commands

• 32 Bit Integer Math

• 32 Bit Floating Point Math

• BS2p Compatible Syntax

• Expanded BASIC library

• Firmware upgradeable

• Unlimited Support

• Free Software Updates

• Plus More!

Kit Includes: Development Board, Atom,

Manual, Cable and power supply

Easy to use multi document interface. Open as many

files as you want all in the same interface. Easily

navigate your files with the built-in explorer window.

Powerful Software

Watch your program run step-by-step as the Atom

executes each line of code. Easily debug your code.

Bring your programs to life quicker than you ever

thought possible !

In Circuit Debugging

No more strategically placing debug

statements throughout your program!

Not only can you watch your program

execute live, you can keep an eye on

every variable and ram location as they

are affected by your program. Each

program variable is displayed in binary,

hexadecimal and its real values.

Watch it Come to Life

Atom-IC Module

Only $59.95

Microcontrollers Made Easy™The Basic Atom is a registered trademark of Basic Micro Inc.

Page 21: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 19

the iButton was deliberately insertedskewed or with light pressure. Forevery test in which a functioningiButton was used, a valid reading wasachieved within 10 tries.

GOOD NEWS SPREADSThe measurements for the proto-

type were welcomed by the adminis-tration of the National University ofScience and Technology. In fact, theschool commissioned the ElectronicEngineering Department to develop acampus-wide security network basedon the iButton.

The flexibility of the reader unit,which can be used in both portable andnetworked modes, is ideal for a largeuniversity site where both external andinternal security is of importance. Thefirst phase of the development tookplace in the library, where identifica-tion of personnel is paramount. Fromthere, we extended the system to othercampus facilities. I hope that the typeof local development realized in thisproject will continue spreading to otherinstitutions in Africa, as well. I

Michael Collier, Ph.D., is the chair-man of the Department of ElectronicEngineering at the NationalUniversity of Science and Technologyin Bulawayo, Zimbabwe. His researchinterests include embedded systems,gate-array techniques, and mecha-tronics applications.

REFERENCES[1] Dallas Semiconductor, “Serial

Number iButton,” DS1990A, 1995.[2] Microchip Technology Inc.,

Microchip 2001 TechnicalLibrary, 2001.

[3] Hitachi Corp., “LM052L.” [4] ———, “How to Use Hitachi's

Built-In Controller Driver LCD-IIDot Matrix LCD Module,”HD44780.

[5] W. Stallings, Data and ComputerCommunications, 6th ed.,Prentice Hall, Upper SaddleRiver, NJ, November 2, 1999.

[6] Dallas Semiconductor,“Understanding and Using CyclicRedundancy Checks with DallasSemiconductor iButtonProducts,” 27, 1995.

[7] J. Buller, “High Speed SoftwareCRC Generation,” EDN, no. 25,vol. 36.

Listing 1—The CRC subroutine takes the current data and CRC values and uses them to compute new 8-bit values for the CRC.

This subroutine will use the value of "data" to update the value of "crc" using the DOW CRC algorithm.*************************************************************calc_crc mov i, #08hcrc_loop mov temp, data

xor temp, crcrr tempjnc zero //jump if (data_bit EOR crc.0) = 0xor crc, #00011000b //if feedback loop, then EORsetb crr crcjmp continue

zero clrb crr crc

continue clrb crr datadjnz i, crc_loopret

;

SOURCESiButtonDallas Semiconductor, Inc.(972) 371-4000www.dalsemi.com

LM052L LCD moduleHitachi Corp.www.hitachi.com

PIC16F84 MicrocontrollerMicrochip Technology Inc.(480) 786-7200www.microchip.com

Page 22: Circuit Cellar2002 03

20 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

ost modern ana-lytical equipment

used in chemistry labstoday comes equipped

with a computer for control/data acqui-sition. However, there are still manyhigh-quality older instruments, suchas gas and liquid chromatographs, inuse that can benefit from the additionof a high-resolution data system.

The data acquisition systemdescribed in this article was built tohandle a dual-detector HP5890 GasChromatograph made by Hewlett-Packard. The basic design of thisinstrument has changed little over thepast 20 years, and many of these unitsare in the field still working faithfully.My design includes instrumentationamplifiers for each channel so that theunit can be readily modified to handlea wide range of input voltages.Because this unit also has differentialinputs, it can replace a strip chartrecorder for many different uses.

To achieve high resolution, I chosethe Burr-Brown (now Texas Instruments)ADS1212 delta-sigma converter for anumber of reasons. First, it has 20-bitresolution at 10 Hz, which is an idealdata rate for gas chromatography.Additionally, the ADS1212 features abipolar input. In chromatography, the

signal can drift below zero at times, soa bipolar input is handy. Also, timemust be measured accurately.

The ADS1212 uses a quartz crystalclock and derives its data acquisitionrate from a programmable divider fed bythis quartz clock signal. This providesaccurate data acquisition rates that canbe easily programmed by you. I providedremote-start capability to synchronizedata acquisition with the sample injec-tion. Apart from the ADCs themselves,an Atmel AT90S2313 is used to set upthe ADCs and communicate with thehost PC through the COM port. VisualBasic application software tailored totwo-channel data acquisition from a gaschromatograph is available to downloadfrom the Circuit Cellar web site.

DATA ACQUISITION USING ADCSBefore discussing the specific needs

of chromatographic data acquisition,let’s review the different analog-to-dig-ital converters available. Althoughthere are subtle variations, ADCs basi-cally fall into three main categories:integrating, successive approximationregisters (SAR), and flash.

Integrating converters include boththe dual-slope integration types usedfrequently in digital panel meters andmultimeters as well as the delta-sigmatype used in this design. The conceptlends itself to both high resolution andgood noise rejection, with the trade-offthat the conversion rate is slow.

SAR converters are middle-of-the-road devices. They don’t have as higha resolution as the integrating types(generally 16 bits or less of resolution)but they are much faster. It isn’tuncommon to see SAR converters thatcan convert an analog signal to a 16-bit digital output in 10 µs or less.

Lastly, flash converters are by farthe fastest converters available, withthe ability to convert video and RF sig-nals with frequencies in the hundredsof megahertz. The trade-offs here arethat they consume more power thanthe previous types and the resolutionis generally only 6 to 8 bits. A trueflash converter needs a discrete com-parator for each of the valid bit combi-nations, so an 8-bit converter wouldrequire 256 comparators. There areconverters on the market that com-

High-Resolution DataAcquisition Made Easy

mOn our workbenches,there’s a good amountof analytical equip-ment that lacks a PCfor control or dataacquisition. That’s notto say that this hard-ware is obsolete, itjust needs updating.Retrofitting hardwarecan be a fun and cost-effective alternative toreplacement.

Brian Millier

FEATUREARTICLE

Page 23: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 21

mine. A programmable gain amplifier(PGA) is included with available gainsbetween one and 16. Figure 1 is ablock diagram of the ADS1212.

These features make the ADS1212ideal for the direct measurement oflow-level signals such as those pro-duced by strain gauges and RTDs.Often in these cases, the low-level sig-nals are best measured using an A/Dconverter that is electrically isolatedfrom the (noisy) power supply thatfeeds the computer or microcontrollerthat’s connected to it. The ADS1212features a serial interface that, whenminimally configured, consists of onlyfour signals. These can be easily sentthrough optocouplers to achieve elec-trical isolation. Furthermore, theADS1212 requires only 1.4 mW ofpower, which can be supplied by a bat-tery or a small DC/DC converter.

Note that the ADS1212 requiresonly a single 5-V power supply foroperation. The voltage range on boththe AINP and AINN inputs is 0 to 5 Vwith the restriction that the voltagenever goes outside this range by morethan 30 mV or excessive leakage cur-rent will flow. Although the datasheetdoesn’t say what will happen if youdo, I assume this will result in damageto the device. [1]

If the signal you’re measuring is apositive, single-ended signal less than5 V in amplitude, you could ground theAINP pin and feed your signal directlyinto the AINN pin. The PGA providesmany different full-scale ranges (more

bine elements of SAR and flash con-version technology to provide resultsthat fall somewhere in the middle interms of both speed and resolution.

In gas chromatography (GC), signalpeaks are what is being measured. Theratio of the smallest peaks to the largestcan be thousands to one. Peaks are notalways the same shape. And, becauseit is the area under the peak that mat-ters, it’s important that a sufficientnumber of samples be gathered to allowthis area to be accurately calculated.Fortunately, chromatographic peaksare generally more than 1-s long, so asample rate of 5 to 20 Hz is adequate.

Equally important is the fact thatthe lower amplitude peaks often con-tain a substantial amount of noise at60 or 50 Hz plus its harmonics. Success-ful measurement of these signals canbe accomplished only by using a con-version scheme that integrates the sig-nal over a period that is an integralmultiple of power line cycles (PLCs).

SAR converters, with sampling win-dows measured in microseconds, arenot appropriate for signals such as thosefound in chromatography. The delta-sigma conversion scheme used in the’1212 inherently integrates the signalover the sample interval, so with theright choice of sample rates, the powerline noise rejection can be effective.

In chromatography, the elapsed timebetween sample injection and thedetection of each peak (called reten-tion time), is as important a measure-ment as the area of the individual

peaks. It’s important, therefore, thatthe data collection rate be extremelyaccurate, which means that it must bebased on a crystal-based clock.

As mentioned earlier, data rates of5 to 20 samples per second are com-monly used, and the ADS1212 can beeasily programmed to achieve theserates using a common 2-MHz crystal.Having the ADC do its own sample-rate timing simplifies the firmwareneeded in the associated microcon-troller and allows the use of an inex-pensive ceramic resonator for themicrocontroller’s clock.

ADS1212I have to admit that the “AD” pre-

fix led me to grab the Analog Devicesdata book a few times when looking

up specifications for this device.Over the past 20 years, I’ve got-ten accustomed to many dataconversion products fromAnalog Devices, which all startwith the corporate initials.However, this device is actuallymade by Burr-Brown.

This ADC’s main feature is itshigh resolution: 20 bits at 10 Hzdropping to 16 bits at 1 kHz. Itfeatures differential inputs,which is an important consider-ation when dealing with low-level signals commonly associ-ated with high-resolution meas-urements. The converter isbipolar, which is important inmany applications, including

2.5-VReference

3.3-V Biasgenerator

Microcontroller

Instruction register

Command register

Data output register

Offset register

Full-scale register

Serial interface

9

87417163 18

10

DGND

SCLK

SDIO

SDOUT

DVDD

1112

13

6 5 15 14

*DSYNC *CS MODE *DRDY

Clock generator

AGND AVDD REFOUTREFIN VBIAS XIN XOUT

AINP

AINN

1

2Third-orderdigital filter

PGA

Modulator control

Second-orderdelta-sigmamodulator

Figure 1—The ADS1212 high-resolution ADC contains its own microcontroller, which explains both its versatilityand programming complexity.

MSB LSB

R/*W MB1 MB0 0 A3 A2 A1 A0

Data transfer size

MB1 MB0 Transfer size

0 0 1 byte

0 1 2 bytes

1 0 3 bytes

1 1 4 bytes

Register address

A3 A2 A1 A0 Register

0 0 0 0 Data output register (DOR)

0 1 0 0 Command register (CMD)

1 0 0 0 Offset calibration register (OCR)

1 1 0 0 Full-scale calibration register (FCR)

Figure 2—For bit R/*W, bit 1 is a read and bit 0 is a write.

Page 24: Circuit Cellar2002 03

22 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

PROGRAMMING THE ADS1212I always get nervous when the

datasheet for a peripheral such as anADC is longer than the datasheet ofthe microcontroller that I’m using inthe project. In the case of the

on this later). Alternatively, if youwere reading a differential signal,from a bridge for example, youcould use the AINP and AINN pinsdirectly, assuming that the combi-nation of input voltage and PGAgain setting keep the signal in the0- to 5-V range.

I’ve used the ADS1212 for severaldifferent projects, but have neverfed a signal directly into it. Myfirst experience with it involvedmeasuring small differences intemperature using a platinumresistance thermometer (RTD) in abridge configuration. In that case, Ineeded more signal amplificationthan the internal PGA would pro-vide, and decided to use an instru-mentation amplifier ahead of theADS1212. I basically followed anapplication example included inthe ADS1212 datasheet. [1]

It’s common practice in chro-matography to set the quiescentoutput signal level at 10% to 20%of full scale to allow for negativebaseline drift using the offsetadjustment available in the instru-ment. This provides a unipolaroutput signal, which is generallyground referenced. Doing thatwould have allowed me to feedthe signal directly into the INPpin of the ADS1212, with theAINN pin connected to ground. Ichose instead to use an instru-mentation amplifier in this projectfor a number of reasons.

The primary reason concernedprotection of the ADS1212’s inputs.Whenever you are measuring asignal from an independent instru-ment, there are many chances forstray voltages to be applied to thedata acquisition system. The inputrange of the ADS1212 is only 0 to5 V, and there is no guarantee thatit will be powered up wheneverthe GC instrument is on. TheADS1212 comes in an 18-pin SOICpackage, so it’s impossible to justplug in a new one if damage occurs.By using an inexpensive INA118instrumentation amplifier, I get inputprotection to ±40 V as well as a widerange of gain adjustment to supplementthe internal PGA of the ADS1212.

ADS1212, programming it to workas desired is somewhat challeng-ing, so I’d like to describe in detailthe way I went about it.

The ADS1212 interfaces to itscontroller using an SPI-compatibleinterface. Unfortunately, SPI is nomore of a “standard” than RS-232(i.e., there are many variations inits implementation). Although theADS1212 is designed to be able toadapt to most of these variations,you must specify all of theseparameters during programming.

To begin with, the ADS1212 iscapable of operating in eitherMaster or Slave mode. In Mastermode, it will power up withdefault parameters and start col-lecting and sending data on itsown. For the microcontroller tochange the defaults, it must sendthe ADS1212 new instructions,following a protocol and timingdictated by the ADS1212. Thisarrangement is a bit awkward touse in practice because microcon-trollers are generally the masterSPI device. In most cases, theADS1212 is operated in Slavemode, which allows the micro-controller to dictate the timing ofthe data transfers. Slave mode isused in this project; set the modeby grounding the MODE pin onthe ADS1212.

The ADS1212 can be configuredto use either a two- or three-wireSPI interface. The ground wire istraditionally not counted whenusing these definitions. In thiscase, you are also not counting the*CS line of the ADS1212 or sever-al handshake lines, which are alsogenerally required.

Therefore, the distinctionbetween the two-wire and three-wire interface is the optional useof the SDOUT line. A two-wireinterface uses the clock signalSCLK and the SDIO line as a bidi-rectional data line. A three-wire

interface adds the SDOUT line forsending data out of the ADS1212. Thisinterface also redefines the SDIO lineas an input line for data into theADS1212. The operational interfacemode of the ADS1212 is governed by

Byte 3MSB LSB

BIAS REF0 DF U/*B BD MSB SDL DSYNC-

-DRDY

Mode bits: MD2–MD0

0 0 0 Normal

0 0 1 Self-calibration

0 1 0 System offset calibration

0 1 1 System full-scale calibration

1 0 0 Pseudo system calibration

1 0 1 Background calibration

1 1 0 Sleep

1 1 1 Reserved

BIAS—Turns internal bias supply on/off

REF0—Turns internal reference on/off

DF—Two's complement data format is used when DF is a zero

U/*B—When this bit is a zero, the data output is bipolar.

When this bit is a one, the data output is unipolar.

BD—The byte order is MSB to LSB when BD is a zero.

The byte order is reversed when BD is a one.

MSB—The bit order is MSB to LSB when this bit is a zero.

The bit order is LSB to MSB when this bit is a one.

SDL—When the serial data output bit is a zero, SDIO is a

bidirectional output; when it's a one, the SDOUT is the output.

DSYNC—Writing a one to this bit is the same as toggling the

*DSYNC pin low, which is used to synchronize multiple

ADS1212 devices. Reading this bit is the same as monitoring

the state of the *DRDY pin on the ADS1212.

Byte 2MSB LSB

MD2 MD1 MD0 G2 G1 G0 CH1 CH0

Gain bits: G2–G0

0 0 0 Gain = 1

0 0 1 Gain = 2

0 1 0 Gain = 4

0 1 1 Gain = 8

1 0 0 Gain = 16

Byte 1MSB LSB

SF2 SF1 SF0 DR12 DR11 DR10 DR9 DR8

Byte 0MSB LSB

DR7 DR6 DR5 DR4 DR3 DR2 DR1 DR0

Turbo mode rate bits: SF2–SF0:

0 0 0 Turbo mode rate = 1

0 0 1 Turbo mode rate = 2

0 1 0 Turbo mode rate = 4

0 1 1 Turbo mode rate = 8

1 0 0 Turbo mode rate = 16

Figure 3—Not all turbo modes are available for gains greater thanone. Channel selection bits 1 and 2 must be zeros for theADS1212. They select the input mux channel.

Page 25: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 23

the value of bit 1 in byte 3 of thecommand register. For a given wiringconfiguration, this bit must be setproperly right from the start or properdata exchange will not occur.

How hard can it be to send out theright command to achieve this? Thismay seem easy, but it isn’t, becauseyou still have to ensure that the micro-controller and the ADS1212 agree onseveral other SPI variables. To beginwith, SPI data can be sent LSB toMSB or MSB to LSB. The ADS1212always expects data to come in MSB-first, so make sure that the microcon-troller’s SPI hardware (or softwareroutine) is set up this way. However,the ADS1212 can return data ineither of these formats, so you haveto make sure bit 2 of byte 3 in thecommand register is set to zero if youwant the data coming in to match theformat of the data going out.

I’ll also mention that the byte orderfor multi-byte register reads can bespecified by bit 3 of byte 3 in thecommand register. Because the orderis fixed for writes to the device, it

makes sense to follow the sameconvention for the data comingback from the device.

Motorola originally inventedthe SPI standard. The company’shardware SPI ports could be pro-grammed for four different com-binations of clock phase andpolarity; other manufacturersused variations on this scheme.In any case, the ADS1212expects its SCLK signal to below when inactive, data to beshifted in and out on the risingedge of the SCLK signal, and data tobe stable on the falling edge of SCLK.In this project, the SPI port is imple-mented in software; you have to spec-ify this particular convention in theroutine’s parameter list.

Having considered the points I’vejust discussed, you can now assumethat the microcontroller and theADS1212 are on the same wavelengthso to speak. However, data sent fromthe microcontroller must be directedto the correct ADS1212 register (andyou must specify the desired

ADS1212 source register for readoperations). In addition to this, youmust specify how many bytes you’retransferring as well as whether a reador write transfer is to take place.

You may achieve this by precedingevery data transfer in or out of theADS1212 with a 1-byte data write tothe instruction register (see the formatin Figure 2). Note that the datasheetincludes the complete list of address-es (needed only to access the registersI discussed on a byte-by-byte basis). [1]As an example, to write to the com-

Photo 1—I broke up the circuit into two PCBs because itworked well in the past. I’ve used the dual ADS1212 ADC frontend (right) with several projects that required different micro-controllers and associated support chips.

Page 26: Circuit Cellar2002 03

24 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

TMR of one, gain of four,Bipolar mode, two’s comple-ment output, and a three-wireSPI configuration. It turns onthe REF0 output, turns off thebias supply, and sets the dataoutput format to match thatof the data input, in terms ofbit and byte order (most signif-icant bit and byte first). It thensends the same parameters,but changes the status to Self-Calibrate mode, which causesthe device to perform a com-plete calibration, prior to use.

After self-calibration com-pletes, the ADS1212 will start con-verting data at a 10-Hz rate. At thistime, the conversion-complete statuscan be polled by the microcontrollerby waiting until the *DRDY pin goesfrom high to low. To read the conver-sion result, send a byte to the INSRregister of the ADS1212, which speci-fies a read operation of 3 bytes withthe data output register as the source(C0 hex). The microcontroller thenclocks in 3 bytes of data, which is thevalue of the last conversion.

The actual full-scale input requiredto produce a full-scale digital outputfor any given gain setting is differentthan you might expect at first glance.The ’1212 contains a built-in 2.5-V ref-erence, and its conversion processrequires twice this value at the input toprovide a positive FS digital output (ortwice this amount of negative input toprovide the negative FS digital output).

To provide a bipolar capability usingthe INA118 instrumentation amplifier,both the AINN of the ADS1212 and theINA118’s output reference pin arebiased using the 2.50-V reference out-put. Choosing a gain of four producesfull-scale digital outputs with anINA118 output range of 1.25 to 3.75 V.This is well away from the power sup-ply rails, which is important.

I haven’t yet mentioned that theADS1212 performs digital filtering,implemented as a sinc3 filter response:

Figure 4 is a normalized response curvefor the filter. The –3-dB point of this

mand register (four bytes long), avalue of 01100100 (64 hex) would besent, followed by the actual 4 bytesintended for the command register.

With this knowledge, you can con-figure the ’1212 for the desired opera-tion and data rate using bytes 3 through0 of the command register, as shown inFigure 3. Note that not all turbo modesare available for gains greater than one(the datasheet states the details).

DECIMATION RATIO BITSThese bits set the decimation ratio,

or the number of modulator resultsthat are used in the digital filter, tocompute each individual result. Assuch, they set the data rate with:

where fDATA is the data rate, fXIN thecrystal frequency of the ADS1212, andTMR is the Turbo mode rate.

In this project, for example, a deci-mation ratio of 1561, TMR of one, anda 2-MHz crystal result in a 9.9968-Hzdata rate. A 9.9968-Hz data rate is asclose to a 10-Hz rate as is possibleusing a common crystal.

Turbo mode rates greater than onecan be used to provide a higher resolu-tion at higher data rates. In this proj-ect, the data rate was low, so a Turbomode rate of one was used because itminimizes power dissipation andincreases input impedance.

The ADS1212 initialization routinein my program first sets the device inNormal mode at a 10-Hz data rate,

0 1 2 3 4 5 6

0

–20

–40

–60

–80

–100

–120

–140

–160

Frequency (Hz)

Gai

n (d

B)

Figure 4—The sinc3 filter provides excellent noise rejection atexact multiples of the sample rate. It also produces at least 40 dBof rejection of nonharmonically related signals that are at leasttwice the data rate.

Page 27: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 25

Figure 5—The two instrumentation amplifiers and ADCs make up the bulk of the circuit. An AVR microcontroller does the ADC initialization and passes the data to the host PC .

Page 28: Circuit Cellar2002 03

26 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

filter is 0.262× the data rate. This proj-ect uses a data rate of 10 Hz and theresponse to a sine wave signal of 2.6 Hzwould be down 3 dB. GC peaks are nor-mally 1 s or longer in length, so theyare only slightly attenuated. Power-linenoise at 60 Hz and its harmonics areattenuated by more than 100 dB.

A side effect of the third-order digi-tal filtering involves the fact that alldigital outputs are a composite of thelast three conversions. In practice, thismeans that the first three readingswill be incorrect and should be dis-carded. This is not a big problemunless you plan to change theADS1212’s gain on the fly to imple-ment some form of auto-ranging orswitch the input signal of theADS1212 using an external mux tomonitor multiple channels. Note thatthis also applies to the internal muxin the ADS1213 four-channel device.

In either of these situations, thefirst three readings would have to bediscarded after either the gain or inputchannel was changed. In a continuouslysampled system such as a GC, this pre-cludes the use of the gain control forauto-ranging and requires the use of twoADS1212 devices for a dual-channeldata acquisition system rather than asingle ADS1213 four-channel device.

CIRCUIT DETAILSFigure 5 is a complete diagram of

the dual-channel data acquisition sys-tem. I covered the operation of theADS1212, so now it’s time to concen-trate on the rest of the support circuit-ry. Analog input signals from eachchannel are fed into individual Burr-

Brown INA118 instru-mentation amplifiers. Ichoose this device forboth its low cost andinput protection feature.The HP5890 GC has a 1-V ground-referenced out-put, so I connected itssignal to the positiveinput of the INA118 andground the other input.The gain of the INA118is defined as:

This results in a gain of 1.227 witha standard 220-kΩ resistor as the gain-setting resistor. This amplifies the 1-Vinput to 1.227 V at the ADS1212’sinput, which is close to its 1.25-V full-scale input (using a gain of four). Thiscircuit can be easily tailored to handleother voltage ranges by changing thegain-setting resistor. Differential sig-nals are handled by using both of theINA118’s inputs.

The ADS1212 A/D converter circuitsare identical except that each one hasits own *CS line from the microcon-troller. I send the initialization com-mands to both devices simultaneouslyby invoking both *CS1 and *CS2simultaneously. However, for the pur-pose of reading data from each device,each *CS line is asserted separately.

The microcontroller is an AtmelAT90S2313-4PC. This device has in-circuit programming of its flash mem-ory making it easy to use. Althoughthe ’2313 includes a hardware SPIport, it is dedicated to the in-circuitprogramming function. This isn’t aproblem because the ACD interface ishandled in software, as I’ll explainlater. Unlike the Microchip PIC16F84that I used with my first ADS1212project, the ’2313 includes a hardwareUART that simplifies the firmwaredesign considerably.

The interface to the PC is via a seri-al data link at 9600 bps. Level shiftingof the microcontroller’s TTL-level sig-nals to RS-232 levels is done using asimple circuit consisting of Q1 andQ2. Because the INA118 instrumenta-tion amplifiers need a ±12-V power

Photo 2—This is a screen dump of the program after it has collected data (only channel one was collected in this case).

Page 29: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 27

source, –12 V is available for use in theRS-232 transmit circuit, eliminatingthe need for a MAX232 or equivalent.

The power supply is a simple bridgerectifier feeding a three-terminal 5-Vregulator. I chose a small Burr-BrownDC/DC converter chip to provide the±12 V for the instrumentation amplifi-er. It provides ripple-free output volt-ages with only small tantalum filtercapacitors because of its high switch-ing rate. Photo 1 shows the circuit.

AVR FIRMWAREAs in all of my AVR-based projects

over the past year, I used the MCSElectronics Bascom-AVR compiler forthis design. This full-featured BASICcompiler produces fast, reasonablycompact code. A free demo version isavailable to download from MCS. Theprogram is fully functional, apart fromthe limitation that it can only compileprograms up to 2 KB. The Bascom-AVRcompiler also includes an integratedAVR device programmer software. Forbackground information, read one ofmy previous article, “My fAVRiteFamily of Micros,” (Circuit Cellar 133).

The hardware SPI port of the ’2313is busy, so a software implementationis needed to communicate with theADS1212 ADCs. The Bascom-AVRcompiler has software SPI routines,but I chose not to use them. Duringinitialization of the ADS1212 devices,I played a little trick and selected bothdevices at once before sending themthe requisite commands. The intrinsicSPI routines in Bascom require you tospecify the port pin used to enable thedesired SPI device, which doesn’t workwell for my trick.

Bascom also includes a shiftoutcommand, which performs a similarfunction but does not include the chipenable function. I used that commandand performed the chip enable func-tion for both ADS1212 devices usingbit set and reset commands.

The decimation ratio must be spec-ified by the host program prior to theinitialization routine for the ADS1212.This allows the host computer toselect many different data collectionrates. The format of this command is:Dxxxx <CR>, where xxxx is thedesired decimation ratio.

After the ADS1212 units have beeninitialized, the firmware goes into aloop waiting for the Remote Startswitch to close. Thereafter, both ’1212devices will be read after conversion iscomplete at the chosen data rate.

The Bascom-AVR compiler hasintrinsic functions for sending num-bers out the serial port as ASCIIstrings, so I decided to transmit thetwo-channel data as two ASCIIstrings, separated by a space characterand terminated with a <CR> <LF>. Imust mention that even though theresolution of the ADS1212 is rated at20 bits, the data output that Iobserved using my signal source wasstable only to about 16 bits. I there-fore chose to transmit only the16 MSBs to the host. This allowed meto treat the data as integer rather thanfloating point data, which sped up theoperation of the host application soft-ware. Given a more stable signal, itwould be easy to modify the firmwareto send the full 3 bytes of data thatthe ADS1212 provides.

If you chose a much higher datarate, it might be necessary to eitherswitch to 19,200 bps or transmit thedata in binary (which requires fewercharacters per data point). The devicewill continue to collect and transmitdata until it receives a single “S”character from the host. At that point,it will stop and any further data col-lection will require the decimationratio command be resent.

FIRMWARE AND SOFTWAREI wrote the host application soft-

ware using Visual Basic ProfessionalV.3 rather than using my new VisualBasic V.6 compiler. I did this to allowthe application to run on eitherWindows 3.1 or the newer 32-bitWindows versions such as Win9x andWinME. Additionally, the code gener-ated by the Visual Basic V.3 compileris compact. The application is lessthan 50 KB, and needs only a 320-KBrun time DLL and a few small VBXsupport files. The same applicationcompiled with Visual Basic V.6 fillstwo 1.44-MB floppies!

This application program providesthe usual real-time display of up totwo channels of data being collected

SOURCEADS1212 Delta-sigma converterBurr-Brown (now TexasInstruments, Inc.)(800) 336-5236www.ti.com

SOFTWARETo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2002/140/.

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

REFERENCE[1] Texas Instruments Inc., “22-Bit

Analog-to-Digital Converter,” SBAS064A, November 2000.

RESOURCEBascom-AVR compiler demoMCS Electronics31 75 6144189Fax: 31 75 6144189www.mcselec.com

as well as post-acquisition displayincluding zooming, peak integration,printer plots, and file storage. Photo 2shows the program in action.

TRY ITHaving done three different designs

using the ADS1212, I can now relaxwhen I use them. I don’t mind admit-ting I was exasperated when I first triedusing them with a Basicx microcon-troller. I just could not make its built-in SPI routines talk to the ADS1212properly. The problem disappearedwhen I switched to a PIC16F84 chip(using assembly code) and later to theAVR chip and Bascom compiler. Thisprobably explains why I devoted somuch of this article to the program-ming details of the ADS1212.

If your hand is steady enough tosolder some eight- and 18-pin SOICsto a PCB, then there’s no excuse notto give this device a try the next timeyou need a high resolution ADC. I

Page 30: Circuit Cellar2002 03

28 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

magine remote-ly monitoring up

to 12 channels ofinformation and access-

ing it anywhere in the world via theInternet with a web link multichan-nel monitoring system. My multi-channel web link system consists of aBASIC Stamp II microprocessor and amini web server module. The weblink system allows great flexibility increating a remote monitoring system.The system can monitor normallyopen and normally closed alarmswitches for perimeter detection andmonitor a wide range of sensors suchas light, humidity, temperature, pH,and magnetic sensors. After it’s acti-vated, the alarm system will notifyyou via the Internet.

The web link monitoring systemprovides a dedicated web page incor-porated in the on-board mini webserver module (WSM), which can beused to remotely display 12 alarmconditions on any web browser. Themultichannel web link monitoringsystem can also send an e-mail messageor FTP a file to a remote computer,informing you of an alarm condition.

The system is centered on theBASIC Stamp II (see Figure 1) and amini web server (see Figure 2). Its

heart is comprised of a low-costBASIC Stamp II Interpreter chip, aPIC16C57, and a 28-pin DIP-styleStamp II, rather than the stockBASIC Stamp II module.

The PIC BASIC interpreter chiprequires a few external support chipsand occupies more real estate but thecost is significantly less. The BASICStamp II interpreter chip requires afew external support components, a24LC6B memory chip, a MAX232serial interface chip, and a ceramicresonator. The MAX232 requires four1-µf capacitors, a diode, and a resis-tor and provides a conventional serialI/O which is used to program theweb link microprocessor.

I chose the Stamp II instead of a PICbecause this is a work in progress, andthe former allows features to be addedat any time in the future. The weblink system provides 12 normallyopen/closed inputs that can be usedfor sensor detection. The system hasfour output pins, a status indicator,and an output for an alarm siren,annunciator, strobe lamps, or such.Also included are two pins for serialcommunication to a PC that isalways on, which can act as a server ifyou elect to send e-mail notificationto a remote computer, cell phone, oralpha-numeric pager.

Figure 2 illustrates the WSM, whichplugs into the main web link moni-toring board. This mini web-servermodule is a real web server in a 1″square package. The module consistsof two main chips, a microprocessorfor control, an Ethernet protocolserver, and a crystal. Additional sup-port components are two exclusiveOR gates, a pulse transformer/filterwith an integrated RJ-45 jack, a fewcapacitors and resistors, and a linkindicator LED. This powerful littleserver can handle a custom 48-KB webpage. The web link monitor web pageconsists of a 12-channel status chartof alarm stations with green and redindicator lights. Anyone going to theweb page address of the web linkmini-server module would be able toview the status of the multichannelalarm from anywhere in the world.

The diagram in Figure 3 depicts aclever method of providing both nor-

A Web Link MonitoringSystem

iBased on a BasicStamp II processorand a mini web servermodule, Tom’s weblink system provides aflexible monitoringsystem that can beconfigured for a vari-ety of applicationsand sensors. Thealarm capabilitiesmake it useful in near-ly any situation.

Tom Petruzzelli

FEATUREARTICLE

Page 31: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 29

adjustment point using a 50-kΩ poten-tiometer control. The threshold con-trol can be biased with either 5 or 9 V.A 9-V reference source on the mainboard provides a wider range of input.

A sensor device is connected to thepositive input of the comparator atpin 3. Almost any resistive type sen-sor could be used in this circuit. Atemperature sensor, resistive light sen-sor, humidity sensor, pH sensor, orHall effect switch could be used atS1. You could also use the input atIN1 to monitor a 5-V signal source

and control the thresholdfor voltage change detectionat this input.

The output of the thresh-old detection circuit is a 5-Voutput, which could be con-nected to any number ofBASIC Stamp II inputs. Forexample, you could monitorfour temperature sensors,light sensors, and voltagesources all at the same timewith my multichannel weblink system. You could fab-ricate a comparator daugh-terboard and plug it into theheader pins at J2.

The diagram in Figure 5highlights how to connectan output device to the sys-tem. As I mentioned previ-ously, the alarm-monitoring

mally open and normally closed inputsensors or alarm switches. Any num-ber of normally closed or normallyopen switches can be used in thisinput circuit. Two 1N914 diodes, anNPN transistor, and a 10-kΩ resistorare all that are required for the inputdevice. You could elect to build one ofthese input circuits for each of theBASIC Stamp input pins (P0–P11) ifyou desire. The output of this inputconverter circuit provides a 5-V signalto the input of the Stamp II upon analarm signal. A input to the daughter-

board could be designed to plug intothe header pins at J2 at the bottom ofthe main web link PC board.

You may use the comparator circuitand sensor shown in Figure 4 to moni-tor a wide array of input sensor devices.This circuit consists of a dual-LM393comparator chip (a single op-amp isshown). You may construct two thresh-old comparator circuits using this onechip and a few support components.

The negative input of the compara-tor chip at pin 2 is used as the feed-back path as well as the threshold

Figure 1—The main web link monitoring system board includes Basic Stamp II programming cable and PC server connections.

Figure 2—The mini web server module has a jack for the transformer, filter, and Ethernet connections.

Page 32: Circuit Cellar2002 03

30 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

CONSTRUCTIONConstruction of the web link

PC board is straightforward.First, install all of the IC sock-ets. Next, you may install theresistors, carefully observingthe color codes on the resistorsin order to correctly identifyand install the resistors. Then,install the capacitors, makingsure to watch the polaritymarkings on them.

Locate the diodes and theindicator LED. Be careful to

identify the Zener versus signaldiodes and take note of the correctpolarity. After that, install the volt-age regulator, checking the inputversus output pins when installing.Next, install the header pins forthe web server module, inputpins, power source, as well as pro-gramming connector J3 and serverconnection J4. Lastly, you need toinstall the input programmingjumper. JP1 and JP2 tie the Stamp IIinput pins either high or low. Thesoftware provided (you may down-load the code from the CircuitCellar web site) is configured forinputs to be tied low or to groundand go high upon activation.

The system can be configured forthree different modes of operation.The first and most elegant configura-tion consists of the WSM plugged intothe web link controller board. With theWSM installed, your monitoring systemwill present the sensor/alarm condi-tions to a dedicated web page that’shosted in your WSM (see Figure 6).

And, of course, theinput sensor conditionsmay be viewed by any-one with a browsersuch as InternetExplorer or Netscapefrom any locationaround the world. Themini web server mod-ule eliminates the useof a dedicated comput-er and is compact. The“always on” Ethernetconnection plugs intothe multichannel weblink board and you’reready to go!

system provides an output for externalalarm devices. The output at pin 23(P13) from the controller is connectedthrough a 1-kΩ resistor to the base ofthe 2N3904 relay driver transistor.Relay RL1 is a 5-V driver relay thatcan turn on Sonalert or other smallsounders or lamps. You can also userelay one (RL1) to drive a second high-er current relay, which can drive alarge motor siren, strobe lamp, orsimilar product. The smaller 5-V relayat RL1 is used to drive the larger cur-rent 110-V relay RL2. So, as you see,only one relay is needed for low-cur-rent loads, but higher current loadsmust have two relays.

I fabricated the monitoring systemon a 3″ × 5″ double-sided circuit boardthat houses the Stamp II microproces-sor, optional web link server, and theglue (or support components). A 5-Vregulator at U4 powers the Stamp II,mini web server, and associated sup-port components. The 9-V Zener diodeserves as the a reference source for thesensor comparator module if its used.

The second web link configurationassumes you already have a PC that’salways running. Installing the WEB-SERV PC Server software will allowthe monitoring system to send alarmconditions via e-mail to a remotelyspecified computer. For this configura-tion, you would not need the miniweb server module installed on theweb link system board (see Figure 7).This configuration also assumes anthat you have an Ethernet connectionthat is always on.

The third configuration of the moni-toring controller allows the web linkboard to be used as a stand-alonealarm system with a siren for localalarm indication. The web link outputalso could be used to activate a tele-phone dialer to summon a friend,neighbor, relative, or police.

SETUP AND OPERATIONSetup and operation of the network

alarm system is straightforward, aswell. First, you have to decide whichconfiguration you’ll use. Do youwish to view the alarm conditionsvia a web page with a self-containedsystem or do you have a computerrunning that can be used to e-mail orFTP alarm conditions to a remotecomputer? If you choose to use theformer option, you must first havean Ethernet connection that isalways up, such as cable modemservice or DSL.

Figure 5—For low-current as well as high-current devices, this serves asthe web link output relay controller.

Figure 3—The input signal conditioner circuit is for normally openor closed sensor/switch inputs.

Figure 4—The voltage, light, and temperature sensor inputswork on the input threshold/comparator circuit.

Page 34: Circuit Cellar2002 03

32 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

site. In the service port range column,type the port number that will be trans-lated to a web link, for this exampleuse 2001, then type the fixed IPaddress of the web link on the internalnetwork. If you don’t fix the IP addressof the web link it could wander aroundwith DHCP and get lost.

Now, you have attached the outsideport 2001 to the inside IP address ofthe web link. From the outside world,you then surf the web link by typing“http://xxx.xxx.xxx.xxx:2001”, wherexxx.xxx.xxx.xxx is your outside-worldIP address. The Linksys will translatethis port request to inside.Weblink.ip.address:2001.

Because the web link responds to allports, the 2001 request is just like anyother normal HTTP port 80 request.You can do this with up to 10 entries inthe Linksys table. I thought you coulddo more but I guess limits are neces-sary. The only wrinkle that I see is thatthis may not work if you’re using PPOEfor your DSL connection, because thePPOE connection is not always direct.You may be going through some

Recall that J2 is provided in the eventthat you want to build a sensor inputdaughterboard. Next, you need to con-nect your sensors and a 9- to 12-Vpower supply or wall wart.

Connect your programming cablebetween a PC or laptop and yourboard at J3 (see Figure 1). You’ll haveto locate the Stamp II program titledWLINK1.BS2 and load the programinto the Stamp II. Your Ethernet con-nection is now plugged into the weblink board at the RJ-45 jack. When thecontroller is powered up and theEthernet connection is established,your monitor alarm is ready for opera-tion. Note that there is a Reset switchfor both Stamp II and the mini webserver module in case you encounter aproblem while starting up the system.

If you’re using the web link monitorsystem board with the WSM server, youneed to identify its location on the net-work. This can be tricky depending onyour network configuration. If youanticipate using the monitoring systembehind a Linksys four-port router/switch,then you need to visit the Linksys web

The diagram in Figure 6 illustratesthe WSM installed on the main weblink monitoring system board. Plug inthe WSM into the main board. Notethe proper orientation of the WSM,with the serial number in the topright corner facing the Stamp II. Themini web server is loaded with a 12-channel status monitor web page.

You’ll first need to figure out whattypes of sensors or switches you wishto use as input devices. Sensor inputsand power are connected at the bot-tom of the circuit board at J1 and J2.

Web servermodule

LED

LED U1CPU

U2

U3

Sirenout

J3

J4

J2J1

WLA/WMK

always onEthernet

Server port

Serial port stam

pprogram

ming cable

Sensor inputs and power

Figure 6—The web server module is installed in theweb link monitoring system.

Page 35: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 33

SOURCESPIC16C57 MicrocontrollerMicrochip Technology Inc.(480) 786-7200Fax: (480) 899-9210www.microchip.com

BASIC Stamp II Interpreter chipParallax, Inc. (888) 512-1024(916) 624-8333Fax: (916) 624-8003www.parallaxinc.com

SOFTWARETo download the code, parts list,and purchasing information, go toftp. circuitcellar.com/pub/Circuit_Cellar/2002/140/.

routers in your ISP. Try forwardingport 80 in the Linksys to the internal IPaddress of the PC and run WeblinkPC.If someone can surf WeblinkPC fromthe outside world, you should be ableto surf the hardware web links.

If you used your own PC serverinstead of the server module on theweb link monitoring board to send e-mail notification, you’ll need to sup-ply your own computer that’s alwayson to act as your server. This configu-ration also requires an Ethernet con-nection that runs continuously inorder to send notifications to yourremote monitoring computer, cellphone, or pager. You have to make upserial connection cable from the out-put of the web link controller board toyour server PC via header J4.

Figure 7 depicts the web-link-to-PC-server connections. Sensors as well asthe power source are connected on thebottom of the circuit board at J1.Connector J2 is provided for a sensordaughterboard. After your serial portcable is connected between the boardand PC server, you need to power upthe board and load EMDAT1.BS2 intoyour Stamp II controller for e-mail noti-fication of alarm. The program containsa sample e-mail address that you’ll haveto change to your own e-mail address.Next, install the mini server programWEBSERV.EXE on your PC and config-ure it for e-mail files. Your monitoringsystem is now ready to serve you.

LAST DETAILSThree additional programs are

included with the software files. Usethe SitePlayerPC program to create orchange web pages in the WSM. Thesite linker program is used to down-

Tom Petruzzelli is an electrical engi-neer at the Binghamton Universitygeophysical laboratory. He is involvedin Earth monitoring studies includingseismology. Tom has authored threeelectronics books as well as manyelectronics construction articles invarious computer, electronic, andradio magazines. You may reach himat [email protected].

load the binary imageto the WSM. A pro-gram titled SitePlayerSerial Port Tester canbe used to get or setthe WSM’s address.

The web link mon-itoring system boardis offered as a kit.You can purchase theweb link main boardwith or without theoptional on-boardmini web server as

your application dictates. If you want asmall self-contained system that can beused to view alarm conditions remote-ly, you should choose the web linkmain board with the WSM. If, on theother hand, you wish the alarm condi-tions to be e-mailed and you alreadyhave a PC that can act as a server, youshould choose the main web link boardwith the PC server software package tocomplete your system. The web linksystem offers great flexibility in moni-toring remote alarm conditions. I

Web servermodule option

LED

LED U1CPU

U2

U3

Sirenout

J3

J4

J2J1

WLA/WMK

alwayson

always on

Ethernet

Serverserial port

Serial port stampprogramming cable

Sensor inputs and power

Serialport

PCserver

Figure 7—An external PC server is attached to the monitoring system.

Page 36: Circuit Cellar2002 03

34 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

ometimes ithelps to get a fresh

perspective on things.Someone else’s opinion

just may be what you never knew youalways wanted for your project. Ourproject was a surgical laser controller.Heeding this notion of a second opin-ion, we listened to one of our client’sthoughts about the device. The client,a surgeon, pointed out that it wouldbe nice if the laser power display andup-and-down power control buttonswere extended to the laser delivery tip.He wanted to keep an eye on the laserpower during operations. Surgical pro-cedures are typically conducted in lowambient light, so the power displayshould be bright enough to be clearlyvisible. For this, we had to choose amedium-size, seven-segment display.The emphasis was on a compact andfeatherweight LCD, because the laserdelivery arm has a delicate structure.

The doctor’s point was genuine. Heexplained that it was difficult tochange the laser power with the frontpanel controls, which are locatedabout 2 to 4 meters from the patient’sbed. We solved the problem with asingle-chip microcontroller with plen-ty of I/O pins. The laser controllerwas designed around an Intel 8051

microcontroller. When the search forthe microcontroller began, we discov-ered Atmel’s 20-pin AT89C2051. The’2051 has an 8051 core, UART, 15 I/Olines with 20 mA, and direct LEDdriving capability. This was perfect, itwas as if it had been speciallydesigned to solve our problem.

Although we carried out the initialdevelopment without any specific hard-ware tool, eventually we realized wewould need an in-circuit emulator forfuture applications; we were steadfastin our choice of the AT89Cx051 fami-ly. The do-it-yourself approach wasirresistible. In this article, we will dis-cuss how we developed an AT89Cx051emulator and circuits.

With about a decade of experience inembedded system design, the increas-ing popularity of single-chip microcon-trollers was obvious to us. They arewinning the sales war because of theirrich on-chip resources (e.g., code memo-ry, scratch pad memory, timers/coun-ters, UART, watchdog timer, RTC,ADC, DAC, etc.). Single-chip microsoffer good processing capabilities, oper-ate at reasonably high speeds, consumemuch less power than their competi-tors, and are economical. Many space-sensitive applications can be built usingthese microcontrollers without adding asingle external peripheral device.

The most popular single-chip micro-controllers are the Intel MCS-51 family,Atmel AT89C family, Motorola 68HCfamily, SGS Thompson ST6 family, andMicrochip PIC series. Let’s take a closerlook at a couple of these best buys.

The MCS-51 architecture is widelyused; many derivatives are availablefrom various manufacturers. It’s basedon an 8051 core with a variety of on-chip resources. Atmel’s AT89Cx051family comes in a miniature (20-pin)package. This family of chips usesIntel’s industry-standard ’80C51 core.AT89Cx051 microcontrollers have nei-ther external data nor an address bus.They are more suitable for single-chip,compact, lightweight embedded appli-cations, especially because they have anoptimized instruction set for bit-orient-ed Boolean operations and can directlydrive LEDs. In short, AT89Cx051 deviceshave a perfect balance of much neededon-chip resources and small size.

In-Circuit Emulator forthe AT89Cx051 Family

sAfter developing a sur-gical laser controller,Praveen and Prajaktareceived a request tomove the power con-trols from the frontpanel of the unit to thelaser tip. They decidedthat an emulatorwould be a good toolto have to make thenecessary changes,so they built one.

Praveen Deshpande &Prajakta Deshpande

FEATUREARTICLE

Page 37: Circuit Cellar2002 03

ing standard features: 1-, 2-,or 4-KB flash memory, 64 or128 bytes of RAM, 15 I/Olines, and two 16-bit timer/counters. Also included are afive-vector, two-level inter-rupt architecture, full-duplexserial port, precision analogcomparator, on-chip oscilla-tor, and clock circuitry. Ifyou want to take a closerlook at the circuitry, EricKesselring’s recent article,“The Need for Speed—AnAccurate Speedometer,”talks about the details(Circuit Cellar 135).

In addition, the AT89Cx051 isdesigned with static logic for opera-tion down to zero frequency and sup-ports two software-selectable power-saving modes. Idle mode stops theCPU while allowing the RAM,timer/counters, serial port, and inter-rupt system to continue functioning.Power Down mode saves the RAMcontents but freezes the oscillator,thus disabling all other chip functionsuntil the next hardware reset.

Three devices, the AT89C1051,AT89C2051, and AT89C4051, belongto the 89Cx051 family. Their majordifferences are flash program memory,

so the emulator hardware reliesentirely on on-chip program memory.Additionally, it must provide all of theon-chip resources present on themicrocontroller it’s emulating. The in-circuit emulator offers the advantageof using the hardware for softwaredevelopment as well as hardwaredebugging. You need to plug-in theactual processor with the debuggedprogram for final deployment.

ARCHITECTURE OF THE ’x051Salient features of Atmel microcon-

trollers are summarized in Table 1.The AT89Cx051 provides the follow-

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 35

When you develop applications basedon a microcontroller, you need a num-ber of tools. The programs have to beput together and debugged with the aidof an appropriate development system.In recent years, the cost of the assem-bler and compiler has dropped consider-ably. Moreover, many free assemblersand C compilers that have about 2 KBof limited code generation capability areavailable on the Internet. Free resourcescoupled with decreasing componentcosts enable almost anyone to developmicrocontroller-based applications.

An in-circuit emulator is one of thetools that will assist you when devel-oping the hardware and soft-ware. Part of the emulatorhardware is a multi-wirecable, which connects thehost to the system beingdeveloped. A plug at the endof this cable is inserted intothe prototype system inplace of its microprocessor.Through this connection,the software of the emulatorallows you to downloadyour application object codeprogram into the RAM ofthe system being tested andrun it. The emulator allowsyou to use either itsonboard internal memory(known as emulation mem-ory) or the memory on theprototype (target) board fordebugging your programs.

Single-chip microcon-trollers don’t have the exter-nal program (code) memory,

Figure 1—The V.1.0 emulator is ideal for software development with an AT89Cx051 device, however, the emulator lacks some ofthe hardware features of the AT89Cx051 family.

AT89Cx051 family AT89 series

89C1051 89C2051 89C4051 89C51 89C52 89C55 89S8252 89S53Flash ROM (kilobytes) 1 2 4 4 8 20 8 12RAM (bytes) 64 128 128 128 256 256 256 256Interrupt sources 3 6 6 6 8 8 9 916-bit Timer/counter 1 2 2 2 3 3 2 3Watchdog timer – – – – – – Yes YesPower Saving mode Yes Yes Yes Yes Yes Yes Yes YesData pointers 1 1 1 1 1 1 2 2Serial UART (full duplex) – Yes Yes Yes Yes Yes Yes YesSPI Interface – – – – – – Yes YesI/O Port pins 15 15 15 32 32 32 32 32Analog comparator Yes Yes Yes – – – – YesPackage pins 20 20 20 40 40 40 40 40

Table 1—AT89Cx051 family microcontrollers have enough on-chip features to make them suitable for compact, lightweight, andbattery-operated applications. Compare the 8051-compatible micros and choose what’s best for your project. All of thesedevices have flash memory and guarantee 1000 programming cycles. The ’x051s feature 20-mA ports for directly driving LEDs.

Page 38: Circuit Cellar2002 03

36 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

Any 8051-compatible assembler or Ccompiler will generate these instruc-tions, unless it specifically supportsAT89Cx051 family devices. You, asthe software programmer, are respon-sible for knowing the physical limi-tations of your device and adjustingthe instructions accordingly in thefinal object code.

The flash memory combines theadvantages of an EPROM with thoseof static memory. After the data isstored in flash memory, it remainsthere for many years, even after thesupply voltage is removed. It can beerased as a single block, which takesup about 10 ms, and can be repro-grammed at least 1000 times.Programming Atmel flash memoryrequires special hardware that pro-vides 12-V (some devices need 5-V)programming pulses with specificrequired data at various microcon-troller pins. It may not always be pos-sible to include such hardware in thetarget application circuit.

GETTING STARTEDAny MCS-51 family microcontroller

(e.g., the AT87C51/52 or AT89C51/52)can be used to emulate an AT89Cx051,because they have the same internalarchitecture and matching on-chipresources. We used an AT89C51 as anemulation controller for this project.The external RAM (equal to the sizeof the AT89Cx051’s flash memory)acts as an emulation memory wherethe object code is downloaded. All ofthe corresponding 18 pins of theAT89Cx051 device are carried to the

internal data memory, anda serial (UART) port.AT89Cx051 devices havetwo hardware propertiesthat deserve special atten-tion. These properties, ifused cleverly, can help youto simplify the circuitdesign significantly.

For directly driving theLEDs, ports P1 and P3 arecurrent-boosted and capableof sinking 20 mA. Thisenables LEDs, optocouplers,small relays, and similardevices to be controlleddirectly from the chip.

Port pins P1.0 and P1.1 provide analternate functionality. These pins maybe used as analog inputs (P1.0 is non-inverting and P1.1 is inverting) of anon-chip comparator. The analog inputvoltage applied to the chip may liebetween 0 V and VCC. The comparatorcompares the voltages at these inputs.If the difference is positive, the com-parator output is switched high. Whenthe difference is negative, and the out-put is pulled low. The comparator out-put is internally connected to the P3.6port line. You can detect when theanalog voltage exceeds a thresholdlevel or even implement a simple A/Dconverter with an additional RC net-work and some software. [1]

The AT89Cx051 microcontrollerfamily is completely op-code-compati-ble with the Intel MCS-51 architec-ture and can be programmed using theMCS-51 instruction set. [2] However,there are a few restrictions you shouldkeep in mind when using certaininstructions to program these devices.All of the instructions related to jump-ing or branching should be restrictedsuch that the destination addressesfall within the physical program mem-ory space of the device. Violating thephysical space limits may causeunknown program behavior.

In the AT89Cx051 family, the stackdepth is limited to the amount of on-chip RAM (data memory). Externaldata memory access is not supportedin these devices, nor is the externalprogram memory or execution.Therefore, no MOVX instructionsshould be included in the program.

multi-wire cable plug. Anexternal 11.0592-MHz crys-tal drives the AT89C51 on-chip oscillator circuit.

The reset logic brings theemulator to a known stateafter power-up and initiatesnew object code download-ing. The AT89C51 has anexternal 16-bit address and8-bit data bus where you canadd 1-, 2-, or 4-KB (emula-tion) RAM memory. It has4-KB on-chip flash memoryfor storing the emulatorfirmware to download theapplication object code from

a PC. Figure 1 shows the circuit dia-gram for the first version of the emu-lator. The emulator uses an RS-232serial interface (see Figure 2) for com-munication with a PC. The MAX232(IC1) has two transceivers; one is usedfor TXD and RXD signals and theother pair is used for RTS and CTSsignals. The circuit illustrated inFigure 2 shows a nine-pin, D-type con-nector for a five-wire connection to aPC. A shorting jumper (JP1) bypassesthe RTS, CTS handshaking to make athree-wire connection.

For true emulation, all of the targetmicrocontroller resources must bereserved for use by the target hard-ware. The only hardware UART avail-able on-chip is left out for targetdevice emulation. Two port pins, P2.6for TXD and P2.5 for RXD, are used toimplement a UART in software, usingthe bit-bang technique (see Listing 1).

The emulator uses a fixed data rateof 19,200 bps for communication withthe PC. For this application, onlyhalf-duplex serial communication isrequired. The circuit uses a RAM(IC1, 62256) as the emulation codememory. The emulator firmwareresides in the on-chip flash memory ofthe emulation microcontroller (IC3).The circuit uses topmost overlappedcode in the data memory area to emu-late the AT89Cx051 on-chip flashmemory (see Figure 3). Although thelower address lines (A0 through A12)address the RAM (IC1), physicaladdress F000H is chosen as a baseaddress of the flash memory of theAT89Cx051 device.

Figure 2—The RS-232 serial interface is implemented using a MAX232. This inter-face IC provides two transceivers that are used to make a three-wire (null modem)interface or a five-wire interface with RTS and CTS handshaking signals.

Page 39: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 37

interrupts and redirects them to thecorresponding vector locations for thetarget application code. The applica-tion code must write the ISR. Thelower address bytes (A0 through A7)

You must locate your object code atthe base address, for example, usingan assembly language statement suchas ORG F000H. The emulator firmware(resident at 0000H) receives all of the

Listing 1—Bit bang the serial I/O functions for the MCS-51-compatible microcontrollers. The data ratedepends on the crystal.

//The delay count for required baud rate is computed using one bit time (BITTIM) = (((crystal/baud)/12) -5) / 2rounded to nearest integer value

bit TxPin @ 0xB1;bit RxPin @ 0xB0;asm(" BITTIM EQU 21"); //(((11059200/19200)/12) -5) / 2

//transmit character in R5 via TxPin linevoid SendChrw (unsigned char ch)asm(" push 00 ");asm(" push 01 ");asm(" push ACC");asm(" push PSW");asm(" mov a,r5");asm(" clr _TxPin "); //drop line for start bitasm(" mov R0,#BITTIM"); //wait for full bit-timeasm(" djnz r0,$ "); //for START bitasm(" mov r1,#8 "); //send 8 bit dataasm("putc1: rrc a "); //move next bit into carryasm(" mov _TxPin,C "); //write next bitasm(" mov r0,#BITTIM"); //wait full bit-timeasm(" djnz r0,$ "); //for DATA bitasm(" djnz r1,putc1 "); //write 8 bitsasm(" setb _TxPin "); //set line highasm(" rrc a "); //restore ACC contentsasm(" mov r0,#BITTIM"); //wait full bit-timeasm(" djnz r0,$ "); //for STOP bitasm(" pop PSW");asm(" pop ACC");asm(" pop 01 ");asm(" pop 00 ");

//receive a character from the RxPin line and return in R3unsigned char RecvChrw (void)asm(" PUSH 00");asm(" PUSH 01");asm(" PUSH ACC");asm(" PUSH PSW");asm("getc0: ");asm(" setb _RxPin "); //make the pin as inputasm(" jb _RxPin,$ "); //wait for start bitasm(" mov r0,#BITTIM/2"); //wait 1/2 bit-timeasm(" djnz r0,$ "); //to sample in middleasm(" jb _RxPin,getc0"); //insure validasm(" mov r1,#8 "); //read 8 bitsasm("getc1:mov r0,#BITTIM "); //wait full bit-timeasm(" djnz r0,$ "); //for DATA bitasm(" mov C,_RxPin "); //read bitasm(" rrc a "); //shift it into ACCasm(" djnz R1,getc1 "); //read all 8 bitsasm(" mov r3,a"); //return result in r3asm(" pop PSW");asm(" pop ACC");asm(" pop 01");asm(" pop 00");

Page 40: Circuit Cellar2002 03

38 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

are latched by IC2(74LS373). The emulationmemory is addressed as adata memory (write opera-tion to U1 using the *WRsignal) during an objectcode transfer from the PC.The target processor con-tains P3.7 (the *RD signalas the alternate functionin the AT89C51), hence,this pin cannot be used toread data from the emula-tion memory. Because the emulationmemory should act as a program mem-ory during application code execution,it must use the program strobe enable(*PSEN) signal to fetch code bytes.

Crystal Y1, C1, and C2 completethe on-chip oscillator circuit. The11.0592-MHz crystal provides manystandard data rates for the on-chipserial ports. R1, C3, and switch SW1comprise the reset circuit.

Because the AT89C51 hardware seri-al port is left out for target emulation,the microcontroller is busy receivingcode bytes from the PC under controlof the software. So, the microcontrollerhas little time to process received datafurther. On-the-fly conversion of Intelhex (ASCII) code to binary isn’t possiblewith a three-wire RS-232 serial inter-face. Most of the assemblers or com-pilers generate hex output files with aPC. A small DOS utility was devel-oped to convert this Intel hex objectfile to binary and then transfer the bina-ry file to the emulator (see Photo 1).

If you compare the on-chip resourcesfor AT89Cx051s and the AT89C51, youcan see that the latter doesn’t match

the former exactly, as the on-chip ana-log comparator is not available on theAT89C51 (see Table 1). Furthermore,its port lines don’t have high-current(20 mA) driving capability like theAT89Cx051. Therefore, this emulatorcircuit (V.1.0) isn’t suitable for develop-ing applications that make use of thesespecial features of the AT89Cx051.

One of our data acquisition systemsneeded to interface a sigma-delta seri-al ADC (IC AD7713 from AnalogDevices) with the AT89C2051. TheADC had an AT89C2051-compatibleserial interface for direct connectionto the on-chip UART in mode 0. TheUART uses a clock with a fixed datarate, determined by the oscillator fre-quency divided by 12, in mode 0. Forthe 11.0592-MHz emulator, it com-putes to 0.9216 MHz. The maximumdata rate of the clock input was400 kHz, so we were forced to operatethe AT89C2051 (and the emulator cir-cuit during development) at a 4.8-MHzor slower clock rate.

The point is that there could be sit-uations when you’re forced to use afixed (application-dependent) oscillator

frequency that may differfrom the oscillator frequencyof the emulator. If you care-fully look at the circuit,you’ll notice that it runs at afixed clock frequency (decid-ed by the crystal oscillatorcircuit) preset on the emula-tor board. If the target cir-cuit’s oscillator frequency isdifferent from the emula-tor’s, a program that uses asoftware delay loop may notexecute as desired. In such asituation, the applicationprogram may execute satis-

Data memory

Overlapped withemulation

program (code) memory

Code memory

Reset location

Interrupt vectortable

Object code loader

Target code resetlocation

Relocated interruptvector table

Target object code

0000H

0FFFH

F000H

FFFFH

Emulatorfirmware

(4 KB maximum)

Emulationmemory

(1, 2, or 4 KB)

Figure 3—Here you see a memory map of the emulator.

Photo 1—Look at the utility LOADX051.EXE in action. You canget help by using an /? command line argument.

Page 42: Circuit Cellar2002 03

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 43: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 41

Listing 2—When you’re loading the object code with this firmware, it’s easiest to use C language.

#include <8051.h>

#define START_ADDR 0xF000 //start address for user program

//This data structure simplifies high and low byte separationfrom a 16-bit (unsigned int) value and vice versa.

struct _intbytes unsigned char hb; unsigned char lb;

;union

unsigned int i;struct _intbytes b;

uIntBytes;

unsigned BaseAddr; //user program is located here

void SendChrw (unsigned char ch); //send one char to serial portunsigned char RecvChrw (void); //read one char from serial portvoid SendS (char *s); //send NULL terminated string to serial portmain()unsigned char far *p; //pointer to the base address for writing dataunsigned counter, count;unsigned checksum =0;unsigned char code *cp; //reading (verify operation) object code

BaseAddr = START_ADDR;SendS ("READY");

//get base address (High & Low) bytesuIntBytes.b.hb = RecvChrw(); //high byteuIntBytes.b.lb = RecvChrw(); //low byteBaseAddr = uIntBytes.i;p = (unsigned char far *)BaseAddr;

//get (16-bit) code size (High, Low) valueuIntBytes.b.hb = RecvChrw(); //high byteuIntBytes.b.lb = RecvChrw(); //low bytecount = counter = uIntBytes.i;

while (counter) *p++ = RecvChrw(); //load data to memorycounter--;

//compute 16-bit checksum valuecp = (unsigned char code *)BaseAddr;counter = count;while (counter)

checksum += *cp++;counter--;

uIntBytes.i = checksum;//transmit the checksum bytes (High, Low) to PCSendChrw (uIntBytes.b.hb); //high byteSendChrw (uIntBytes.b.lb); //low byte

//wait for user to press 'G' key (GO) commandwhile ( RecvChrw() != 'G'); asm ("clr a ");asm ("mov dph,_BaseAddr+0"); //load base addressasm ("mov dpl,_BaseAddr+1"); //in dptr registerasm ("jmp @a+dptr "); //to execute the object codewhile(1); //be in a infinite loop here

Page 44: Circuit Cellar2002 03

Working on yournext masterpiece?

It’s time for new tools.

POWERFUL PCB LAYOUT

AUTOROUTING & AUTOPLACEMENT

NETWORK & COMMUNICATIONS SIMULATION

Powerful & easy-to-use PCB layout & editingReroute while move (full rubberbanding)

3D board visualizationReal-time design rule check

Component push & shove with springbackExtensive copper placement capabilities

Benchmark test leader with superior routing resultsCombination of grid-based/gridless routing available

Highly flexible router provides complete controlOptimal part placement improves routing performance

Supports manual wire pre-placementPin and gate swap

Powerful, yet easy-to-use fast, accurate simulation toolModel & simulate end-to-end communications systems

Analog, digital & mixed system design capabilityIndustry-leading block libraries — channels,

encoders/decoders, modulators/demodulatorsView simulation results in various methods

— time domain, frequency domain, xy plots,log scale, eye diagrams and power spectra

from $399

from $399

from $399

from $399

SCHEMATIC CAPTURE, SIMULATION & PROGRAMMABLE LOGIC

Advanced modeless schematic captureLibrary of 16,000 parts supplied, with 12 million online

Analog, digital and mixed-mode simulationPatented co-simulation of SPICE, VHDL and Verilog

Suite of “virtual instruments” including oscilloscope,wattmeter, spectrum analyzer & network analyzer

Design collaberation across the Internet

sales: 800.263.5552 • http://www.electronicsworkbench.com© 2001 Interactive Image Technologies. All rights reserved. Electronics Workbench, Multisim and Ultiboard are registered trademarks of Interactive Image Technologies Ltd. All other trademarks are registered trademarks of their respective owners.

Electronics Workbench products areused by more designers than anyother software of their kind. Theywill help you reduce developmenttimes and produce higher qualitycircuits — We guarantee it, or yourmoney back!

We offer a portfolio of products to meet all your design needs:Schematic Capture, ComponentDatabase, SPICE/VHDL/VerilogHDL/RF Simulation, PCB Layout,Autoplacement, Autorouting andnow Network & CommunicationsSimulation.

Ease-of-use continues to be one ofour biggest strengths, letting youproduce designs in the time it takesto install and configure most otherprograms.

Our unique combination of power and unrivaled ease-of-use allows us to offer this guarantee. Powermeans you get capabilities simplynot available elsewhere, such as patented co-simulation ofSPICE/VHDL/Verilog/RF all together.

That’s why we are the EDA supplier of choice to over 150,000 users worldwide.

The World’s Most PopularElectronic Design Tools

Page 45: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 43

factorily with the emulator board butit may refuse to work when run withthe target microcontroller in place.The bottom line is that you have totake proper care when writing soft-ware delay loops and modify the codesuitably before transferring it to thetarget microcontroller.

SOME MORE FEATURESThe V.1.0 emulator circuit may offer

serious limitations for time-criticaland low-power, battery-operated (withwhich you may be forced to operate ata much slower speed to reduce powerconsumption) application development.One temporary solution is to replacethe emulator board crystal with therequired target crystal. However, thismay create another problem, becauseit may become difficult for the emula-tor to achieve a standard data rate forcommunication with the PC. Replacingthe emulator board crystal with thetarget also requires a change in theemulator’s firmware. So, changing theemulator board crystal is not an idealsolution. Instead, you should feedsome logic to the target clock fre-

quency to give to the emulationmicrocontroller just before it beginsexecuting the object code from theemulation (program) memory.

We decided to add an AT89C2051microcontroller to do this gracefully.The Figure 4 shows a circuit diagramfor the modified emulator circuit(V.2.0) with the AT89C2051 (IC7) con-trolling the overall operation of thecircuit. The AT89C51 (IC6) doesn’thave a clock out signal, so we don’tuse the onboard oscillator. We builtan 11.0592-MHz crystal oscillatoraround IC3E, IC3D, C5, R3, and R4.IC7 uses this clock (CLK) signal.

IC6 uses the same 11.0592-MHzCLK signal while downloading objectcode. IC7 receives the object codefrom the PC and transfers it to IC6the AT89C51, which stores it in theemulation memory using bit-bangedtwo-wire serial I/O (see Listing 1).Port pin P3.6 (IC6) has an alternatefunction (external data memorywrite) in the AT89C51.

The on-chip comparator output inAT89Cx051 devices is internally con-nected to P3.6. Because the AT89C51

doesn’t have an on-chip comparator, anexternal comparator (IC8) is added toemulate it. You can use any comparatorIC here. The output of this comparatoris connected to the P3.6 port pin ofIC6 via a tri-state buffer (IC9A). It is dis-abled using the ENCOMP signal whilethe object code is being downloaded.

Port pin P36 of IC6 is connected toone of the inputs of an OR logic gate(IC5C), which drives the *WR signalof the emulation memory. Anotherinput of this OR gate (IC5C) is driv-en by the *ENWR signal from IC7.The *ENWR signal is used to write-protect the emulation memory dur-ing object code execution.

The emulator pod has its own oscil-lator circuit, as you can see in Figure 5.IC1A, IC1B, R1, R2, and the targetcrystal generate the ECLK clock sig-nal. The shorting jumpers (JP1through JP5) enable selection of anemulator pod oscillator or targetboard oscillator if either is necessary.The 2 × 10 header (CN1) connects theemulator pod to the main board (CN1in Figure 4) using a 20-pin FRC cable.The IC2 is the socket plug.

Figure 4—The circuit of the V.2.0 emulator enables target (crystal) clock execution and has an analog comparator.

Page 46: Circuit Cellar2002 03

44 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

The AND/OR logic gates(IC5A, IC4A, and IC4B inFigure 4), IC3B, and controlsignal CLKSEL (IC7) enableyou to select an internal(on-board) or external (tar-get board) clock signalunder control of the (IC7)software. Other AND/ORlogic gates (IC5B, IC4C,and IC4D), IC3C, and con-trol signal TXDSEL (IC7)enable you to connect thetarget serial port output (ifused as a serial port) to thePC. R1 and C3 form areset circuit for IC7. IC7can hold IC6 in a resetcondition with transistorsT1 and T2 and resistorsR5 and R6 mainly duringthe oscillator switchingand before object code execution.

WHAT’S NEXT?We were not happy with the V.2.0

emulator because it was unable toemulate one of the most importantfeatures of AT89Cx051 family: directLED driving capability! Moreover, itisn’t possible to implement this fea-ture simply by adding external bidirec-tional buffers, because AT89Cx051devices don’t provide an external I/Oport read/write signal to select thebuffer direction automatically.

Finally, we realized that we couldimplement a full-featured AT89Cx051emulator using the AT89Cx051 itself,because the emulation processor pro-grams its on-chip flash memory withthe application object code. Thisscheme enables you to have at least1000 program development iterationswithout compromising any specialAT89Cx051 feature (see Figure 6).Although we couldn’t get enough time(or drive!) to work out the idea (tryinga V.3.0 circuit and so on), we didn’tsee any reason why it wouldn’t work.

The circuit initially connects theemulation processor to the flash mem-ory programming circuit and programsit with the object code. The pro-grammed device is then switched overto the target board socket for codeexecution. The flash memory pro-gramming circuit will apply logic-

level signals on a few AT89Cx051 pinsduring flash memory write and eraseoperations. Also, a 12-V signal isapplied to the RST pin.

The RST pin generally will be fixedhigh or low when the target board iscarrying out its normal mission. Thetarget board may use available I/Opins as needed by your project, eitheras an output driving some other cir-cuit or as an input driven by an appli-cation-specific circuit. So, the emula-tor of the AT89Cx051 device must bephysically disconnected from the tar-get circuit to avoid interference withoutput signals coming from the flashmemory programming circuit andexposure to excessive overdrive,which may damage components onthe target board. [3]

IC1 on the AT89C51 acts as a maincontroller responsible for reception ofthe object code, generating the neces-sary flash memory programmingsequence and 12-V program pulses. It

physically connects the emu-lation processor (IC6) to thetarget board, isolating theflash memory programmingcircuit using IC2 and IC5.The schematic in Figure 6shows the reed relay switch-es (K1 through K4) to con-nect the emulation processorto the target circuit duringexecution of the program.Although only one relay (K1)is shown to connect twosignals (SP31 and SP32), anexactly similar relay circuitis required for the remainingsignals from the SP3 [1…7]and SP1 [0…7] signal buses.Relay K5 optionally connectssignals TP30 (RXD) and TP31(TXD) to the PC while theprogram is running.

Table 2 lists the states of variouspins for the program and verify opera-tions. A program pulse generation cir-cuit is an adjustable voltage sourcebuilt around transistors T1, T2, T3,and some discrete components. WhenT3 is driven, the base of T1 is at 0 Vand the programming voltage isswitched off. When only T2 is driven,Zener diode D3 stabilizes the base ofT1 at 5.6 V so that a programmingvoltage of 5 V is obtained. When T2and T3 both are switched off, diodesD1 and D2 provide a reference voltageof 12.7 V so that you get a secondprogramming voltage of 12 V. ResistorR1 limits the current to the con-troller’s program pin. LED D5 glowswhen a program voltage of 12 V isavailable at the output.

Port P1 of IC1 is used to write or readdata during flash memory programmingor to verify operation. You need notworry about the exact program timing,because the actual programming oper-

Figure 5—The emulator pod circuit has an oscillator circuit. The pod enables you toselect the target oscillator or the emulator’s onboard oscillator for code execution.

Mode RST/VPP P3.2/*PROG P3.3 P3.4 P3.5 P3.7

Write Code Data 12 V – L H H HRead Code Data H H L L H HWrite Lock for: Bit 1 12 V – H H H H

Bit 2 12 V – H H L LChip Erase 12 V – H L L LRead Signature Byte H H L L L L

Table 2—You’ll need to know the states of various pins to program and verify operations when you’re programmingflash memory. The emulator V.3.0 firmware uses these modes and the object code to program.

Page 47: Circuit Cellar2002 03

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

www.saelig.com • [email protected]

Saelig

! "#$%&&' !'" $( $")"!& &"' "& "' *+ "

We are noted for ourgreat after salessupport. , &1-888-7SAELIG -' -! " ' ' ' " $

• Over 50 different DIN-modules for:analog i/p & o/p, thermocouple i/p,digital i/p, relays, on 2000m network!

• Plug directly into PC— self powered!

• Drive any RS422 or RS485 devices.

• Send control and data 100s of feet!

K422/K485, 25pin > 9pin . . . $69K422-99/K485-99,

9pin > 9pin . . . . . . . . . . . $69Isolate RS232/422/485 signals

Kxxx-ISOL 25pin self-powered . . . . . . . . . $139

Make PCstalk I2Ceasily!

ISA PCI p-port

RS232 to RS422 &RS485 converters

• Store analog/digital data on PC FlashATA cards

• > 100 readymadesoftware functionmodules—finish 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!

osziFOX$129

Self-contained in2" x 3" plastic box,2-year battery-powered analog anddigital dataloggersfor storing events,

voltages, currents orpressures for days to weeks.

Download detailed time and datavia RS232 port and review your results with graphic software or PC spreadsheet.

Turn yourPC into a

scope!

HandheldPenScope

2-Year Dataloggers

PCMCIA Datalogger TDS2020D

lowpower PCcard logging

Remote control & dataacquisition without power!

PC InstrumentsADC-10 8-bit $79 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!

GP S

Logg ing

see what’s new at www.saelig.com!

Industry-standard card for PC’s . . . . . . . . . . . . . $299• Master, Slave or Bus monitor

• Control or program I2C devices

• Low volt ICA93LV for 3V ic’s . . $399• PARALLEL PORT VERSION

NEW - PCI VERSION!

BIT®

CANboards

USB icsRS232 <> USB easily!!

SMD PCB adaptersfor prototyping

by Janzfor all computers

www.abidata.be for details.

“How to I2C”

www.saelig.com

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!

2-wire control network

power & information on 2-wires!

CANbus Starter PacksBoards for PCI/ISA/PCMCIA/PC104/VME/compPCI

Drivers for WIn95/98/NT,VxWORKS, pSOS, Lynx,

Linux, OLE, HPVee, LabView, etc.

DrDAQEducationalDatalogger

built-in sensors!www.drdaq.com

," '. , ) / 0,1 2 0 2 *+ !3' 4 5 6"- 7 "'4 + !8#87 '

new!

Page 48: Circuit Cellar2002 03

either COM1 or COM2 with a com-mand line option of -p1 or -p2. Anystandard data rate (1200, 2400, 4800,9600, 19,200, 28,800, or 57,600 bps)may be selected with the -r <BAUDRATE> option. You should supply anIntel hex object file name and a baseaddress for the emulation memory,where you wish to locate your binarycode. Choose the base address F000Husing command line option -b60. Theutility LOADX051.EXE verifies thecommand line base address in theobject file and converts it to a binaryfile. Then, the utility displays a“Synchronizing…” message whilewaiting for a “ready” string messagefrom the emulator (see Photo 1).

The Hi-Tech compiler allows youto write assembly language instruc-tions in C using a source file with an

46 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

uses the same V.2.0 pod for targetboard connection. This circuit operatesonly from the target crystal oscillator.

FIRMWAREThe firmware for the emulator is

developed mostly in C and partly inMCS-51 assembly language. In thepast, we’ve used the Hi-Tech C com-piler for MCS-51. Any other 8051-compatible C compiler should equallywork well for your project. Thefirmware is responsible for loading theobject code in the emulator RAM andexecuting it on request (see the gocommand, g, in Photo 1).

A glimpse of the emulator loadercode is shown in Listing 2. You need acommand line DOS utility (namelyLOADX051.EXE) to download theobject file to the emulator. Select

ation is carried out by the AT89Cx051device itself. The emulator PCB possi-bly should have a 20-pin ZIF (zeroinsertion force) socket to hold the con-troller of the AT89Cx051 device. LEDsD7, D8 and D9 indicate the status ofthe emulator circuit. A detailed dis-cussion about the flash memory pro-gramming is beyond the scope of thisarticle, but anyone interested in moreinformation should read the Atmeluser’s manual for microcontrollers. [4]Additionally, the company’s web siteprovides application notes about pro-gramming flash memory.

The circuit has a provision for a five-wire RS-232 serial interface with RTSand CTS handshake signals. This cir-cuit is powered using a 15-VDC powersupply. Use the onboard regulator,IC7, to generate the 5-V. The emulator

Figure 6—The schematic of the V.3.0 emulator shows a full-featured AT89Cx051 device. Most of the circuit is dedicated to handling on-chip flash memory programming.

Page 49: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 47

#asm - #endasm directive, or asmkeyword. The interrupt vector table(IVT) is declared in MCS-51 assemblylanguage (see Listing 3). When any tar-get (internal or external) interrupt isactivated, the program control ispassed to the IVT in the AT89C51’sflash memory. The LJMP instructionin the IVT redirects it further to thecorresponding vector (emulationRAM) location of the application code.

When writing application programs,you should declare an interrupt vectortable and write an interrupt serviceroutine (ISR) for each interrupt you use.The unused ISR should be terminatedwith a RETI instruction. After perform-ing the emulation RAM test, the emu-lator sends a “ready” message. Then,LOADX051.EXE transmits a 2-bytebase address, MSB to LSB. The emula-tor code confirms the IVT location rel-ative to this base address and proceedsto receive a 16-bit code byte count.

The utility next initializes a downcounter and loads the received binarydata byte by byte to the RAM. Anunsigned character pointer variable (p)writes to the data using MCS-51 exter-nal data memory (signal *WR) access.Following that, LOADX051.EXE dis-plays the progress of the object codedownloading on the PC. After thecomplete object code is loaded inmemory, each byte is read back tocompute a 16-bit checksum. The bytesare read using code pointer variable cpwith the *PSEN signal. Finally, thechecksum is transmitted to the PC. LOADX051.EXE similarly computes

its own checksum value and comparesit to the emulator value. The programdisplays both of the checksum values,and then waits for the go commandfrom the PC if it finds a match.

The emulator code uses an indirect(assembly language) jump instructionto execute the application program(see Listing 2). Because the applicationprogram is normally continuous,pressing the Reset switch is the onlyway to stop the process and start load-ing a new program. The V.1.0 emula-tor implements a software UARTusing the bit-bang technique (seeListing 1). Two routines, SendChrw()and RecvChrw(), transmit and receiveserial data using two general I/O port

lines (in this case, P2.5 and P2.6) with8 bits, no parity, and 1 stop bit. Theseroutines are useful for performingserial I/O on 8051 derivatives thatdon’t have internal UARTs or forimplementing a second serial chan-nel. The routines make use of thesoftware time delay loop. The delayvalue depends on the crystal; you maycompute it using the formula men-tioned in Listing 1.

The V.2.0 emulator (see Figures 4and 5) firmware resides in two con-trollers, the AT89C51 emulationdevice (IC6) and a AT89C2051 (IC7)supervisory controller. The emula-tion microcontroller code is similarto the code in V.1.0. This code getsthe application code bytes from theAT89C2051 instead of the PC. TheAT89C2051 has to do many jobs. Forinstance, during power-up, theAT89C2051 initializes its hardwareUART for 19,200 bps. Because all ofthe port lines are logic high duringreset, the onboard clock is selectedfor the emulation microcontroller,the emulation memory is write-pro-tected with the *ENWR signal, andthe comparator output buffer (IC9A)is in tri-state format.

IC7 reads the onboard DIP switchesand stores various emulator settings.The AT89C2051 controls overall oper-

Photo 2—In this view of the V.2.0 hardware, you cansee a 20-pin header and the 74HCT04 IC for the targetcrystal oscillator circuit. The emulator board and podare connected with a 20-pin FRC cable. The cablelength should be as short as possible.

Page 50: Circuit Cellar2002 03

48 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

state. IC7 takes the MODE signal(P1.4) port line low to inform IC6 thatthe object code has been completelydownloaded. When you press “g” key,IC7 selects the appropriate clockdrive signal to IC6 as per the DIPswitch settings and takes the TRSTport line low. This enables IC6 torecover from the reset condition. IC6checks the mode input (P2.7) for alow state; if the low status is found,IC6 knows that the object code isalready loaded. If this is the case, IC6

ation and is mainly used for loadingobject code from the PC. Its down-loading firmware logic is similar tothat of V.1.0, except for the use of anon-chip hardware port for serial com-munication with a PC.

After the object code is down-loaded to the emulation memory, IC7takes the TRST port line high. TheTRST signal drives transistor T1 tooff state and turns on transistor T2.This discharges the IC6 reset capaci-tor (C7) and holds IC6 in a reset

jumps to the base address for execu-tion or sends a “ready” message andbegins loading object code. LED D2glows to indicate that the object codeis downloading. The go command isindicated by LED D1.

A V.3.0 firmware algorithm receivesthe object code and programs the flashmemory on the fly. Because approxi-mately 2 ms are required to program 1byte, the PC side object code loadingprogram (e.g., LOADX051.EXE) mustwait for this much duration.Otherwise the previous data byte willbe overwritten and lost. You canselect a lower data rate so that theamount of time required for serialtransmission of 1 byte exceeds the 1-byte flash memory programming dura-tion. Alternatively, you may use RTSand CTS handshaking signals from theRS-232 serial interface.

The UART of the AT89C51 doesn’thave RTS and CTS signals, therefore,you have to use two I/O port lines(IC1 P2.6 and P2.7 shown in Figure 6)to generate these signals under soft-ware control. The firmware reads theflash memory using a verificationoperation and computes the check-sum for sending it to the PC. DIPswitches 1 and 2 decide the emulatingdevice type. The firmware loads onlythe permitted sizes—1, 2, or 4 KB—ofthe object code. You can disable theconnection of the AT89Cx051device’s serial port to the PC usingDIP switch 3. This may be requiredif port pins TP30 and TP31 are notused for serial I/O.

CONSTRUCTIONMaking the tiny plug used to con-

nect the emulator board to the targetboard is simple. First, two 20-pin ICsockets are glued face to face. Thecorresponding pins of the two socketsare connected with small, stiff, sin-gle-strand wire before gluing. Solderthe assembly to the emulator podPCB at the bottom side. The topsideof the PCB has a 2 × 10-pin header forconnecting a 20-pin FRC cable, asshown in Photo 2.

All of the emulator circuits use thesame RS-232 serial interface, whichyou can see in Figure 2. The emulatorrequires a three-wire (five-wire if

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 53: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 51

you’re using V.3.0) cable for RS-232connection to the PC. The RS-232handshake signals (at the PC connec-tor) should be connected in a nullmodem configuration. The emulatorPCB is double sided with plated-through holes. IC sockets are used tosimplify hardware debugging.

So far, we skipped an integral partof the system, the power supply cir-cuit. Versions one and two of theemulator may use 5-V power fromthe target board circuit. The third ver-sion requires a separate 15-V powersupply. The current rating of thispower supply is decided mainly by thereed relays. The 15-V regulator ICshould be fitted on a proper heat sink.You have to make a nine-core D-typestraight cable for connecting theemulator circuit to the RS-232 serialinterface (COM port).

HOW DO I CHOOSE?Some of you may get confused when

it comes to choosing the best part.Each circuit offers specific advantagesand may be more suitable for a specif-ic application. This is why we present-ed all of the circuits rather than just acouple of decent ones.

The V.1.0 emulator is the easiest ofthe bunch to implement. This versionmeets most of the AT89Cx051 soft-ware development requirements. Ifyour application has a constraint forthe target oscillator operation, we rec-ommend V.2.0. Keep in mind that it’sslightly difficult to debug a circuit

SOURCESAD7713 Sigma-delta serial ADCAnalog Devices, Inc.(800) 262-5643(781) 329-4700www.analog.com

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

C CompilerHi-Tech Software61-7-3552-7777Fax: 61-7-3552-7778www.htsoft.com

SOFTWARETo download the code, go to ftp.cir-cuitcellar.com/pub/Circuit_Cellar/2002/140/.

REFERENCES[1] Atmel Corp., “Analog-to-Digital

Conversion Utilizing the AT89CX051 MCU,” 0524A-B, December 1997.

[2] Intel Corp., MCS 51 Micro- controller Family User’s Manual,272383-002, February 1994.

[3] Atmel Corp., “Designing Boards with Atmel AT89C51/52, AT89C1051 for Writing Flash at In-Circuit Test,” rev. 0534B-A, December 1997.

[4] Atmel Corp., “Atmel CorporationMicrocontroller Data Book,” October 1995.

Mrs. Prajakta Deshpande earned aB.S. from Sagar University and aMasters of Computer Applications(M.C.A.) from Barkatullah VishwaVidyalaya, both in India. Currently,she lectures about computer science.You may reach her at [email protected].

built with V.2.0 because it involvescommunication between two micro-controllers. We used the V.1.0 emula-tor to develop the software for theV.2.0 emulator. This plan has only onedeficiency: V.2.0 does not support theLED driving port pins.

A circuit built with V.3.0 is com-plex but worth the trouble because it’s100% compatible with AT89Cx051devices. This circuit extends the tar-get board with in-circuit flash memo-ry programming capabilities. In addi-tion, after it’s debugged, the emula-tion microcontroller simply can beinserted into the target board, ready torun the application code. If you usethis circuit, you’ll also need anAT89Cx051 device for it to emulate.

Note that it’s possible to use a sin-gle AT89C4051 to emulate all threedevices. Because a circuit based on theV.3.0 emulator contains more on-chipRAM (128 bytes), you should be care-ful when using it to developAT89C1051-based applications; theAT89C1051 has only 64 byte of RAM.

For those of you who want to buildwith the V.1.0 emulator, you maydownload the source code from theCircuit Cellar web site. One morenote, although the emulator circuitspresented here are affordable, theyincrease in cost from V.1.0 to V.3.0.Now, with any one of the emulatorcircuits as your tool, you can thinkabout developing various embeddedapplications using the AT89Cx051microcontroller family. I

Listing 3—The assembly language interrupt vector declaration captures all of the interrupts and redirectsthem to the corresponding emulation RAM address.

//declaration of interrupt vector table in flash memory#asm

psect vectors,ovrld //directive to declare this as IVT

ORG 03h //INT0 locationLJMP START_ADDR + 03hORG 13h //INT1 LocationLJMP START_ADDR + 13hORG 0Bh //TIMER0 locationLJMP START_ADDR + 0BhORG 1Bh //TIMER1 LocationLJMP START_ADDR + 1BhORG 23h //serial port interrupt locationLJMP START_ADDR + 23h

#endasm

Mr. Praveen Deshpande earned a B.S.in Electronics Engineering fromRegional Engineering College (REC)in Nagpur, India. Presently, he worksas a senior scientific officer in thefield of distributed data acquisitionand control. His interests includereal-time operating systems and dis-tributed control. You may reach himat [email protected].

Page 54: Circuit Cellar2002 03

52 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

or the process-ing of analog sig-

nals, many of the cur-rent microcontrollers

(MCUs) include an A/D multichannelconverter. The converter has severalinputs connected to it by means of ananalog multiplexer. Usually theseMCUs have one or more pulse widthmodulator (PWM) outputs that can beused as D/A converters.

Sometimes it’s convenient to gener-ate an analog output with software inan MCU that lacks PWM outputs orto increase the number of availableanalog outputs in the chip. This arti-cle is about the technical softwarethat can generate analog outputsusing 1-bit converters, like the well-known PWM and the less popularsigma-delta modulators.

PWM D/A CONVERTERThe DAC is based on a PWM with

many positive characteristics. It uses aPWM output that provides a rectangu-lar signal of constant frequency andvariable duty cycle followed by an RClow-pass filter that obtains the aver-age value of the rectangular signal. Toget a PWM output, you only need totoggle a unique output pin of theMCU at logical values.

Figure 1 shows the PWM output with3-bit resolution using a module eightcounter and a 3-bit comparator. Thecounter’s outputs are connected to oneof the comparator’s inputs, and the digi-tal value of the wanted output is appliedto the other input of the comparator.

The output of the comparator staysat a high level while the counter stateis less than the wanted value of output.When the counter’s value is greaterthan or equal to the value of the otherinput of the comparator, the output ofthis passes at a low level. This way,the output of the comparator generatesa pulse for each complete count cycle.

You can calculate the maximumnumber of samples that can be sent to aPWM output by dividing the frequencyof the clock by the counter’s modulus.If you want 8-bit resolution that allowsa 1-KHz refresh speed, you need a mini-mum clock frequency of 256 KHz. Forthis reason, the converters based onPWM outputs usually are used in appli-cations that require slow refresh speeds.

A timer that requests periodic inter-rupts can produce a PWM output of n-bit resolution. Every time the timerrequests an interrupt, the n-bit variable(counter) is increased. The value iscompared to the wanted output value.Depending on the result of the compari-son, the output value of the PWM mod-ulator occurs as shown in Figure 2a.

Balancing D/AConversion on One Pin

fIf you’ve ever thoughtit would be nice togenerate an analogoutput from an MCUwithout PWM outputs,you’re not alone.Mariano and Javierhave already donethe homework andcome up with the soft-ware that allows forjust such a beneficialconvenience.

Mariano Barrón &Javier Martinez

FEATUREARTICLE

Counter

Comparator

Clock

Digitalinput (DI)

DI > count

DI > countAnalogoutputLow-pass

filter

01

23

45

67

01

23

45

67

01

23

45

67

TON

TOFF

TON

TOFF

TON

TOFF

Counteroutputs

DI = 3

Figure 1—If the n bit value of the digital input is not zero, then the output of the PWM without a filter will generateonly one pulse every 2n clock pulses.

Page 55: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 53

[3]

You need a simple RClow-pass filter to calcu-late the average value ofthis output.

With the software, youcan use a timer thatrequests periodic inter-rupts to generate an outputof n-bit resolution. Everytime the timer requestsan interrupt, it adds thecontent of an n-bit regis-

ter, called accumulator (ACC), to thewanted output value. Use the carry bitdetermined by this sum to activate theoutput value of the modulator. Figure 4illustrates the process.

If a PWM modulator and a sigma-delta modulator have the same n-bitresolution, they work at the same clockfrequency and receive the same valuein their digital input. So, the outputvalues determined by the two modula-tors during a time interval equivalentto 2n clock pulses should remain athigh and low levels simultaneously.

The difference resides in the factthat the PWM outputs group all of theones and zeros, but the sigma-deltaoutputs try to distribute the ones andzeros uniformly inside the interval oftime equivalent to 2n clock pulses.Consequently, the sigma-delta outputscontain higher frequency componentsthan the PWM outputs, thus the filter-ing is simpler. As a result, if the sameRC low-pass filter is used to average aPWM or sigma-delta output, the latteryields a better result.

You can see the waveforms generatedby the PWM and sigma-delta modula-tors, both with 4-bit resolution, inFigure 5. The numbers that appear nextto the signals of the sigma-delta modu-lator are the values that the accumula-tive register stores in each instant. Themodulators produce identical signalsonly in extreme cases corresponding tothe values of outputs zero, one, and 15.

In light of this fact, it’s evident thatwhen using an RC filter to get the ana-log average value, usually the sigma-delta converter will work best. Thismodulator will provide an output withonly minor ripple because the charge

The algorithm discussedcan consume a lot of CPUtime, because 256 timerinterrupts are needed togenerate a pulse in a PWMoutput with 8-bit resolu-tion. Figure 2b shows abetter solution. Now, foreach pulse in the PWMmodulator’s output, onlytwo timer interrupts areneeded. Variables TON andTOFF store the values neces-sary to recharge the timer.

D/A SIGMA-DELTA CONVERTER Converters based on sigma-delta

modulators use a pin that changestheir state between two voltage levelsand uses a clock frequency much high-er than the maximum refresh frequen-cy of the analog output.

Figure 3 shows a sigma-delta 3-bitresolution output using an adder and a3-bit accumulative register. For eachclock pulse the register stores the resultof a new sum. In this case, the value ofthe digital input can vary between zeroand seven. If during eight clock pulsesthe digital input (DI) value doesn’tchange, it means that eight sums of theDI value have completed and DI carrieshave taken place. Using the carry out

of the adder as sigma-delta modulatoroutput with a period of eight clockpulses, you’ll have a high level duringDI pulses and a low level during 8 – DIpulses on the output. Supposing thatthe output of the adder’s carry variesbetween 0 V and VCC, the averagevalue of the output signal will be:

[1]

varying from:

[2]

with increments of:

No

Output = 0 Output = 1

Counter < value?

Counter ++

Yes

PWM_1

End

No

Reload timerwith TON

Output == 1?Yes

PWM_2

End

Reload timerwith TOFF

No

Invert output

TON == 0?Yes

Output = 0

Figure 2—To generate a PWM output using a timer interrupt, use these flow charts.

a) b)

Listing 1—The code snippet shown generates one PWM output using the timer T0 interrupt.

PR_INTE_T0_PWM SEGMENT CODE DT_PWM SEGMENT DATA

PUBLIC VRSEG DT_PWM

V: DS 1CSEG AT 0000BH

LJMP INTE_T0RSEG PR_INTE_T0_PWM

INTE_T0: PUSH ACC MOV A,V JZ LABEL_02 CPL P1.0 JNB P1.0,LABEL_01 MOV A,V CPL A INC A MOV TH0,A //TH0 = 256 V SJMP LABEL_03

LABEL_01: MOV TH0,V //TH0 = V SJMP LABEL_03

LABEL_02: CLR P1.0

LABEL_03: POP ACCRETI

Page 56: Circuit Cellar2002 03

54 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

same clock frequency. Under these con-ditions, the losses by commutation in asigma-delta output also will be 2(n – 2)

times bigger than a PWM output. For 8-bit resolution, the average number oftransitions of a sigma-delta output is 64times higher than that of a PWM output.

GENERATING A PWM OUTPUTLet’s look at a program to generate

an 8-bit resolution PWM output withan 8051 MCU using the periodic inter-rupt of timer T0 (see Listing 1). Theinterrupt service routine is adjusted to

and discharge times of the capacitor areinferior to the PWM modulator. If youanalyze the spectrum of both outputtypes, you’ll reach the same result. [1]

Keeping everything in mind, we cansay that the sigma-delta outputs aresuperior to the PWM outputs when wewant to obtain the analog average valueby means of an RC filter. However,with applications in which it’s impor-tant to minimize energy losses pro-duced by the commutation, PWM out-puts are the most appropriate becauseof the smaller number of transitions.

What relationship exists between thenumber of transitions of a PWM outputand a sigma-delta output of the samenumber of resolution bits? A PWMoutput of n bits generates a single out-put pulse (two transitions) for each 2n

clock pulse applied to the counter inFigure 1. Depending on the value of thedigital input, a sigma-delta output gen-erates a variable number of output puls-es for every 2n clock pulses applied to theaccumulative register in Figure 3. Forthis reason, it makes more sense to tryto find the average value (AV) of thenumber of pulses generated in the carryoutput of the adder, after having applied2n clock pulses to the accumulative reg-ister. Taking the data in Figure 5 and a4-bit resolution sigma-delta output, youcan calculate Equation a in Figure 6.

The average number of transitions willbe twice as much (eight). Extrapolatingthis result to an n-bit resolution genera-tor, the average number of generatedpulses is calculated using Equation b inFigure 6. When you reorder Equation b,you get Equation c or d in Figure 6.

With the ΑV value for an outputPWM as one, you can affirm that an n-bit resolution sigma-delta output gener-ates an average of 2(n – 2) times more puls-es and transitions than a PWM outputof the same resolution and uses the

the flow diagram in Figure 2b. TimerT0 works in 16-bit mode. It requests aninterrupt when it overflows (passesfrom 0xFFFF to 0x0000). When an inter-rupt occurs, the state of pin P1.0 isinverted and registers TH0 and TL0are recharged appropriately.

In this example, suppose that the peri-od of the PWM output takes 216 = 65,536machine cycles. This is needed to re-charge the high byte TH0. Indeed, ifyou want to generate an analog value,known as V (0 = V ≤ 0xFF), the re-charge values of the timer to make TOFF

temporary should be TH0 = V and TL0 =0, and the recharge value to make TON

temporary should be TH0 = (256 – V)and TL0 = 0. This results in Equation eshown in Figure 6. No pulse will berejected because you’re not rechargingTL0. Also, there won’t be an error ifTH0 is recharged before 256 cycleslapse since the interrupt was requested.

If you need to generate an analog valueof zero, the PWM output will stay at

Listing 2—With this code, you can generate eight PWM outputs using the timer T0 interrupt.

PR_INTE_T0_PWM SEGMENT CODE DT_PWM SEGMENT DATA

PUBLIC V //unsigned character V[8] PUBLIC COUNTER //unsigned character COUNTERRSEG DT_PWM COUNTER: DS 1 //unsigned char COUNTER V: DS 8 //unsigned char V[8]

CSEG AT 0000BH //T0 interrupt vector LJMP INTE_T0RSEG PR_INTE_T0_PWM

INTE_T0: PUSH ACC PUSH PSW MOV PSW,#08H //use register bank 1 MOV TH0,#0FEH //interrupt after 512 cyclesINC COUNTER MOV R0,#LOW (V) //R0 point to V[0]

//; MOV R1,#00H MOV R2,#08H //repeat eight times

LABEL_01: MOV A,@R0 //ACC = VALUE CJNE A,COUNTER,LABEL_02 //CY = 0 if VALUE ≥ COUNTER SETB C //C1 = 1 if VALUE = COUNTER

LABEL_02: CPL C //CY = 1 while VALUE > COUNTERMOV A,R1 RRC A //rotate right through carry bit MOV R1,A //move CY to R1.7 INC R0 DJNZ R2,LABEL_01 MOV P1,R1 //refresh PWM outputs POP PSW POP ACCPETI

Clock

DI

Carry out

Carry out

Analogoutput

Low-passfilter

0

23

45

6

7Registerinputs

DI = 3

Register

Adder1

0

3

6

12

45

7

0

3

6

12

45

7

Figure 3—The output of the sigma-delta modulator can generate to 2(n – 1) pulses for each 2n clock pulse.

Page 57: Circuit Cellar2002 03
Page 58: Circuit Cellar2002 03

56 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

By not changing the TL0, you ensuremore precision because when thetimer passes from 0xFFFF to 0x0000,it requests an interrupt but continuescounting. Because you’re not recharg-ing TL0, no pulse will be rejected andyou won’t have an error when theTH0 is recharged before 256 cycleslapse since the interrupt was requested.

The program uses nine variables ininternal RAM, one to maintain an 8-bitcounter and the other eight to store thevalues of the analog outputs. Just as thediagram of PWM_1 in Figure 2a shows,for every interrupt requested by T0, thevariable counter is increased and eightcomparisons to the values of the PWMoutputs to generate are carried out.Depending on the result of these compar-isons the eight PWM outputs are actual-ized. In this example, the eight PWMoutputs are the eight pins of the P1 port.

To minimize the execution time ofthe T0 interrupt, this interrupt reservesregister bank 1, eliminating the pushand pop instructions of the R0, R1, R2,and R3 registers used by the interrupt.

If the 8051 uses a 12-MHz crystal

The maximum speed of PWM outputrefresh depends on the MCU’s crystal.If you use a 12-MHz crystal (1016 cyclesper second), the maximum refreshspeed of the PWM output will be:

[4]

EIGHT PWM OUTPUTSWhen the number of outputs the

PWM has to generate is high, the solu-tion proposed in Figure 2b gets com-plicated. Resorting to the diagram inFigure 2a can be a convenient solution.This way, you have a simpler programbut use more interrupts (see Listing 2).

Now, it’s time to learn how to gener-ate eight 8-bit-resolution PWM outputswith an 8051 using the periodic T0interrupt. Suppose that timer T0 isworking in 16-bit mode and requests aninterrupt when it overflows (passes from0xFFFF to 0x0000). The interrupt serv-ice routine recharges the timer T0 with0xFE00 so that a new interrupt takesplace after 512 machine cycles. The lowpart of the TL0 is not recharged to zero.

zero and the timer T0 won’t be re-charged. This way, one will have a newinterrupt when T0 passes from 0xFFFFto zero again. Because, in this case, thevalues with which the TH0 registershould be recharged are V and 256 – V,the program uses a single variable ininternal RAM to store the voltage value.

Every 65,536 machine cycles, twocalls are sent to the T0 interrupt serv-ice routine, which has an average dura-tion of 21 machine cycles. The genera-tion of the PWM output consumes42 machine cycles every 65,536 cycles,or 0.064% of the CPU’s time.

No

Output = 0 Output = 1

Carry out?

ACC + = value

Yes

Sigma delta

End

Figure 4—This flow diagram demonstrates how togenerate a sigma-delta output using a timer interrupt.

Page 59: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 57

an instruction in one clock pulse andcan work at frequencies up to 20 and50 MHz, respectively. [2, 3, 4] Withmodern MCUs you can generate ana-log outputs of much higher frequen-cies or that consume less CPU time.

EIGHT SIGMA-DELTA OUTPUTSMoving on, let’s examine how to

program and generate eight 8-bit sigma-delta outputs with an 8051 using the

periodic interrupt of T0 (see Listing 3).As you see, the instructions are thesame. The program uses 16 variables ofinternal RAM. Eight variables store thevalues of the analog outputs and anoth-er eight store the accumulators thateach output needs. As Figure 4 shows,for every interrupt requested by T0, thevalue of the associate variable is added toeach accumulator. The carry bit is usedto generate the corresponding output.

(1016 machine cycles per second), the T0interrupt will occur at a frequency of:

[5]

The PWM outputs have 8-bit resolu-tion, so the maximum refresh frequen-cy of the outputs will be:

[6]

The T0 interrupt routine has an aver-age duration of 99 machine cycles, sogeneration of the eight PWM outputsconsumes 19.3% of the CPU time, or:

[7]

A maximum refresh speed of 7.63 Hzisn’t a high value, but the 8051 needs12 clock pulses to execute an instruc-tion. Today, some 8051s execute instruc-tions using fewer clock pulses. Amongthe quickest are the Cygnal C8051F000and Dallas DS89C420, which execute

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

1 2 3 4 5 6 7 8 9 A B C D E F 0 1

2 4 6 8 A C E 0 2 4 6 8 A C E 0 2

3 6 9 C F 2 5 8 B E 1 4 7 A D 0 3

4 8 C 0 4 8 C 0 4 8 C 0 4 8 C 0 4

5 A F 4 9 E 3 8 D 2 7 C 1 6 B 0 5

6 C 2 8 E 4 A 0 6 C 2 8 E 4 8 0 6

7 E 5 C 3 A 1 8 F 6 D 4 B 2 9 0 7

8 0 8 0 8 0 8 0 8 0 8 0 8 0 8 0 8

9 2 B 4 D 6 F 8 1 A 3 C 5 E 7 0 9

A 4 E 8 2 C 6 0 A 4 E 8 2 C 6 0 A

B 6 1 C 7 2 D 8 3 E 9 4 F A 5 0 B

C 8 4 0 C 8 4 0 C 8 4 0 C 8 4 0 C

D A 7 4 1 E B 8 5 2 F C 9 6 3 0 D

E C A 8 6 4 2 0 E C A 8 6 4 2 0 E

F E D C B A 9 8 7 6 5 4 3 2 1 0 F

Sigma-delta modulation

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

1

2

3

4

5

6

7

8

9

A

B

C

D

E

F

Pulse width modulation

Figure 5—For a total picture, take a look at all of the output waveforms of a 4-bit resolution PWM (left) and a 4-bitresolution sigma-delta modulator (right).

Page 61: Circuit Cellar2002 03

UP TO SPEEDSo far, we’ve shown how to generate

an analog signal using an output pin ofan MCU, a timer interrupt, and an RClow-pass filter. We demonstrated that asigma-delta output, on average, multi-plies the number of transitions of aPWM output by 2(n – 2). The software gen-erates one or eight analog outputs withPWM modulation and eight outputswith sigma-delta modulation in an 8051.

The interrupt service routines to gen-erate eight analog signals using PWMor sigma-delta modulators have almost

the same duration and takeless than 100 machinecycles. Rewriting the func-tions for a different MCUshould not introduce prob-lems and will execute inabout 100 machine cycles.This means that if anMCU of 1 MIPS is used andthe interrupt routine occurs2560 times per second,

eight analog outputs of 8-bits resolutioncan be generated. These outputs can berefreshed to a maximum speed of 10 Hzconsuming 25.6% of the CPU’s time.

Today, it’s easy to get 10-MIPS MCUs.In this case, the generation of eight ana-log outputs to 10 Hz would consumeonly 2.56% of the CPU’s time. Recently,the System-on-a-Chip (SoC) appeared,which integrates a CPU and a block ofprogrammable logic in the same pack-age. [5] With SoCs, you can generateanalog signals without consuming CPUtime to achieve a higher speed whenrefreshing the outputs. To do so youmust use the block of programmablelogic to build either the PWM or sigma-delta modulator, following the outlinesshown in Figures 1 and 3. I

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 59

In this example, the eightsigma-delta outputs are theeight pins of port P1. Tominimize the executiontime of the T0 interrupt,this interrupt reserves regis-ter bank 1, eliminating thepush and pop instructions ofthe R0, R1, R2, and R3 reg-isters used by the interrupt.

As in the case of thePWM converter, the timer interruptwill occur at a frequency of 1953 Hzand when the resolution of the sigma-delta output is 8 bits. The maximumfrequency to refresh the outputs is:

[8]

The routine of the timer interrupt hasa duration of 99 machine cycles, forwhich the generation of the eightsigma-delta outputs consumes 19.3%of the CPU time.

Javier Martinez teaches electronic sys-tems at a secondary school in LaRioja, Spain. You may reach him [email protected].

REFERENCES[1] D. Tweed “Digital Processing in

an Analog World—Part 3: Dithering Your Conversion,” Circuit Cellar 101, December 1998.

[2] Cygnal Integrated Products, Inc., “C8051F000/1/2 C8051F010/1/2 Mixed-Signal ISP Flash MCU,” rev. 1.1, September 2000.

[3] Dallas Semiconductor, Inc., “DS89C420 Ultra High Speed Microcontroller,” September 2002.

[4] T. Cantrell, “Cygnal Processor,” Circuit Cellar Online, September2000.

[5] ———, “SoC It to Me,” Circuit Cellar 116, March 2000.

Mariano Barrón is a professor of con-trol engineering at University of theBasque Country in Spain. You mayreach him at [email protected].

Listing 3—Using the timer interrupt, you can produce eight sigma-delta outputs.

PR_INTE_T0_SIGMA //segment code DT_SIGMA //segment data

PUBLIC V //V[8] (values) PUBLIC S //S[8] (accumulators)RSEG ?DT?SIGMA

S: DS 8 //V[8] (values) V: DS 8 //A[8] (accumulators)

CSEG AT 0000BH //T0 interrupt vector LJMP INTE_T0RSEG PR_INTE_T0_SIGMA

INTE_T0: PUSH ACC PUSH PSW MOV PSW,#08H //use register bank 1 MOV TH0,#0FEH //interrupt after 512 cyclesMOV R0,#LOW (S) //R0 point to A[0] MOV R1,#LOW (V) //R1 point to V[0]

//MOV RS,#0 MOV R2,#00H MOV R3,#08H //repeat eight times

LABEL_01: MOV A,@R0 //ACC = *p_accumulator ADD A,@R1 //ACC += *p_value MOV @R0,A //*p_accumulator = ACC MOV A,R2 RRC A //rotate right through carry bit MOV R2,A //move CY to R2.7 INC R0 INC R1 DJNZ R3,LABEL_01 MOV P1,R2 //refresh sigma-delta outputsPOP PSW POP ACCRETI

AV = 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 116

= 6416

= 4

AV =0 + 1 + + 2n – 1 – 2 + 2n – 1 – 1 + 2n – 1 + 2n – 1 – 1 + 2n – 1 – 2 + + 2 +1

2n

2 + … …

AV =0 + 1 + 2 n – 1 – 1 + 2 + 2n – 1 – 2 + … + 2n – 1 – 2 + 2 + 2n – 1 – 1 + 1 + 2n – 1

2n

AV =0 + 2 n – 1 + 2 n – 1 + … + 2n – 1 + 2 n – 1 + 2 n – 1

2n=

2 n – 1 × 2n – 1

2n= 2n – 2

Period = TON + TOFF = [ 256 × (256 – V)] + (256 × V) = 256 × 256 = 216 Machine cycles

Figure 6—Use these equations as guidelines.

a)

b)

c)

d)

e)

Page 62: Circuit Cellar2002 03

adder logic.That sounds like

something paintersand window washers

would use and be good at. On theother hand, my plumber friend andhis father both fell off the same lad-der performing the same plumbingtask at the same house with the lad-der in the same position for each oftheir falls. If you were to poll me onwho’s who of ladder logic, I’d say thecouple of plumbers I know are defi-nitely not experts at it.

Ladder logic came along in the fabu-lous 1960s and matured with the greatmusic my teenagers think was writtenby contemporary rap artists. Unlikethe rappers, ladder logic is an originaland didn’t have much except relaycoils to take anything from. In fact, I’dwager that some of our most popularmicros took some pointers from thebeginnings of automated industrialcontrol in which ladder logic was akey player.

Ladder logic’s climb to popularityoriginated in Motown as auto manu-facturers were trying to find a suitablereplacement for the relay-basedautomation found on their assemblylines. Out went the relays and incame the Programmable Logic

Controller (PLC), and right there withit was a newfangled programminglingo called ladder logic.

The new programming languageadopted some of the old relay logiclingo. Ladder logic programs are full ofrelays, coils, and contacts. Some ofthese relay components are real andmany more of them are logical, or, fora better word, virtual, as they onlyexist in the mind of the PLC.

As I studied example ladder logicprograms and experimented with myown ladder logic creations, I realizedthat the relay coils and contacts in myprograms were the bits that controlthe behavior of my embedded pro-grams. Taking the analogy a bit fur-ther, the ladder logic inputs and out-puts perform the same functions asI/O pins on microcontrollers. With theinclusion of timer coils, counter coils,and sequencers, ladder logic is to PLCswhat C is to microcontrollers withone major difference. The microcon-troller behind a ladder logic program ison steroids and a daily regimen ofBowFlex strength training.

WHAT’S FRED UP TO?Well, if you’re wondering why I’m

on the rungs, I happen to have a real-live PLC from Triangle ResearchInternational in my possession. ThePLC you see all lit up in Photo 1 is aT100MD888+. This PLC is chock fullof relay coils, relay contacts, timers,counters, sequencers, PWM outputs,analog inputs, analog outputs, andhigh-current I/O.

What really makes this TrianglePLC shine is its ability to use an IPnetwork for control and monitoringpurposes and its extended ladderlogic programming language calledLadder+BASIC. Of course, theT100MD888+ understands all of thestandard PLC protocols like OMRON,MODBUS, ASCII, and RTU.

I didn’t get a schematic diagramwith my T100MD888+, however, Irecently completed a job that usedsome of the components on theT100MD888+ circuit board. So, Idecided not to violate any of the pro-tective labels, and instead tackle figur-ing out what I could about how theT100MD888+ works physically. Some

60 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

Replacing Relays withLadder Logic

lFred’s reaching forthe sky with his latestproject so it’s no sur-prise that ladder logiccame into play. With awell-balanced pro-grammable logic con-troller board, Fredobserved the “Do notdisturb” labels on theboard and tried figur-ing out the hardwarevia the software.

Part 1: Getting Ready for the Climb

Fred Eady

APPLIEDPCs

Page 63: Circuit Cellar2002 03

remove the 74HCT14, a 74HC595,and a 74HCT165 from the vicinity ofthe input connector. I applied powerto the T100MD888+ and noted thatmy test program didn’t respond to itsinput but the input LEDs still illumi-nated when I took each of them toground. That told me that the resistornetwork uses the incoming groundsignal to illuminate the input statusLEDs. The result also proved my the-ory that the 74HC595 is being used asa serial-to-parallel converter for theexpansion port in conjunction withthe 74HCT165 performing the expan-sion port parallel-to-serial conversionduty. Using a ribbon cable, you canadd 40 analog and 40 digital outputsto the T100MD888+ through theexpansion connector.

One last mystery in the input areais the monolithic presence of a lone7805 voltage regulator sans externalheat sink. Inspecting the circuittraces, I found the output of this regu-lator directly tied to the 74HCT14 VCC

pin. Well, that made sense, but whatare those other two regulators doingon the other side of the board?

Using the silk screen legend I couldeasily make out that one of the regula-tors was a 7818 and its input tieddirectly to the incoming 24-VDC sup-ply. Its output made a beeline to theinput of the second regulator, which issurrounded by a heat sink and a cou-ple of filter capacitors. After a surgi-cally accurate component removalprocedure, I managed to get a glimpseof the heat sink-laden voltage regula-

folks can program blind not caringabout what the hardware is composedof or how it works. I think I gain aprogramming edge knowing what thehardware is doing with my code, or inthis case, ladder logic.

INSIDE THE HARDWAREThe first thing I wanted to do with

my new T100MD888+ was make itturn stuff on and off. Before I startcontrolling the world, it might be agood idea to provide the T100MD888+with some power to help me with myconquests. The T100MD888+ requiresbetween 12 and 24 VDC (preferably24 VDC) for a power source. There’s a12-VDC jumper that must be set ifyou choose to use a 12-VDC supply.

I hooked up my bench supply andcranked 24 VDC into the removablepower connector of the T100MD888+,knowing that was the wrong thing todo. The engineers working at TriangleResearch International didn’t design-in the removable power connectorsjust for me. In fact, the T100MD888+works in hostile factory environmentsother than the Florida room. And, justin case something (or someone in theFlorida room) takes out a T100MD888+,the removable I/O and power connec-tors make it easier to replace the deador wounded T100MD888+. I amhappy to report that the T100MD888+draws 160 mA at rest.

The T100MD888+ comes standardwith eight digital inputs and eight dig-ital outputs all on removable screw-down connectors. These I/Os are mul-tiplexed with other functions likePWM output and high-speed counterinput. Each input pin has a green sta-tus LED that illuminates when theinput is active. Active inputs are inputvoltages on the input pins between 0and 5 VDC (preferably 0 VDC). Theinactive voltage level is 24 VDC usinga 24-VDC supply. The power supplyand unused inputs are pulled to theinactive voltage level.

A 74HCT14 Schmitt trigger isstrategically placed behind a ton ofresistor networks, which are locateddirectly behind the removable inputconnector. I did some probing, andsure enough, the first six inputs flowthrough the Schmitt trigger. Thatmakes sense because all of the specialinputs, like the high-speed counters,quadrature encoder inputs, interruptinputs, and pulse measurementinputs are all grouped within the firstsix inputs. Inputs 7 and 8 are missingin action and assumed connectedsomehow to the processor module ofthe T100MD888+.

I bought a little IC-removal crow-bar from Trinity Works and sincethen, I’ve damaged very few of the ICsI’ve removed from embedded circuitboards. So, I took the liberty to

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 61

Photo 1—The T100MD888+ is a simple and ruggedpiece of hardware that can fly with some of its partsdamaged or missing. How do I know that? I yankedsome ICs and put my assumption to the test. There areonly a couple of parts you can’t get from normal chan-nels, so your local gurus can maintain the T100MD888+.

Listing 1—If you tally the outcome, I wrote only four lines of code to provide a real-time visual indicationof what my ladder logic program was doing.

//OFF CUSTOM FUNCTIONsetlcd 0,1,CHR$(12) //no cursorsetlcd 0,1,CHR$(1) //clear the screensetlcd 1,1,"LEDS OFF"

//1ISON CUSTOM FUNCTION

setlcd 1,1, "LED 1 IS ON" //print at row one, column one

//2ISON CUSTOM FUNCTION

setlcd 1,1, "LED 2 IS ON" //print at row one, column one

//3ISON CUSTOM FUNCTION

setlcd 1,1, "LED 3 IS ON" //print at row one, column one

//4ISON CUSTOM FUNCTION

setlcd 1,1, "LED 4 IS ON" //print at row one, column one

Page 65: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 63

eliminate the relatively expensive inte-grated RS-232 IC. With the presence ofULN parts in the output area and theabsence of any switching componentsaround the MOSFETs, I discounted theuse of the 10 VDC for those purposes.

The T100MD888+ output circuitryis based on a ULN2003, ULN2803,and two IRL530 MOSFETS. Thesedevices are high-voltage, high-current,inverting current sinks that operateon TTL-level inputs. After locatingthe IRL530 data-sheet, I read thatthese are logic-level gate drive MOS-FETS, which eliminates any doubtconcerning the 10-VDC drive assump-tion I made previously.

The IRL530 MOSFETs are heavy-duty units rated to handle 10 A at 24-VDC peak and 2 A continuous each inPWM mode. The MOSFETs are locat-ed on outputs 7 and 8. Outputs 1through 6 are composed of paralleledULN2003 and ULN2803 gates, canprovide peak currents of 1 A, and runall day at 350 mA. A 20-A removableground terminal rounds out the powercircuitry. Red LEDs provide status forthe eight outputs. A 74HC595 takescare of the output status LEDs one,two, three, four, and eight as well asthe RTC error, pause, and run errorindicators. There’s no visible supportfor the remaining output status LEDs,but I’ll bet they are tied back to theengine of the T100MD888+.

The last 74H595 on the T100MD888+circuit board supports a 2 × 16 LCD.The LCD interface is a standard 14-pinlayout that can drive displays fromsimple 1 × 16 to 4 × 20 LCDs. There’salso a potentiometer included toadjust the LCD contrast.

tor’s markings. It’s a 7810. So, theincoming 24 VDC is passed throughthe 7818 and then dropped againthrough the 7810, which passes the10 VDC to the 7805 in the input areaof the T100MD888+. Remember the12-VDC jumper? Now, it looks like itbypasses the 7818 input and puts the12-VDC supply voltage directly on theinput of the 7810.

I measured the voltage at theULN2003 and ULN2803 and their sup-ply inputs were at 24-VDC. I didn’tsearch out other uses of the 10 VDCbecause the options were obvious. Theonly possible places left to use it wouldbe in the RS-232 area or to drive the twooutput MOSFETs.

The documenta-tion for the PLCdefines the RS-232circuitry as a 5- to0-VDC implemen-tation designed to

Photo 3—The only thingsI need to know are myuser name, password,and where the TLServerresides regarding the IP. Iadded the user “fred”using the Add User boxshown in Photo 2.

Photo 2—The TLServer provides a means of remotelycontrolling and monitoring multiple T100MD888+devices either on a LAN or across the Internet. At leastone T100MD888+ must be connected to the PC run-ning the TLServer. The client also can access anyother PLC connected to the server-connected PLC viaRS-485. There’s even an e-mail function to send alertsor status messages from the PLC.

Page 66: Circuit Cellar2002 03

64 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

run-away or drop-dead programs andturns off static nonvolatile RAM ifthe battery/RTC option is installed.

A 15-pin female D shell connectorprovides the interface for six or eightADC channels and two DAC channels.An LM317 and its sidekick poten-tiometer provide an adjustable voltageoutput on one of the D shell pinsthat’s referenced to analog ground.

The ADC and DAC channels arenormalized for 12 bits of resolution.The actual ADC resolution is 10 bitsand the DAC resolution is 8 bits. Theanalog hardware does its thing as nor-mal and the ADC and DAC firmwarefunctions perform the normalizationagainst the data generated by the ana-log subsystems. The normalization isintended to prevent the ladder logiccoder from having to change existingcode to match higher resolution partsif they exist on the target PLC.

CLIMBING THE LADDERNow that you have a good idea of

what’s in the black box, I’m ready tomake the T100MD888+ flash some of

one of its ICs. That’s because the actu-al ladder logic program is stored innonvolatile EEPROM. The four-posi-tion DIP switch allows recovery from

In addition to being able to commu-nicate using RS-232 and IP, theT100MD888+ uses a standard 75176RS-485 driver IC to allow peer-to-peernetworking of multiple T100MD888+devices. The combination of the RS-232 and RS-485 ports coupled withthe ability to work on the Internet oran Intranet makes for a useable PLC.Oddly though, the RS-485 connectoris not removable.

Now, all that’s left to describe are acouple of memory ICs, a four-bankDIP switch, and the T100MD888+analog interface. I/Os, timers, coun-ters, and internal variables includingDAC and PWM data are stored in anindustry standard 62256 256-KB staticRAM. Of course, all of this data is lostwhen the T100MD888+ loses power.If your application requires retentionof the aforementioned data, you canpurchase a piggyback module for the62256 that adds a lithium battery andreal-time clock to the T100MD888+.

I noticed that when loaded, my pro-grams didn’t disappear when I pow-ered down the T100MD888+ to put on

Photo 4—This shot is actually a collection of each ofthe individual panels. The ladder logic labels are justlike the #define statements in your C programs.

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 68: Circuit Cellar2002 03

those status LEDs. The softwarepackage that comes with theT100MD888+ is impressive. InternetTRiLOGI V.5 is a suite of softwaretools that enables the T100MD888+to be monitored and programmedlocally or remotely using a standardserial port of a personal computer,your office Intranet, or the Internet.

TRiLOGI is a Java application; theJava run-time environment (JRE)needed to run it is included in thesoftware package. Internet TRiLOGIis based on the client/server principle.Everything that TRiLOGI does,including accessing the T100MD888+,depends on running the TLServerapplication. TLServer acts as an HTMLweb server or Java applet with respectto Internet browsers like IE orNetscape. TLServer uses the PC serialport to connect to the T100MD888+and acts as the message path betweena PLC and the client. I’ve pulled outmost of the available functionality ofthe TLServer for you to see in Photo 2.

66 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

The client program is the applicationthat allows the ladder logic code to becreated and transferred to the server/PLC anyway you can get it there. TheTRiLOGI client runs as either a localJava application or a Java applet. TheJava applet allows a remote computerto access the PLC using only a Java-enabled web browser. The local appli-cation mode assumes that all of thenecessary TRiLOGI software resides onthe local PC. For instance, I have onePC running the TLServer and InternetTRiLOGI that is dedicated to theT100MD888+. The server-connectedT100MD888+ is attached to the serialport of the server PC. All of the othermachines in the lab can access thePLC via their web browsers.

Photo 3 shows a log-in screen point-ed at the PC running the TLServerfrom an arbitrary machine I had. AfterI’m logged in, the fun begins. Let’sstart by writing a simple LED flasherladder logic program and go throughthe steps of getting it from the editorscreen to the T100MD888+ EEPROM.

Like any other programming proj-ect, the first thing to do is get organ-ized and define all of the inputs, out-puts, and variables up front and thenwrite your code to them. Using theTRiLOGI system, the definitions arepredefined in the I/O table. You canalso define I/O table items on the fly,like I will probably have to do as Imove ahead with the project.

F2 or the Edit pull-down menu willget you to the I/O table. Let’s defineinput 1 as the normally open startcontact. Momentarily closing the startcontact (taking input 1 low) shouldenergize an internal relay, which I’llcall run. A contact of the run relaywill seal the start contact to keep itactive after the start input goes active.I’ll also define a normally closed stopcontact to demonstrate how to haltthe LED sequencing.

As for output definitions, I’ll defineLEDs one through four and assignthem in that order to the output pins.I want to flash them starting withLED one and ending with LED four,and then reverse the flash orderbeginning with LED four. For thatstrategy to pan out, I’ll need to define

Photo 7—It’s easy to put words on the LCD. With thelarger 4 × 20 format, you could hide the PLC and,using the LCD, present an eminence that portrays amore complicated and expensive embedded system.

Photo 6—The LCD is great for debugging becauseanalog values can be shown in real time. Using my lad-der logic-to-C comparison, using the LCD to print mes-sages at certain points of the logic program is akin tousing printf statements for debugging C code.

Photo 5—You probably wouldn’t want to be running a motor with this ladder logic program, but it works well for flashing the LEDs on the T100MD888+.

Page 69: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 67

SOURCESULN2003, ULN2803 ArraysAllegro MicroSystems, Inc. (508) 853-5000Fax: (508) 853-7861www.allegromicro.com

T100MD888+ PLCTriangle Research International, Inc.(877) 689-3245www.tri-plc.com

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

one of the counters as a sequencer. I’lldefine and use counter one as sequencerone in the I/O table.

A sequencer or counter needs aclock. A 1-s clock should do well here.The clock doesn’t have to be definedin the I/O table because I can selectthe clock source from the Special Bitspanel when I build my ladder logic.All of the I/O table entries I madeincluding the Special Bits panel areshown in Photo 4.

I put it all together using the sixcircuits shown in Photo 5. The idea isto get the voltage from the power lineat the far left through the contacts tothe coils at the opposite end. Closingthe normally open start contact at thebeginning of circuit one allows powerto flow through the normally closedstop contact and energize the runrelay. When the run relay is ener-gized, all of its normally open con-tacts close and vice versa. Therefore,the run contact in parallel with thestart contact is closed as long as therun relay is energized.

The run contact in circuit one sup-plies power to the run relay just as itwould in a physical hook-up, exceptthe run relay doesn’t physically exist.In circuit two, a second set of normal-ly open run contacts will close at theactivation of the run relay in circuitone. The run relay contacts of circuittwo supply power to your sequencercounter, which has a 50% duty cycleand a 1-s period.

The sequencer is edge-triggered. Ateach off-to-on transition of thesequencer one coil, Seq1:X, executesand closes the Seq1:X contact. Thenormally open Seq1:1 contact isclosed first and provides a power pathto output 1. Then, Seq1:2 closes for 1 sand so forth all the way throughSeq1:8. Because there is no Seq1:9, thesequencer goes inactive and opens allof its contacts until the next off-to-onclock transition. Seq1:X in Englishtranslates to sequence one, step x.

Taking the stop input contactactive opens the normally closed stopcontact, which removes the powerpath to the run relay. The run relayde-energizes and all of the run con-tacts that are normally open revert tothat state and vice versa.

And that’s just the beginning.TRiLOGI has the capability of mixingcode with the relay coils using theTBASIC language. The best way to showyou this is to modify the ladder logicprogram and add a custom function toprint the name of each LED as it acti-vates and tell you when they are all off.

The modified ladder logic is shownin Photo 6. I already anticipated thecustom function definitions, as thecustom function panel is shown inPhoto 4. In Photo 6, each customfunction is in parallel with the outputcoil it represents. Thus, the customfunction executes when its output coilis active. The contents of the customfunctions are given collectively inListing 1. I stopped the T100MD888+to get the LED message shot in Photo 7.

TOP OF THE LADDERUnlike my plumber friends, I’m on

the roof now and I intend to stay hereat least through one more articleperiod. There is still plenty ofT100MD888+ and Internet TRiLOGIstuff to talk about. And, I’ve got itfrom reliable sources that some trickynew TRiLOGI software may find itsway to the Florida room in time forPart 2. Until then, it’s pretty obviousto me that the engineering staff atTriangle Research Internationalbelieves that PLCs aren’t complicated,they’re embedded. I

Page 70: Circuit Cellar2002 03

68 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

y wife Beverlyand I often drive

differing routes to getto the same location.

This causes arguments on just whichroute is the quickest or shortest.When I’m driving alone, I might tryboth routes and compare the numberof stop signs, traffic lights, speed lim-its, total distance, and a number ofother secret ingredients to come upwith a clear winner. I don’t know ifshe’s guilty of this, I doubt it mattersmuch to her, but I find it a construc-tive exercise in time study.

Time studies are a great tool fordetermining the health of things. Theterm time study might bring to mind away to determine how close a job cameto the actual estimate. As previouslyillustrated, this doesn’t have to dealwith the work environment. It may notbe obvious, but much of this is builtinto today’s technologies. Your car mayprovide you with a running miles-per-gallon indication, which can indicateengine performance and help to deter-mine when a tune-up is necessary.

Data logging is an integral part of atime study. A data logger samples andstores data values in one of two modes,either periodically or on event. A peri-odic logger would sample and store

data at predefined and equal intervals.An event logger would sample dataonly on a specific occurrence of a trig-ger. There are differences in what mustbe logged for each of these modes.

PERIODICALLYPeriodic sampling must be used

whenever the data does not containevent (logic state) information. Analogdata doesn’t contain event informa-tion, unless you’re interested in zerocrossings or some other such signalconditioned output. Data samplesmust be taken at the Nyquist rate ofno less than twice the highest frequen-cy of the data. The highest data fre-quency is that which you are interest-ed in (providing all higher frequencydata has been properly filtered outprior to sampling). This is why it isextremely important that you knowwhat it is you’re interested in.Although the data logging of sensoroutputs is generally considered lowfrequency (below audio), you can cer-tainly see how this is applicable tohigher frequencies.

Because a periodic data logger sam-ples and stores data at defined intervals,you can calculate the time of each datapoint referenced to the start of data log-ging by multiplying the sample numberby the sample rate, so only data needsto be saved. However, because of theperiodic nature of this mode, loggingmemory is consumed at a steady rate.The upside to this is that only the actu-al data or change in data needs to bestored, no time stamp is necessary.

EVENT-DRIVENOften the data you’ll need to sample

and save will be logical (1-bit data).This might be the position of a door orwhether the temperature in a room isabove or below the thermostat’s setpoint. Sample time is unnecessary withevent data logging because the samplingtimes are not based on the maximumfrequency of the data. Instead samplingis based on the event of interest,which can occur at any point in time.

The drawback to event-driven sam-pling is that some kind of time refer-ence (time stamp) must be saved toindicate when the event occurred.This time stamp allows each sample

Spy-Size Event Logger

mWhen itcomes toperform-ing a timestudy or

logging events, themore information youcan gather, the better.Jeff set out to build asmall event logger totrack events duringthe off/on cycles ofhis water pump.

Jeff Bachiochi

FROM THE BENCH

Page 71: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 69

communication) to continue operatingas long as the attached battery remainsabove 2.6 VDC. Active current at 5 VDCis about 2 mA. When it’s running onbattery power, the current drops toabout 0.5 µA (about 4.5 mAh per year).

The 2000-compliant RTC is codedin BCD format down to seconds. Thehours are available in either standard12-hour (using a.m. and p.m.) or mili-tary format. Missing are the familiarI2C user-programmable address inputsA0–A2, which allows multiple devicesto be set to different addresses andcoexist on the same bus. Instead, tokeep the pin count low, it is assumedthere will be only one DS1678 (RTC)on the bus; as such, the device doesn’tneed the multiple address capabilitiesof other devices (i.e., serial EEPROM).The ’1678 is a registered device, whichmeans you must use the registeredread and write formats to access all ofthe data registers within the device.

to be accurately referenced to the startof data logging series. Although timestamp data will gobble up availablelogging memory at an increased rate,the rate between samples can beextremely long with the result ofactually using less memory.

Although a 1-bit A/D converter(comparator) is an example of a signalthat could be sampled and saved inEvent Driven mode, the additionaltime stamping overhead may make ita more reasonable candidate forPeriodic mode. Therefore, you’ll needto analyze data for each application todetermine the most effective modefrom both an accuracy and memoryavailability standpoint.

TINY DANCERDallas Semiconductor, now owned

by Maxim Integrated Circuits, is wellknown for its mixed-signal products.Dallas’s expertise includes excellencein time keeping and data logging justto mention two. It seems inevitablethat these would be combined into asingle device at some point, but an 8-pin real-time event recorder? Thisdeserves some attention.

The DS1678 contains all of the ele-ments (except for a battery) of a 1025event recorder. Note that it is anevent that causes a time stamp to besaved. No data is actually saved! Thedata itself is the event. The devicecommunicates using an I2C interface.The schematic in Figure 1 demon-strates how the DS1678 is used in thisproject (also see Photo 1.)

I2C FOR YOUR UARTI used to be able to do a few basic

auto repairs. Many of those now requirespecial tools. It’s unfair practice todesign in the requirement for a specialtool that ends up costing more than therepair itself. If you were concerned aboutthe same problem when I mentionedI2C, don’t worry, I won’t let you down.

Let’s take a short break from theDS1678 and develop an I2C interfacefor your serial port. I picked up one ofmy favorite micros, the PIC16F84,PicBasic Pro, and threw together aserial-to-I2C interface (see Figure 2).With PicBasic Pro I can configure asoftware UART with four user-selec-

table data rates in the ’F84. Ican even have programma-ble serial polarity to elimi-nate level shifters (thisinverted TTL interfaceworks fine with most serialports). Also in the PicBasicPro’s vocabulary is an I2Cinterface, which can bedefined on any I/O pins justlike the software UART.

The application handlesthe four basic I2C routines,read, write, and registered read andwrite. Asynchronous serial communi-cation (on one side) asks you whetherthe action will be writing or readingand whether the read or write is regis-tered. Your reply will direct the ques-tions toward collecting the device’saddress, register number (if necessary),and data. This mini project then createsan I2C communication (on the otherside) to communicate on its two-wire,open-collector I2C bus. A reply is gen-erated on the serial port and the cyclecan be repeated. With these basic rou-tines you should be able to communi-cate with any I2C device tied to its bus.

AND NOW, BACK TO THE SHOWAs a time-keeping reference, the

DS1678 requires a standard 32-kHzcrystal but no external crystal capaci-tors. Despite the fact that communi-cations requires a VCC of 5 VDC, VBAT

allows the whole enchilada (minus

Figure 2—This circuit allows a dumb terminal (or smart application) to access I2C devices via a serial connection.Note the use of a MAX680 to steal power from the serial port.

Figure 1—This is all that’s necessary for a working logger circuit. J4connects to the RS-232-to-I2C circuit.

Page 72: Circuit Cellar2002 03

70 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

Figure 3 shows that the registers aredivided into three main groups, theRTC, user, and event groups.

RTC GROUPThe RTC group is similar to many

other real-time clocks in which thedata is held in BCD format. The 2000-compliant century register correctlynotes the year 2000 as a leap year.Although we’re well past 2000, havingthe century available makes date han-dling safe for all of those programsthat had to translate a two-digit yearinto the correct century.

The most complicated configurationto understand is military versus stan-dard time. The upper-nibble BCD digitof the hour can never be greater than 2(00–23 in military time) and nevergreater than 1 (01–12 in standardtime). So bit 6 always can be used toindicate military time or standardtime. It indicates military time whenset and standard time when cleared.

When this bit is set, the hours willrollover after 23:59:59, as opposed tostandard time, which rolls over after11:59:59. If bit 6 is cleared (standardtime), then bit 5 is available to indicatea.m. or p.m. When bit 6 is cleared, bit 5indicates p.m. when set and a.m. whencleared. Remember that most RTCswill not validate the data you write aslegal, so it’s possible to set an illegalmode/time such as 20:00:00 standardtime (which is 10 p.m., not the equiv-alent standard time of 8 p.m.).

Just above the RTC data registers00–07 are the RTC alarm registers. Analarm can be generated whenever a

match occurs on all registers withtheir alarm bit (bit 7) cleared. If regis-ters 08–11 have bit 7 cleared, then analarm will be generated every week ona match of the seconds registers (00and 08), minutes registers (01 and 09),hours registers (02 and 10), and DOWregisters (03 and 11).

When bit 7 of any alarm registers08–11 is set, the action specifies a“don’t care” condition for that regis-ter. This means that you can get analarm state once a week, once a day,once an hour, once a minute, or oncea second (if all four registers have thealarm bit 7 set). When in Alarm mode,the INT pin is configured as an outputand will go low until reset or whenyou access any of the alarm registers.

Configuration and status registerscomplete the RTC group. The controlregisters configure the DS1678’s mode.Figure 4 and Table 1 provide the oper-ating modes and status of the DS1678.

USER GROUPThe next group of registers contains

user registers. This is a group of 32 user-programmable NV memory bytes. Youmay wish to save some kind of textmessage or data here, like a copyrightnotice or serial number. The DS1678doesn’t use nor will it destroy any datayou place in these registers (16–47) butit is battery-backed and will disappearwhen the VCC and VBAT are removed.

EVENT GROUPThis last group is the working regis-

ters for the Event Logging mode of theDS1678. The first eight registers get

Bit Bit name Function

7 – Not used6 MEM CLR Memory cleared; a one indicates the memory has been cleared5 MIP Mission in progress; can be set if memory is cleared to immediately

begin data logging. Otherwise it reflects the status of the logging process. Clearing this bit ends the logging mission.

4 CM Clears memory; can be set following setting of the CLR bit in the control register, to clear the event log memory, event count, and start time stampregisters.

3 LOBAT Low battery flag; a one indicates a low VBAT

2 ROF Rollover flag; set when more than 1024 events have occurred1 – Not used0 ALMF Alarm flag; a one indicates the existence of an alarm match. The bit is

reset on any alarm register access.

Table 1—Status bits reflect the state of the D1678. Interaction between this status register and the control register(see Figure 4) protects the device from unintentional operations.

Data RecorderTM

Introducing...

Data Collection Specialists

WWW.NAVMASTERS.COM 3440 Youngfield St. #269, Wheat Ridge, CO, 80033, 303-467-1718

Go Anywhere, Record Anything, Works Every Time

FEATURES: >5 year power source, 2-256MB capacity DOS removable media, Flexible I/O (2-Serial, 7-Digital, 3-12 bit

Analog, 2-Capture, 2-PWM), Temp, RTC, JTAG, 2.2”x2.4”x1”

This truly unique device will find more uses than you can imagine. Built on the TI MSP430-149 processor,

the Bit Vault Data Recorder has it all. Ultra long battery life, ultra large storage capacity, and the speed and internal resources to tackle the most

demanding jobs. Used off-the-shelf or programmed to your specifications, the Bit Vault will find a promi-

nent location in your development or production arsenal. Customization available on request or DIY.

Page 74: Circuit Cellar2002 03

72 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

Address Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Function

00 0 10 s (0–5) Seconds (0–9)

01 0 10 min. (0–5) Minutes (0–9)

0 = AM

02 0 1 = PM Hours (0–9)

1 = 24 10 h (0–2)

03 0 0 0 0 0 DOW (1–7)

04 0 0 10 Days (0–3) Days (0–9)

10 05 0 0 0 Months Months (0–9) (0–1)

06 10 Years (0–9) Years (0–9)

07 10 Centuries (0–9) Centuries (0–9)

08 MS 10 s (0–5) Seconds (0–9)

09 MM 10 min. (0–5) Minutes (0–9)

0 = AM

0A MH 1 = PM Hours (0–9)

1 = 24 10 h (0–2)

0B MD 0 0 0 0 DOW (0–7)

0C

0D

0E ME CLR DIS1 DIS0 RO TR1 TR0 COE Control

MEM LO CLR BAT

10 Byte 1

11 Byte 2

... ...

2E Byte 31

2F Byte 32

30 0 10 s (0–5) Seconds (0–9)

31 0 10 min. (0–5) Minutes (0–9)

0 = 12 0 = AM

32 0 1 = PM Hours (0–9)

10 h (0–2)

33 0 0 0 0 0 DOW (1–7)

34 0 0 10 Days (0–3) Days (0–9)

10 Months (0–1)

36 10 Years (0–9) Years (0–9)

37 10 Centuries (0–9) Centuries (0–9)

38 Event 0 elapsed time from last event counter LSB

39 Event 0 elapsed time from last event counter MSB

3A LSB

3B NSB Event count

3C MSB

3D LSB

3E MSB

3F LSB Address

40 MSB Address

41 LSB Address

42 MSB Address

43 Data byte

44 (Reads 00)

45 (Reads 00)

... (Reads 00)

FF (Reads 00)

0 = 12

0 = 12

10 h(0–1)

10 h(0–1)

10 h(0–1)

(Reads 00) Reserved

RTC alarm

0F 0 MIP CM

User NVmemory

1 = 24

35 0 0 0 Months (0–9)

Reserved

Address pointer

Elapsed timecounter

ROF 0 ALMF Status

Time stamp

Data logRAM port

RTC

Figure 3—Registers within the DS1678 allow for RTC, alarm, and data logging configurations.

Page 75: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 73

sion began. Ordinarily this registerwould increment to 1024 and the loggerwould be full of data. However, youhave no real idea when this might occur,so even if you’ve configured the loggingto stop at 1024 events (the maximum),the DS1678 can continue countingevents even if it can no longer log them.

So far I haven’t discussed the log-ging memory, in fact, you may havenoticed it isn’t shown in any of theprevious figures. That’s because youdon’t have direct access to the loggingmemory. You can’t write to it, only

written following the first event of themission (logging session). They are acopy (time stamp) of the RTC registersreflecting the exact time of the mis-sion’s first event. The time each eventoccurs is based on this start time.Time between events (the logged data)is the elapsed time from the lastevent. Logged data consists of a two-byte elapsed time count. Each count isequal to the configuration set in thecontrol register (bits 4 and 5, seeFigure 4). This makes a minimumcount of one equal to 1 s, 1 min., or 1 h.

Naturally you want to pick the reso-lution that best fits your minimumtime between events. Events will belogged even if they occur at a rate quick-er than the chosen resolution. Thiswould be data logged with an elapsedtime count of zero. For instance, if youchose hour increments of the elapsedtime counter and events happened every15 min., you might see three logs of zeroelapsed time counts and one log withone count. Independent of logging, whichconsists of saving and clearing theelapsed time counter (ETC), the RTC isin charge of incrementing the ETC on atime match determined by the durationinterval bits in the control register.

On the other hand, you must also payattention to maximum times, which are65,535 times the resolution. Thereforethe maximum ETC for the second’sduration interval is 65,535 s, or 18.2 h.If your event happens once per day, theelapsed time count will overflow (androll over to zero). So again you can seethe importance of choosing a resolu-tion that fits both your minimum andmaximum times among events.

Following the time stamp registers(48–55) is the event zero elapsed timefrom last event counter 2-byte register(56–57). At the beginning of the mis-sion, this register pair is written withzeros. This designates the first eventand the start of a mission. If the RO bitis set (allowing rollovers), this registerpair will hold an elapsed time countsince the last event (event 1024) afterthe rollover has occurred. (This is oneway of determining a rollover. But, asindicated, an ETC of zero is possible.)

The next three registers (58–60) holda 3-byte count of the number of eventsthat have been logged since the mis-

the event logger can. This preventsdata tampering. Any attempt to accessthe data halts the mission and locksin the data. After it’s been halted, theonly way to begin a mission is to clearthe memory and start from scratch.

Following the ETC register pair is anaddress register pair. This register pair(63–64) points to the next logging mem-ory address or the location where theETC will be stored on the next event.Initially it will point to address zero(2047 being the last logging memoryaddress prior to rollover). The 2-byteETC count will be stored at the point-er at the next event and the pointerwill be incremented (two consecutivebytes for each 2-byte ETC value).When RO equals one and a rolloveroccurs, not only is the ETC stored inregister pair 56–57, which was zero,but a new RTC sample is stored in thetime stamp registers (48–55). Eventswill continually be logged, overwritingthe oldest data with new.

Even though you are prevented fromwriting to the logging memory, theremust be a way to retrieve the logged

Photo 1—The DS1678 circuit with a battery (upperright) fits into the 1″ × 2″ plastic shell for a spy-sizedevent logger. The RS-232-to-I2C circuit is on the left.

Page 76: Circuit Cellar2002 03

74 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

data. The last three registers (65–68)hold the key. The first two registersare an address pointer pair enablingthe user to read the logging memory.The last register will hold the datapointed to by the first two address reg-isters. The address pointer will auto-matically increment for multiplereads to the data register (43), so youcan skip having to continually writethe address to read multiple databytes. When you’re pointing to theaddress of interest, you can read asmany multiple bytes as you wish.Note multiple byte reads are not sup-ported in the simple serial-to-I2C con-verter in this project, so you’ll have toupdate the address for each read.

MISSION POSSIBLEYou’re going set this module up to

log movement through a doorway.This is an “enter only” doorway, soyou’ll log traffic in one direction only.A reflective IR device presentlymounted in the doorframe has relaycontacts that close whenever its beamis broken. The contacts are easilywired to produce a gated 5-VDC pulse,which you can connect to the INTevent input pin of the ’1678.

Before I get into this short example,there is one other small matter. Youbuilt a serial-to-I2C converter to beable to talk to any I2C device. It wouldbe nice to have an application thatmade talking to this specific device abit easier. I wrote this application inGWBASIC to talk to the converterusing a COM port (I still find manyuses for Microsoft’s DOS Basic). Theapplication has three functions, read,write, and dump. This application ismenu-driven and allows reading fromand writing to DS1678 registers. Unlikeusing, say, HyperTerminal, this pro-gram provides a smart front end, whichdisplays information about the registersand not just the values that are storedthere. You don’t have to think aboutwhat value to store in which register,you just choose menu selections, whichwill be interpreted into (hopefully) thecorrect register and value data. Thedump retrieves the log memory andcreates a data file containing the val-ues for use in a spreadsheet.

To set up the registers properly for amission, you must follow these steps.First, display the RTC registers (0–7)and change the present date and timeif necessary. For this project, you are

Name Function

Mission Enable; if MEM CLR = 1, then a one written to this bit will ready the data logger to begin the next event (INT change).

Clear Enable; writing a one to this bit allows the event log memory, event count, and start time stamp registers to be cleared if the next action is a write of one to the CM bit of the status register.

7 ME

6 CLR

5 DIS1

4 DIS0

3 RO

2 TR1

1 TR0

0 COE

Durationintervalselect

Bit 5 Bit 4

Bit 2 Bit 1 Edge(s) used to trigger event

1 1

1 1 Both rising and falling edges

1 0 Rising edges

0 1 Falling edges

0 0 Nothing (illegal state)

1 0

0 1

0 0

Elapsed time count to increment every...

Hour (maximum count = 7.5 years)

Minute (maximumcount = 45.5 days)

Second (maximumcount = 18.2 h)

Alarm Output mode

Alarm Output mode

Rollover; if set, data logging is allowed to rollover (overwrite previously loggeddata) after 1024 events. If cleared, data logging is stopped after the memory isfilled (1024 events).

Triggerselect

Clock Oscillator Enable; the oscillator is stopped when this bit is cleared (PowerSaving mode and all functions cease). Automatically enabled when VCC > VBAT.

Bit

Figure 4—Configuration bits establish the operating mode of the DS1678.

www.circuitcellar.com

Now all of the greateditorial, advertising, and

information you get inCircuit Cellar is available in

a digital format eachmonth. With the ElectronicEdition of Circuit Cellar, the

latest issue is availableworldwide in a

matter of minutes.

So, whether you’re aninternational subscriber

who wants to avoidshipping delays, or you

just prefer pixels to paperwhen it comes to reading

material, go to www.circuitcellar.com tofind out more about the

Electronic Edition of Circuit Cellar.

Only $15

NO MATTER WHERE YOUARE, WE‘RE ALWAYS AT

YOUR FINGERTIPS.

Page 77: Circuit Cellar2002 03

not using the alarm, so these registersdo not need to be set. Next, display thecontrol register and toggle the triggerand duration interval selections tochoose the appropriate event-trigger-ing edge and count increment time. Iuse falling edge triggering and 1-s countincrements. I also clear RO to preventa rollover should I get more than1024 events before I stop the mission.

To clear the memory I need to setthe CLR bit. When this bit is set, theapplication immediately stores thecontrol register and asks if you wishto also set the CM bit (in the statusregister). You must set this bit imme-diately after setting the CLR bit, oth-erwise the CLR bit is cleared and youcannot clear memory without repeat-ing the process. This is a securitymeasure implemented within theDS1678 to prevent unintentional era-sure of data. Displaying the statuswill now show “MEM CLR set,”meaning the CLR bit is not clearedagain as the process has taken place.Only with the memory cleared canyou start a mission.

There are two ways to begin a mis-sion. If the MIP bit is set (with memo-ry cleared) a mission begins immedi-ately (as if there was an event). If theME bit is set, the mission waits for anevent to start the mission. At thispoint, the DS1678 module is ready tobe connected to the event source. Theevent must present at least 2.2-Vinput to look like a logic-zero-to-logic-one transition.

When the logging mission is fin-ished, you can remove the data logger’sevent source and reconnect the logger

to the serial-to-I2C converter. Now youcan run the BASIC application programand interrogate the logger. Changingany register will halt the mission. Notonly does this discourage tampering,but also the device is immediatelyready to give up its logged data.

One of the user selections of theBASIC application program is to dumpthe logged data. This not only goes tothe screen, but also to a .TXT file in“event number elapsed count sincelast event” format. To make sense ofthis you must also know two things,the RTC values at mission start (timestamp in registers 48–55) and the dura-tion interval (from control register 15).

To find the time of the first event,take the duration interval (1 s, 1 min.,or 1 h) and multiple it by the “elapsedcount since last event.” Obviously,this gives the time passed since thelast event. Add this to the time stampof the previous event to get the actualtime the event occurred. I importedthe .TXT file into Microsoft Accessand was able to produce a plot thatshows a timeline of event occurrencesas shown in Figure 5.

MAKE AN APPOINTMENTLogging capabilities aside, the device

can be programmed to trigger the INTpin every second or upon a secondsmatch, a seconds/minutes match, aseconds/minutes/hours match, or aseconds/minutes/hours/day-of-the-week (DOW) match. Accessing anyalarm register resets the alarm output.This mode allows your circuit to sleepfor up to a week at a time. That’squite the low-current alarm!

I find this device extremely flexibleand offer kudos to Dallas and Maxim.You can count on them to produceunique devices covering a wide rangeof applications. There are a couple ofother new logging devices you maywish to research at the companies’web sites, namely, the DS1615 andDS1616. Internal temperature sensorsand ADC additions may satisfy morecomplex requirements.

In any event, I’ll be taking this proj-ect over to my well’s water pump togive me an indication of pump cycletimes over the course of a week. I canuse Trigger on Rising and Falling Edgesmode to capture the on and off cyclesof the pump. Note that the logger doesnot log on or off status, but I’ll be ableto determine which is which becausean event will occur at each transitionbetween on and off. Additionally, the offtimes should be considerably longerthan the on times, especially duringnighttime hours. I wonder if I can mon-itor the gas pedal in my car to trulydetermine the best driving route? I

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 75

SOURCESDS1678 Real-time event recorderMaxim Integrated Products(408) 737-7600Fax: (408) 737-7194www.maxim-ic.com

PIC16F84 MicrocontrollerMicrochip Technology Inc.(480) 786-7200Fax: (480) 899-9210www.microchip.com

PicBasic Pro compilermicroEngineering Labs, Inc.(719) 520-5323Fax: (719) 520-1867microengineeringlabs.com

SOFTWARETo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2002/140/.

Mission log

11/28/01 0:00

11/28/01 4:00

11/28/01 8:00

11/28/01 12:00

11/28/01 16:00

11/28/01 20:00

11/28/01 0:00

11/28/01 4:00

11/28/01 8:00

11/28/01 12:00

Date/time

Figure 5—The Microsoft Access plot of logged data shows the majority of the activity taking place from 8 a.m. to 5 p.m. The overnight hours do not reflect any activity.

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 03

t was just abouttwo years ago when

I first covered the Tri-scend TE505 (“SoC Hop”

Circuit Cellar 116). Now, it’s time totake another look and see how thepromise of this intriguing device is pan-ning out. I imagine most Circuit Cellarreaders are up to speed on the conceptbehind the part, even if they haven’tyet had a chance to design with one.

For the few people who need tocatch up, the idea is simple. Combinean MCU and FPGA in a single chip,season well with some fancy tools, anddish up a System-on-a-Chip (SoC) forthe masses. Have it your way but with-out the muss and fuss, not to mentionup-front sticker shock, of an ASIC.

This sounds good, but the devil is inthe details—price, performance, ease ofuse, and so on. Furthermore, chips thatuse a hard-core controller (from Tri-scend, Atmel’s FPSLIC, or the CypressPSoC) must square off against equallyinnovative soft-core SoCs. Both face adaunting competitor in the 1000-lbgorilla represented by traditional MCUs,and so far, it’s hard to argue any ofthese SoCs are more than niche players.

However, I still think the future isbright. After all, every chip is a nichepart until a manufacturer starts selling

a zillion of it. I can well remember atime when folks said other now main-stream technologies, notably includingPLDs and FPGAs, were also doomedto meet an also-ran fate. There’s noth-ing like millions of chips and billionsof dollars to silence a skeptic.

Right now, with the arrival of a boxof the latest goodies from Triscend, I’vegot a sudden urge to get under the hood.

NEW AND IMPROVEDSince I first wrote about Triscend,

the company has been busy rollingout new versions of the E5 withmore memory and logic. They’ve alsomade some 32-bit moves with therecent introduction of an ARM-basedCSoC as well as announced plans foran SH-based version.

Less obvious perhaps but equallyimportant, Triscend has beefed up theFastChip tool chain, a critical piece ofthe puzzle that turns an MCU and abunch of gates into something useful.Judging by the splash screen, FastChipstill presents the friendly drop-and-draginterface that makes building a chip asfun as playing with Legos (see Photo 1).

The process starts by configuringthe dedicated resources (i.e., hardwiredfunctions built into the MCU such astimers, UARTs, etc.). Instead of plow-ing through a datasheet to figure outwhat bits to twiddle, it’s simply amatter of filling out a form, andFastChip generates the initializationcode automatically.

Turning to the programmable logicportion of the chip (a.k.a., configurablesystem logic, or CSL for short), prede-fined functions can be drawn from alibrary provided with FastChip. Aswith the dedicated resources, you sim-ply fill out a form defining specificparameters of the function andFastChip does the rest.

When all of the chip logic (i.e., dedi-cated resource setup and CSL net list)is in hand, it’s time to bind the twotogether into a full-fledged configura-tion. Make that plenty of time,because even a speedy PC takes quitea while (we’re talking coffee breakhere) to crunch the gates.

Not surprisingly, the first of manyFastChip user interface enhancementsI noticed was the addition of a progress

76 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

Tom Cantrell

SoC Hop

i

SILICONUPDATE

WhenTom tooka firstlook atthe TE505

from Triscend, heliked what he saw.Now, he’s followingup to let us know howthings have comealong and what wecan expect fromTriscend in the future.

The Sequel

Page 79: Circuit Cellar2002 03

Much of what’s differentabout the latest version ofFastChip (V.2.3) is hiddenunder seemingly innocuousmenu entries for importingand exporting. These pro-vide the vital links to pop-ular third-party hardwaredesign tools. Basically, youcan import a module fromanything that can generatean EDIF net list—the linguafranca for hardware people.In turn, you can export EDIFor even a high-level descrip-tion (Verilog or VHDL) ofyour design to a simulationor synthesis tool.

Similarly, links have beenembellished between Fast-

Chip and software development tools,such as the evaluation version of theKeil tool chain that I received. In thefirst versions of FastChip you were pret-ty much limited to using Triscend’sminimal debugger with little more thanstop, go, and a couple of physicaladdress break points. Now, thanks tocoordination with a Triscend-specificdebug driver, you can use the moresophisticated source-level debug capabil-ity of the Keil tools and needn’t switchback and forth for every debug cycle.

I confess to having neither the meansnor the will to fully test and evaluatethese integration features. Needless tosay, juggling multiple complex toolchains isn’t trivial and I suspect theeffort will be ongoing. Still, it’s fair tosay the latest version of FastChip goes along way toward deflating the objec-tions of chip design guys who wouldrather view things from a hardware per-spective. However, for the long term, Iwonder if hardware-centric designerswon’t gravitate toward soft-core parts(like NIOS and Microblaze) and ASICstalwarts like ARM or ARC. Meanwhile,those of you who are coming from anMCU orientation will still find it mucheasier simply to cut and paste usingFastChip rather than bring a complicat-ed chip design tool chain into the mix.

BOUNTIFUL LIBRARYSpeaking of a big library, the selec-

tion of peripheral modules continuesto grow with dozens of handy func-

bar for the bind process. Lasttime, asking for trouble byrunning FastChip on a PCwoefully short of RAM, Icomplained when it seeminglywent away for lunch during abind with a thrashing disk asthe only sign of activity.

The good news is that myPC now has 128 MB, twicethe RAM it did then. The badnews is that the latest versionof FastChip now prefers awhopping 256 MB. Neverthe-less, I was able to get throughthe tutorials and demos with128 MB, and FastChip did agood job of keeping me postedon its progress.

And, I have one moredetail for you. You do need softwareto drive the ’51. Combine your appli-cation-specific code with the variousdrivers generated by FastChip andmush it all into a .hex file. Combinethat with the .csl file and you endup with a configuration (.cfg) file.Download the .cfg file into the chipand you’re off to the races.

THE HARD WAYAn interesting challenge the SoC-for-

the-masses suppliers must deal withis a dual customer base. One group ofcustomers comes from an MCU-cen-

tric point of view. Members of thisgroup need not be accomplished hard-ware designers and are likely mostinterested in simply cutting and past-ing a chip from the Triscend library.

On the other hand, there’s anothergroup of customers for which the gates,not the MCU, come first. To these peo-ple, the chip is an FPGA that just hap-pens to have an MCU stuck in the cor-ner for housekeeping. Furthermore, asaccomplished hardware designers, it’slikely they already have a favorite chipdesign methodology (e.g., schematic orHDL) and a set of tools in place.

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 77

Listing 1—The LCD demo program, written in (Keil’s) C, takes advantage of high-level graphics functionssuch as line, circle, and rectangle (which produced the display in Photo 2).

void demo_rectangles(void)

char msg[] = "void paintRect (x,y,w,h,outline,fill)";int i;U16 x, y;e5hal_graphics_setFontColors(foreground, background);e5hal_graphics_writeString(msg, 8, 8);

for (i = 0; i < 320; i++) x = rand() % screenWidth;y = rand() % screenHeight + 30;if (PANEL_BITS_PER_PIXEL==1)

e5hal_graphics_paintRect( x, y, rand()/(256*4)+5,rand()/(256*4)+5,foreground, y&0x01 );

elsee5hal_graphics_paintRect( x, y, rand()/(256*4)+5,

rand()/(256*4)+5,x, y&0x01 );

R G BR G BR G B

Configurablesystem logic

Converter(4 to 8 bits)

Color palette

Clockgenerator

Controlsignal

generator

Passive colorgeneration

(3 to 12 bits)

CPU(8051 or ARM7)

FIFO

Imagebuffer

MIU DMA

InternalSRAM

Imagebuffer

Externalmemory

Command register

Status register

R G B

QVGA LCD

Figure 1—The newly introduced graphics LCD interface takes advantage of thebuilt-in DMAC of the ’51 core to handle the high-bandwidth burden of refreshing thescreen with minimal CPU intervention.

Page 80: Circuit Cellar2002 03

78 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

BITMAP BONANZAThere’s nothing I like better than

experimenting with the latest andgreatest, so I jumped at the chance torevisit the CSoC and check out therecently introduced graphics LCDperipheral module and kit fromTriscend. The interface is designed towork with so-called Quarter VGA(QVGA) LCDs, bitmap monochrome, orcolor panels with 240 × 320 resolution.It’s like an interface in a PDA, and it’s amajor step up from alphanumeric LCDstypically associated with 8-bit MCUs.

It isn’t that 8-bit applications wouldnot prefer to spiff up their displaycapability, but the price of the fancierLCDs and the complexity of theirinterfaces have been problematic.Now, however, thanks to volume pro-duction and a buyer’s market, QVGALCDs are more affordable than ever.

I headed over to the Earth ComputerTechnology web site (www.earthlcd.com) and found a number of seeming-ly suitable panels for prices rangingfrom $39 to $59. When you find a pas-sive (not active matrix), single-scanpanel, you’re in business. That leavesonly the interface as a roadblock todesigning in an embedded application.Plain alphanumeric LCDs have a sim-ple, if somewhat cryptic, hardwareinterface that any 8-bit MCU with afew spare I/O lines can handle. Thecontroller built into the alphanumericLCD module handles all of the messydetails, making life easy for the MCU.

By contrast, the bitmap LCDs arelike a CRT, so they’re much moredemanding of the host MCU. The mostannoying chore is that the MCU has tohandle refreshing the LCD. Refreshingentails repeatedly streaming the imagedata to the panel while meeting fastand tight timing constraints.

Anyone who’s dealt with CRTs andvideo knows the bandwidth demands

tions on the shelf. To calibrate,members of the E5 family comewith roughly 200 to 2000 CSLlogic cells, each roughly equiv-alent to perhaps 20 ASIC gates.

Available on the CircuitCellar web site, I’ve provided alist that serves to highlight aneasily overlooked advantage forCSoCs that helps close the gapamong standard MCUs. Yes, for agiven level of collection of functions,the latter uses transistors much moreefficiently than the former. That’s thepoint. With a standard MCU, thenumber, type, and specific capabilitiesof the peripheral functions are givens.Notably, the functions tend to be full-featured in order to serve the broadestbase of customers. By contrast, with aCSoC, you give the chip it’s marchingorders and tell it exactly what baggageto pack, no more and no less.

As the library catalog shows, thereare big savings to be had with formfit-ting functions. If you just need a fixed-speed transmitter half-UART withoutall the bells and whistles, it uses onlyone tenth of the logic of a traditionalfully loaded version. Why waste tran-sistors on a 16-bit timer with a plethoraof options when you need only 12 bitsdedicated to a specific cause?

The same goes for memory and FIFOsize. If you need to store some 12-bittimer readings, why make do withtypical MCUs, 8- or 16-bit width? WithFastChip, the width is variable from1 to 32 bits in single bit increments.

Fine-tuning to meet your require-ments is one way the CSoC closes theefficiency gap with standard parts.However, it’s fair to say that that abilityalone isn’t a compelling advantage overtypical MCUs. A programmable logicversion of a typical chip will never becompetitive with the real thing.

The real advantage for CSoCsbecomes obvious when you start throw-ing in more specialized functions. I canchoose from hundreds of MCUs with aUART, timer, and all, which are all finesolutions if they can handle the taskat hand. But, what about features likeHDLC, DES encryption, or a graphicsLCD interface? What if you need allthree? The list of standard MCU alter-natives all of a sudden gets really short.

add up fast. For instance, aQVGA 256-color (8-bit pixel)LCD refreshed at 75 Hz (fastrefresh reduces flicker) calls for5 MBps-plus. Even cuttingdown to only eight colors (3-bitpixels) calls for 2 MBps.Remember, that’s just forrefreshing the screen. There’soften more to do than that.

For instance, many designs boostthe number of colors (or turn a black-and-white panel into gray scale) bytime multiplexing the data over mul-tiple frames. For example, a black-and-white panel could display multi-ple shades of gray by adjusting theduty cycle of a pixel across fourframes (e.g., 0000 = white, 1000 =light gray, 0101 = gray, 1101 = darkgray, and 1111 = black).

After reaching the point when youcan put something on the screen, youstill have to come up with program-mer-friendly routines to draw figuresand handle bitmapped text.

A GRAPHIC EXAMPLEAs shown in Photo 2, my entire

lash-up is comprised of the EVAL520evaluation board ($298) plugged intothe I/O expansion baseboard ($698). Inturn, the LCD interface board ($198)plugs into one of the three I/O proto-typing expansion slots on the base-board. Note that the LCD panel, inmy case a Kyocera color unit, is notincluded. You pay $1200 for the con-venience of a plug and go solution.

For those of you with more time anda smaller budget, I’ll speculate on somecost-saving alternatives. The mostobvious solution is to bag the base-board. Although it’s handy, for thepurpose of this assignment it’s actingas little more than a $698 connectorbetween the EVAL520 and LCD inter-face boards. It wouldn’t be too diffi-cult to fabricate a connection betweenthe two boards for the dozen or so sig-nals required. But, the EVAL520 boardhas only flash memory, so you’d likelywant to graft on an SRAM chip.

More aggressive home brewers mayconsider axing the LCD board. Becausethe ’E5 chip is doing most of the work,the LCD board consists of little morethan a couple of buffers/level shifters

1 2 3 4 5 6 7 8 9 A B C D E FFrame counter value

Color output with framecounter not inverted

Color output with framecounter inverted

Figure 2—Getting 16 colors out of a 3-bit RGB panel is accomplished bycomparing the pixel value (in this example, 0x8) to a frame counter.Swapping the bits (MSB becomes LSB and vice versa) of the frame counterbefore the comparison spreads the high and low time evenly to reduce flicker.

Page 81: Circuit Cellar2002 03

www.circuitcellar.com CIRCUIT CELLAR® Issue 140 March 2002 79

As I said, the passive color generatormaps the 12-bit bit color onto the 3-bit(RGB) panel by varying the duty cycleof each bit across 15 frames. There’s aseparate 4-bit frame counter for R, G,and B that’s compared to the correspon-ding portion of the 12-bit pixel to deter-mine the duty cycle. The output of the

(’244s), a panel bias voltagegenerator (14 to 30 V typical-ly), and three relays. Therelays properly sequence thevarious supplies (3.3 V, 5 V,and panel bias) at powerup.One nice feature of the boardis that it includes five differ-ent vendor/panel-specificconnectors, which is definite-ly a convenience especially ifyou plan to try different pan-els or aren’t sure which oneyou’ll end up using.

As a final option to cutcosts, you might considerthe bargain-basement alter-native from XESS. TheXSTE5 board is only $170and is eminently hack-wor-thy thanks to its form factor that canbe breadboarded (pins are on 0.1″ cen-ters). It has a lesser version of the ’E5than the Triscend board (’505 versus’520), but still incorporates enoughCSL logic to handle the LCD con-troller. Additionally, it includes 128 KBof SRAM and 128 KB of flash memory,which I suspect is enough to get offthe starting line.

DMA TO THE RESCUEThe LCD interface relies on the

built-in DMA controller of the ’E5 todo the heavy lifting (see Figure 1). DMAis a relative luxury for 8-bit MCUs, butcomes in handy in an application likethis, completely off-loading the band-width burden of refreshing the screen.

In essence, you simply access a framebuffer stored in external SRAM atwill, with no concern over the detailsand timing of how the data gets fromthere to the screen. As necessary, theDMA controller will sneak in andgrab data from the frame buffer tokeep the pixel FIFO filled.

The LCD interface accommodates16- or 256-color (4- or 8-bit pixel data)applications. For the former, the outputof the byte-wide FIFO passes througha converter block that translates a sin-gle byte from the FIFO into two 4-bitoutputs. Subsequently, the color paletteboosts the number of bits per pixel to12, allowing the 16 or 256 colors thatcan be simultaneously displayed to bechosen from a selection of 4096.

frame counter is swappedbefore comparison to spreadthe high time evenly over theperiod (see Figure 2) and thecounters are run out of phaseto reduce flicker. Finally, out-put registers group multiple 3-bit pixels into 12- or 24-bitblocks for transfer in threeclock cycles over a 4- or 8-bitLCD data bus, respectively.

SOFT MACHINEAfter plugging in everything,

I started wading through the“Graphic LCD ControllerSolution Development KitTutorial.” The tutorial is amust for Triscend newbies as itaptly demonstrates the overall

process of getting a project going fromdouble-clicking the FastChip icon todownloading your design.

Things went well as I defined theCSL logic for the design. There are afew bits to control the LCD boardpower sequencing, but the real fun ispointing and clicking the particular

Photo 1—FastChip is the closest thing to a desktop foundry that lets anyone,not just the big boys, roll their own chips.

Page 82: Circuit Cellar2002 03

80 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

sets the bias voltage according to yourparticular panel specifications. TheTriscend document stated that myKyocera panel called for 30 V.

Rechecking the voltage with myadmittedly cheap (5% accuracy) VOM,it looked like I was a couple of voltsshy. After I tweaked up the poten-tiometer a tad, sure enough, thescreen instantly became clear. Thecontrast continued to improve as Iturned the voltage up to about 31 V.Subsequently, I tracked down aKyocera specification and, of course,the bias voltage specifications are atight 29.1 to 31.1 V at room tempera-ture. I must admit I wouldn’t haveguessed 2 to 3 V would make such anight-and-day difference, so checkyour panel voltage carefully.

The tutorial code includes a decentgraphics API, with functions like line,circle, rectangle, paint, and text. Thatmakes for easy programming, asdemonstrated in the code fragment(see Listing 1) taken from the demo.

READY OR NOTWe’ve been running a reader survey

on the Circuit Cellar web site, and I’dpersonally like to thank all of youwho took the time to respond. Fromtime to time, it’s helpful to do a reali-ty check and make sure we knowwhat you’re interested in.

I’m not surprised that the good-old8-bit MCU remains the perennialleader as the single most often speci-fied component. It’s been, and will nodoubt continue to be, the the most

popular chip of the silicon age.The interesting question is

how quickly and to what degree8-bit SoC chips, such as thosefrom Triscend, Atmel, andCypress, will be able to leverageoff the popularity of their stan-dard MCU counterparts.

Triscend’s web site says theyjust captured their three-hun-dredth design win. That’s a farcry from the thousands of designsfor a standard MCU, but nothingto sneeze at. It means the SoCconcept is here to stay.

The degree of success for SoCsis largely in suppliers’ hands byvirtue of the price they set.

specifications for the LCD interface(see Photo 3). As you can see, theentire graphics module consumes onlya small fraction of the resources avail-able on the top-end ’E520 chip.

Next, I turned to the software portionof the tutorial, a step-by-step guide usingthe Keil tools. However, here I ran into asevere problem, namely that the evalua-tion version of the Keil software imposesa 2-KB code size limit, which is far toosmall to handle this project. Fortunatelythere was an out. I fell back to theaptly named, and at this point indispen-sable, section of the manual titled“Instant Gratification.” Thankfully,Triscend provides ready-to-download.cfg files for a variety of panels.

At first, I couldn’t even download,but that turned out to be a simplematter of getting a copy of some late-breaking documentation for the boardand fiddling with some jumpers.Finally, FastChip happily reported asuccessful download and I hit the Gobutton. But nothing happened, nada.

I checked the obvious possible cul-prits, including the delicate connec-tion with the fine-pitch LCD flexcable, which seemed OK. Whippingout the logic probe, I probed here andthere and convinced myself that the’E5 was actually trying to talk to thepanel judging by all the activity on theLCD control and data lines.

It was about that time when I thoughtI noticed some shadowy ghosts on theotherwise murky screen. One of thefirst steps in the tutorial is to adjust apotentiometer on the LCD board that

SOURCESQVGA LCDsEarth Computer Technologies, Inc.(949) 248-2333Fax: (949) 248-2392www.earthlcd.com

CSoC MicrocontrollersTriscend Corp.(650) 968-8668Fax: (650) 934-9393www.triscend.com

XSTE5 BoardXESS Corp.Fax: (919) 387-1302www.xess.com

Tom Cantrell has been working onchip, board, and systems design andmarketing for several years. You mayreach him by e-mail at [email protected].

Originally, some had the idea thesechips would be useful only for nicheapplications like ASIC prototyping forwhich price was of little concern.These days though, suppliers recog-nize that more realistic prices (singledigits) can open the door to a lot ofmainstream applications.

I’ve said before that I think therewill be an SoC in your future. And,with lower chip prices, better tools,and fully stocked libraries, I would saythe future is close at hand. I

RESOURCEJ. Gray, “Building a RISC System in

an FPGA,” Circuit Cellar, 116–118, March 2000–May 2000.

Photo 3—Specifying the LCD interface details is a point-and-click affair. Parameters for a number of popular panels are pre-defined. If your panel isn’t on the list, use the provided Excelspreadsheet to calculate the timing parameters.

Photo 2—A Triscend evaluation setup includes theEVAL520 board and LCD interface board plugged intoan I/O and memory expansion baseboard.

SOFTWARETo download a list of the CSoC fea-tures, go to go to ftp.circuitcellar.com/pub/Circuit_Cellar/2002/140/.

Page 84: Circuit Cellar2002 03

82 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

51 East Campbell AveCampbell, CA 95008

....by using real-time emulators.

888-886-6428

Support for:HC12, HC118051C166C500ST10Super10Philips XA68300 familyUbicom Scenix

"Nohau emulators show you what is really goingon inside your embedded system. Turn yourselfinto a debugging expert and find bugs fast."

How to:Cut Your Development Time

[email protected]

For more “How to” info see www.nohau.com/howto

408-866-1820

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 86: Circuit Cellar2002 03

84 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

SI-SCOPE AnalyzerFull featured PC RS232 Analyzer for Windowsand DOS. No more guess work SI_SCOPE letsyou view and interact with any RS232 line.Complete with Timestamps, Triggers, SignalCapture, and more!

SI_COMM ActiveXRobust 32 Bit Communications ActiveX for VC++and VB. Full Port Control, Async CallbackEvents, Xmodem, Ymodem, Zmodem, and more!Complete with examples in VB and MFC!

Software InnoVations Inc.

www.sinnovations.com

72 Prospect Hill Rd.Wallkill, NY 12589

Ph: 845-566-1919Fax:[email protected]

Page 90: Circuit Cellar2002 03

88 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

1•80

0•A

•Dre

amer

ww

w.D

ream

Tech

.co

m

!" #$%$&''( #)*+,-)-.*/! !!0 !0 '1 ""!' 2!" " 3 4/!" 5(6!"

$ 7*(3!" #$%$&''( #)*+,!!0 !0 89-)'1 "*!""*!"8:--'!;<2 /934/!"5(6!"5#$=<*".9&!> "-.*/! 8-)

Dream P4-845D

POWERFUL PENTIUM 4 ~ USING INTEL 845GBMAIN BOARD & FAST PC2100 DDR MEMORY!VALUE PRICED WITH 128MB RAM, 40GB HD,MOUSE, SOUND & MODEM!

DreamTech

DreamMX-464

$3 3!" #$%$&''( #)*+,!!0 !0 '4+1&1 "*!" "-.*/! 8-)<2 /934/!"5(6!"5#$=<*".9&!>

$3 *7 3!" # $% $ &''( #)*+,!!0 !0 '1 ""!' "-.*/! 8-) " (8 :-- '!;: ".=70 985(6!"5#$=<*".9&!>

FAST PC800 RAMBUS MEMORY & INTELD850MV MAIN BOARD FOR ULTIMATEPERFORMANCE. AVAILABLE UP TO 2.2GHz!A STATE OF THE ART PENTIUM 4 SYSTEM.

$3

$3

1•51

0•35

3•18

00

!!

"#$%&'()()*+,-./01

$

64MB GEFORCE II, 60GB HD, SOUND & MODEM.USES STANDARD PC133 SDRAM FORGREATER COMPATIBILITY ~ A DREAM BUY.

DreamPowerDesigner +

Dream P4-850R

2(

$33

RELIABLE PIII WORKSTATION! COMPLETE &READY TO LOAD WITHOUT UNWANTED EXTRAS.

®

®

Page 96: Circuit Cellar2002 03

Robotics94 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

INDEX11,85 Abacom Technologies

92 Abia Technology

24 Acroname Inc.

84 ActiveWire, Inc.

72 ADAC

82 Advanced Circuit Designs Inc.

19,37 Advanced Transdata Corp.

62 All Electronics Corp.

84 Amazon Electronics

9 Amulet Technologies

92 AP Circuits

91 Appspec Computer Tech. Corp.

63 Arcturus Networks

83 Athena Microsystem Solutions LLC

85 Atlantic Quality Design, Inc.

41 B+K Precision

84 Bagotronics

91 Baritek

17,83 Basic Micro

48 CadSoft Computer, Inc.

14 CCS-Custom Computer Services

49 Ceibo

86 Cermetek Microelectronics Inc.

92 Conitec

11 Connecticut mircoComputer Inc.

91 Copeland Electronics Inc.

91 Cyberpak Co.

39 Cypress MicroSystems

C4 Dataman Programmers, Inc.

86 Dataprobe Inc.

85 DataRescue

82 Decade Engineering

89 Delcom Engineering

The Advertiser’s Index with links to their web sites is located at www.circuitceller.com under the current issue.Page

87 Designtech Engineering

88 Dreamtech Computers

1 Earth Computer Technologies

23 ECD (Electronic Controls Design)

83 EE Tools (Electronic Engineering Tools)

14 EMAC, Inc.

33 Engineering Express

55 ESEC Tokyo

90 EVBplus.com

83 FDI-Future Designs, Inc.

90 GoHubs, inc.

83 Hagstrom Electronics

90 Hall Research Technologies

23 HI-TECH Software,LLC

91 HVW Technologies Inc.

84 ICE Technology

89 IMAGEcraft

85,92 Intec Automation, Inc.

42 Interactive Image Technologies Ltd.

85 Intronics, Inc.

67 Intuitive Circuits, LLC

26 JED Microprocessors Pty Ltd.

64 JK microsystems

70 JR Kerr Automation & Engineering

83 Kuper Controls

67 LabJack Corp.

56 Laipac Technology, Inc.

67 Lakeview Research

50,87,93 Lemos International

2 Link Instruments

91 Lynxmotion, Inc.

81 MaxStream

93 MCC (Micro Computer Control)

10 Microchip

89 Micro Digital Inc

92 microEngineering Labs, Inc.

40 Micromint Inc.

90 MicroSystems Development, Inc.

87 MJS Consulting

58 MVS

86 Mylydia Inc.

33,70 Nav Masters

65 NetBurner

95 Netmedia, Inc.

82 Nohau Corp.

88 OKW Electronics Inc.

93 Ontrak Control Systems

87 P & E Microcomputer Systems Inc.

90 Paradigm Systems

C2 Parallax, Inc.

90 Peter H. Anderson

82 Phytec America LLC

93 Phyton, Inc.

93 Picofab Inc.

25 PicPalm

85 Pioneer Hill Software

86 Prairie Digital Inc.

47 Premier GPS Inc.

7 PSoC 2002 Design Challenge

89 Pulsar Inc.

86 R2 Controls

31 R4 Systems Inc.

71 Rabbit Semiconductor

84 R.E. Smith

56 Remote Processing

89 RLC Enterprises, Inc.

Design a Noncontact Infrared Bumper

An Open Source Motor Control Project

The Rovervac—Building a Robotic Vacuum Cleaner

Cyber Robotics?—Experimenting with Robot Simulation

Designing with the RoCK—A Robot Conversion Kit

I Above the Ground Plane: Switches and Glitches

I From the Bench: You Too Can Design with SoC—A Design Challenge 2002 Primer

I Silicon Update: Home is Where the Plug is

I Applied PCs: Replacing Relays with Ladder Logic—Part 2: The T100MD-1616+

Page Page Page

PREVIEW

141

ADVERTISER’S

Attention Advertisers:

May Issue Deadlines

Space Close: March 8Material Due Date: March 15

Theme: Signal Processing

86 RPA Electronics Design, LLC

91 Rutex

45 Saelig Company

89 Scidyne

3 Scott Edwards Electronics Inc.

38 SeaFire Micro, Inc.

88 Sealevel Systems Inc.

86 Senix Corp.

84 Sensory, Inc.

82 Signum Systems

87 SmartHome.com

70 Softools

84 Software InnoVations, Inc.

16,57 Solutions Cubed

92 Spectrum Engineering

82 Square 1 Electronics

32 SUMBOX

15 Systronix

83 TAL Technologies

C3 Tech Tools

84 Techniprise Inc.

73,79 Technologic Systems

86 Technological Arts

88 Tern Inc.

18 Texas Instruments

86 Triangle Research Int’l Inc.

25 Trilogy Design

90 Vesta Technology

85 Vetra Systems Corp.

93 Weeder Technologies

87,89,90 Wittig Technologies

91 Xilor Inc.

87 Z-World

84 Zagros Robotics

Page 98: Circuit Cellar2002 03

never thought I’d say this, but enough is enough. Feature creep in every communication device, computing gadg-et, and entertainment contraption has made them overly complicated to use. I’ll admit that it used to be a badge of

distinction when I claimed to be one of those guys who couldn’t program the VCR. In truth, it was partly because wehave six VCRs, all different brands, and none program the same way, but it was mostly because I was too lazy to deal with

all of the instructions. I don’t see myself getting better either.What got me thinking about all of this was an e-mail from an Italian reader who translated an article from the auto section of a respected

Bologna newspaper. Essentially, the article lamented that car manufacturers were creating their new design offerings via enhanced electron-ics rather than better engineering. Having apparently not learned their lesson from the disastrous response to talking cars (remember “thedoor is ajar”), feature competition among car manufactures is as fierce as ever. However, instead of physically engineering new models,“new design” now means the application of electronics to virtually everything. Certainly electronics has made cars safer, but if I understandthe article correctly, it contends that when the software guys take over car design, somehow we trade true engineering advancement for fea-ture enhancements. They also might not know when to stop. In short, electronics can continually increase the reaction time and response ofvehicle brakes—right up to the point when a catastrophic event demonstrates that the brake disk is really just too small.

Ordinarily, I wouldn’t get excited by all of this hype, but it’s starting to hit a little too close to home. As a car buff, I’ve always respectedgood engineering and I’ve paid the price to drive it. When somebody tells me that my next car is going to look like something from Microsoft,I go berserk! OK, for the most part I hide out in a cellar but occasionally I do venture out. I drive a BMW 740iL. In fact, I like them so much(I’ve owned six) that I even placed an order, sight and specs unseen, for the new BMW 745i almost a year ago. After all, it’s a BMW. Whatcould they do to it but make it better?

At this point I have to qualify everything else I say as the rantings of a car buff displaced by software enhancements and feature creep.This is an emotional issue because I love cars and because I’m an engineer. Currently, there are no test cars available in my area, so I haveno concrete proof for any of my claims. It’s just that from the early reports, I have this awful feeling that the car I love has become a comput-er nightmare. Worse yet, even if all of the enhancements really work, I can’t help but visualize the trunk completely filled with instructionmanuals necessary to operate the thing. And you already know how I feel about instructions.

Admittedly radical in design, the 745i has a more powerful engine and the only production six-speed automatic transmission on the mar-ket. At 0 to 60 mph in 5.8 s, that’s the car I ordered! What I didn’t count on was the car having more computers than a NASA shuttle. To con-trol some 700 functions for communication, GPS, climate, and entertainment, the designers removed the stick shift and replaced it with a bigrotary knob so you can menu-control everything on a video screen (when you’re not using the voice recognition system, that is). I can’t waitfor the cell phone police to catch some guy weaving all over the road while trying to tune a radio station on his iDrive!

And finally, something all of you will closely identify with: think about coordinating all of the embedded controllers. This car has no lessthan 123 electric motors in it; there are 38 fans just in the two front seats! Heaven forbid you blow a fuse.

As I said, it’s an emotional issue and maybe I’m getting too old. It used to be that I’d get in my car and turn the key. Yes, I studied theowner’s manual for the 30 minutes it took to set all of the necessary defaults, but then the negotiation ended. I was in control and the vehicledynamics would remain the same until I changed them. Unless I’m overreacting to the handwriting on the wall, I see cars evolving into com-puters with engines. Daily or weekly your car will link through the Internet into a maintenance system to upload the latest anti-virus software,engine control tweaks, trip and map resources, entertainment, movie, and game files, and lots more. Just like the computer you have on yourdesk today, you’ll know less and less about what really makes it tick and it will become just one more appliance.

I understand the necessity for technical evolution and I want to be wrong about my fears. Most of all, however, I want them to stop mess-ing with the world’s best driving machine, especially when it’s mine!

Automobiles by Microsoft?

INTERRUPT

i

[email protected]

96 Issue 140 March 2002 CIRCUIT CELLAR® www.circuitcellar.com

PRIORITY

Page 100: Circuit Cellar2002 03

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