#147 October 2002 www.circuitcellar.com CIRCUIT CELLAR®

THE MAGAZINE FOR COMPUTER APPLICATIONS DATA ACQUISITION

2-D Or Not 2-D

Solar-Powered Robot

The LED Alternative

Mad DashWWW.GiURUMELE.Hi2.RO For Flash Cash Contest Primer

10>

7925274 75349

$4.95 U.S. ($5.95 Canada) WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO Digital Oscilloscopes

• 2 Channel Digital Oscilloscope DSO-2102S $525 • 100 MSa/s max single shot rate DSO-2102M $650 • 32K samples per channel Each includes Oscilloscope, • Advanced Triggering Probes, Interface Cable, Power • Only 9 oz and 6.3” x 3.75” x 1.25” Adapter, and software for • Small, Lightweight, and Portable Win95/98, WinNT, Win2000 • Parallel Port interface to PC and DOS. • Advanced Math options • FFT Spectrum Analyzer options Logic Analyzers

• 40 to 160 channels • 24 Channel Logic Analyzer • up to 500 MSa/s • 100MSa/S max sample rate • Variable Threshold • Variable Threshold Voltage • 8 External Clocks • Large 128k Buffer • 16 Level Triggering • Small, Lightweight and Portable • up to 512KWWW.GiURUMELE.Hi2.RO samples/ch • Only 4 oz and 4.75” x 2.75” x 1” • Optional Parallel Interface • Parallel Port Interface to PC • Optional 100 MSa/s Pattern Generator • Trigger Out • Windows 95/98 Software LA4240-32K (200MHz, 40CH) $1350 LA4280-32K (200MHz, 80CH) $2000 LA2124-128K (100MSa/s, 24CH) LA4540-128K (500MHz, 40CH) $1900 Clips, Wires, Interface Cable, AC LA4580-128K (500MHz, 80CH) $2800 Adapter and Software $800 LA45160-128K (500MHz, 160CH) $7000 All prices include Pods and Software www.LinkIns4.com Link Instruments • 369 Passaic Ave • Suite 100 • Fairfield, NJ 07004 • (973) 808-8990 • Fax (973) 808-8786 WWW.GiURUMELE.Hi2.RO TASK MANAGER

EDITORIAL DIRECTOR/FOUNDER CHIEF FINANCIAL OFFICER Be a Contender Steve Ciarcia Jeannette Ciarcia MANAGING EDITOR Jennifer Huber CUSTOMER SERVICE Elaine Johnston TECHNICAL EDITOR C.J. Abate ACCOUNTANT Jeff Yanco WEST COAST EDITOR Tom Cantrell ART DIRECTOR he pages of Circuit Cellar brim with practical yet KC Prescott intriguing information. Our goal is to enlighten and CONTRIBUTING EDITORS t Ingo Cyliax entertain you with every issue. In keeping with our goal, Fred Eady GRAPHIC DESIGNER Mary Turek we have a number of features throughout the magazine that George Martin inform, teach, and hopefully inspire you. Most of our articles serve as tutorials, George Novacek Jeff Bachiochi STAFF ENGINEERS giving you step-by-step instructions on how to build with a new part or sophisti- John Gorsky cated technology. And, you can always count on columnist Tom Cantrell for NEW PRODUCTS EDITOR John Gorsky QUIZ COORDINATOR updates on the industry. In every issue, you’ll also find thought-provoking quiz David Tweed questions (page 11), announcements about products fresh to the shelves (page 8), PROJECT EDITORS Steve Bedford and a guide to find the ads of your favorite manufacturers (page 94). But, one of Ken Davidson our best staples is our challenging design contests. David Tweed Circuit Cellar contests have become one of our most successful ventures. ADVERTISING Each one draws out top engineers who specialize in everything from chip design PUBLISHER to embedded systems, and from neuroscience to rocket science. The varied Dan Rodrigues E-mail: [email protected] backgrounds of the contestants always ensure a plethora of unique entries. ADVERTISING SALES MANAGER Sean Donnelly Fax: (860) 871-0411 If you haven’t already participated in one of our contests, don’t miss your (860) 872-3064 E-mail: [email protected] next opportunity. Start building your project for the Mad Dash for Flash Cash Cell phone: (860) 930-4326 Design Contest 2002, sponsored by Microchip Technology, today! You have until ADVERTISING COORDINATOR December 16 to enter, so that still gives you a couple of months to work on your Valerie Luster Fax: (860) 871-0411 project. The Microchip PIC family of has become universally (860) 875-2199 E-mail: [email protected] popular; in fact, we continually receive scores of articles about projects that fea- ADVERTISING ASSISTANT ture various PIC parts. With a well-liked PIC at the center of your design, you’ll Deborah Lavoie Fax: (860) 871-0411 (860) 875-2199 E-mail: [email protected] have no trouble creating a masterpiece of ingenuity. Those of you who want an edge in the competition should incorporate one of Cover photograph Ron Meadows—Meadows Marketing the following features: TC1047 temperature sensor; MCP6022 op-amp; PRINTED IN THE UNITED STATES MCP3002 analog-to-digital converter; MCP42100 digital potentiometer; CONTACTING CIRCUIT CELLAR MCP1541 VREF; at least one communication port; or a CCP to control an SUBSCRIPTIONS: INFORMATION: www.circuitcellar.com or [email protected] event. Entries that showcase any of these features will be given bonus consider- To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or [email protected] ation by the judges; for more information, read the official contest rules on our PROBLEMS: [email protected] web site (www.circuitcellar.com/flash2002). GENERAL INFORMATION: TELEPHONE: (860) 875-2199 Fax: (860) 871-0411 Consummate designers get all of the facts first. Before you begin working INTERNET: [email protected], [email protected], or www.circuitcellar.com with these features, I recommend reading columnist Jeff Bachiochi’s article, EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066 NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066 starting on page 62. Jeff’s thorough introduction to Microchip components will [email protected] AUTHOR CONTACT: ready you for the task. After reading his article, you’ll be armed with the knowl- E-MAIL: Author addresses (when available) included at the end of each article. edge needed to design a competitive project. For information on authorized reprints of articles, Aside from the prestige winners earn from succeeding in a Circuit Cellar con- contact Jeannette Ciarcia (860) 875-2199 or e-mail [email protected]. test, they also receiveWWW.GiURUMELE.Hi2.RO prizes. A total of nine entries will be awarded prizes: CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub- Grand, First, Second, Third, and five Honorable Mention prizes. The lucky win- lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico ner of the Grand Prize stands to receive the Microchip MPLAB ICE2000 proces- $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 money sor module and free registration to the Microchip Annual Summer Technical order, or check drawn on U.S. bank. Exchange Review (MASTERs). Additionally, don’t forget that we’ll recognize all Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call (800) 269-6301. of the winners in the magazine as well as on our web site. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from 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 to build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct 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 trademarks [email protected] of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com check out what’s new at www.saelig.com! DrDAQ PC-based Instruments Educational NEW!! Datalogger ADC-10 8-bit $85 through ADC-216 16-bit$ 799—display 12-bit with built-in scope, spectrum and meter simultaneously. Connect to PC sensors! parallel port and start 100Ms/S www.drdaq.com gathering/displaying data dual-ch immediately! DrDAQ plugs into a PC for useful scope • EnviroMon temperature datalogging at school, college, adapter logging/alarm system industry. Built-in sensors for light, standalone or with PC. sound, temp. or add pH sensor and ADC-212/100 • • thermistor- run one of the manysuggested TH-03 to-PC converter science experiments! - only $99! $1015!! • • TC-08 8x thermocouples RS232 to RS422/485 Make PCs Remote control & data acquisition link self-pwrd converters 2 BIT ® talk I C power & data • • Plug directly into PC on two-wire — — self powered! easily! control network • • Drive any RS422 or RS485 devices. • • Send control and data Industry-standard card for PC’s NEW!Euroquartz filters/crystals! 100s of feet! ISA/P-port/PCI versions K422/K485, 25pin > 9pin . . . $69 2-6V I2C bus versions 2-yearself-contained DATALOGGERS for volts, switch- $ • Master, Slave or Bus monitor K2 9pin > 9pin ...... 69 closures, events, flow, pressure, etc. 2 Isolate RS232/422/485 signals • Control or program IC devices See www.abidata.be for details K4xx-ISOL 25pin ICA90/93LV - PICA90/93LV PCI90/93LV self-powered ...... $139 - from$299! 2C” NEW! 9p-9p K3-ISOL - $129! “How to I CANbus Starter Packs www.saelig.com

PCI/ISA/PCMCIA/PC104/ by Janz WILKE TIGER MODULES VME/cPCI format boards. for all NOW! com multitasking powerful BASIC building blocks GPS PCMCIA Software drivers for most OS’s. puters Logging CAN/Ethernet bridges, etc. BASIC Tigers are Datalogger TDS2020 tiny multitasking computer systems lowpower PCcard logging SMD PCB adapters for quick project • • Store analog/digital for prototyping development. Powerful features and low /GPS or CANbus data prices make Tigers a number on FlashATA cards - one choice for developers: super-fast read on your own PC! USB ic’s development cycle, high reliability products, • > 100 customizable USB <> RS232 easily!! >100,000 instructions/s, up to 38 I/O lines,software modules— US232: USB <> RS232 cable $35 A/D, D/A, I2C, SPI, , text/graphic LCD inter-finish REALLY quickly. face, up to 50,000 lines of BASIC, RTC/watch- • 8ch 10bit A/D, 33 I/Os,2C, 2I x dog timer. Easy connection and software for Saelig Company brings youunique, RS232, interrupts, sleepmode, Expansion Modules for CANbus, TCP/IP for easy-to-use control and instrumentation pre-emptive multitasking, easy to net-access, opto-I/O, 64 analog inputs, 64 dig- products to USA, mostly from Europe, but now from worldwide. (Need USA ital outputs, high-current outputs, etc. attach LCD or keypad. • • CANbus adapter—recompile or log sales help - overseas companies?) TIGER Starter Kits start from $159! data over huge network! Our customers comment on our unrivalled FREE Customer list inc: Intel, after-sales support. Compaq, Philips, NEC, Saelig Co. Inc. Kodak, Nokia, US Military, “Hi - I’m Alan Microsoft, Dell, Xerox, - you can email me at 585-425-3753 • Fax: -3835 Universities, T.I., Dalsa,[email protected] for free advice for your control or Harris, Litton, Sony, J&J, measurement problem.” www.saelig.com • [email protected] Thomson, H-P, Agilent, etc. 2-D or Not 2-D? 12 Martin Courtney 20 High-Frequency Job ISSUE Frequency Counter and VFO Controller Richard Hosking

30 Light the Way An LED-Based Alternative Philip Ching & Bruce Land 147 36 Convert Your PC Sound Card Make a DC-Coupled Arbitrary Waveform Generator David Prutchi & Michael Norris 44 Choosing Your LCD Roberto Ferrabone FEATURES 24 ROBOTICS CORNER SOPHOCLES A Solar-Powered MSP430 Robot Jens Altenburg 50 I ABOVE THE GROUND PLANE Audio Transformation Task Manager Ed Nisley 4 Jennifer Huber Be a Contender 54 I APPLIED PCs Design with STKxxx Parts New Product News Build an Ethernet Controller 8 edited by John Gorsky Fred Eady 11 Test Your EQ 62 FROM THE BENCH 12, 16, 18, Hike! Advertiser’s Index Dashing for Flash Cash 94 November Preview Jeff Bachiochi 96 Priority Interrupt 76 I SILICON UPDATE Steve Ciarcia Watch Me Pull A Rabbit Out of My Hat Linguini with Clam Sauce Tom Cantrell Contest Related Articles COLUMNS

6 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Our AVR is probably 12 times faster than the one you’re using now. (It’s also smarter.)

Introducing the Atmel AVR®. An 8-bit MCU that And when you consider that it can help slash months off your can help you beat the pants off your competition. development schedule and save thousands of dollars in project AVR is a RISC CPU running single cycle instructions. cost, it could make you look pretty smart, too. With its rich, CISC-like instruction set and 32 working registers, AVR comes in a wide range of package and performance it has very high code density and searingly fast execution–up to options covering a huge number of consumer and industrial 16 MIPS. That’s 12 times faster than conventional 8-bit micros. applications. And it’s supported by some of the best development We like to think of it as 16-bit performance at an 8-bit price. tools in the business. With up to 128 Kbytes of programmable Flash and EEPROM, So get your project started right. Check out AVR today at AVR is not only up to 12 times faster than the MCU you’re using www.atmel.com/ad/fastavr. Then register to qualify for your free now. It’s probably 12 times smarter, too. evaluation kit and bumper sticker. And get ready to take on the world.

Check out AVR today at www.atmel.com/ad/fastavr

AVR 8-bit RISC Microcontrollers Memory Configurations (Bytes) Debug and Processor Package Flash EEPROM RAM Development Tools tinyAVR 8-32 pin 1-2K up to128 up to128 Available Now low power AVR 8-44 pin 1-8K up to 512 up to1K Available Now megaAVR® 32-64 pin 8-128K up to 4K up to 4K Available Now R

© 2002 Atmel Corporation. Atmel and the Atmel logo are registered trademarks of Atmel Corporation. NEW PRODUCTNEWS Edited by John Gorsky MULTICHANNEL THERMAL MONITORING The ADT7xxx family of temperature-to-digital con- age output 12-/10-/8-bit DAC. And, the ADT7516/17/18 verters offers a combination of multichannel ADCs and adds a four-channel ADC and a quad-voltage output 12-, DACs in addition to its core ambient and remote tem- 10-, or 8-bit DAC. All are fully operational with 2.7- to perature measurement functions. Used in conjunction 5.5-V power supplies and over a temperature range from with the thermal monitoring channels, this additional –55 to 125°C. functionality allows compensation, control, and moni- This family of multichannel temperature sensors is toring of circuits and subsystems, including power designed for applications such as PCs, communication sys- amplifiers, oscillators, power devices, power supplies, tems, industrial instrumentation, and portable equipment. and fans. Combining these multi- In 1000-piece quantities, the ple functions into a low-cost, one- ADT7411 is priced at $2.29 per unit; chip solution allows designers to the ADT7316/17/18 are priced at have more flexibility in optimizing $4.95, $2.95, and $1.75 per unit, their system’s performance. respectively; and the ADT7516/17/18 These new products are all com- are priced at $5.65, $3.65, and $2.65 patible with SPI/I2C and feature a per unit, respectively. 10-bit digital ambient and remote temperature sensor. The ADT7411 Analog Devices, Inc. adds an eight-channel ADC. The (800) 262-5643 ADT7316/17/18 adds a quad volt- www.analog.com

TOUCH SCREEN CONTROLLER SAME-ADDRESS I2C SWITCH The TSHARC Octopus board is a touch screen The PCA954x is the first family of I2C controlled controller that can concurrently and inexpensively switches that can connect multiple devices with the same support all communication standards and analog- I2C address on a single bus. This replaces the multiple I2C resistive touch screen overlays. buses or bus switches previously required. By using the The versatile Octopus has jumper-selectable PCA954x I2C switches, you can greatly simplify board lay- communications capabilities for RS-232, PS/2, and outs for cost savings and additional flexibility. This prod- USB, as well as four-, five-, and eight-wire analog uct is can be used in a wide range of applications in the resistive screen technologies. It is available in 10- computing, communication, telecom, networking, indus- or 12-bit configurations, delivering up to 4096 × trial, and consumer markets that depend on sharing one 4096 resolution. I2C bus with multiple devices with the same I2C address. Available optionally to OEMs as a TSHARC-10 The PCA954x switches are designed for I2C buses or or 12 chip, the Octopus controller can be integrat- SMBuses where multiple devices have the same address or ed on motherboards. Through the use of different voltage levels. These switches allow voltage-level Hampshire’s proprietary dynamic point flow rate shifting between devices operating at 5, 3.3, 2.5, or 1.8 V decoding, the controller quickly and accurately at serial clock frequencies of up to 400 kHz. They provide decodes screen touch points in touch-only, draw- multiplexing and interrupt controlling to eliminate the ing, and writing applications. need for glue logic and general-purpose I/Os. Four devices Hampshire writes and supports all of the support- with two, four, or eight-channel configurations are cur- ing driver software to guarantee a properly matched rently in production. In addition, the switches are set of touch screen hardware and software for any equipped with a hardware reset pin that returns the device application. TSHARC device drivers are included to the default state of no and compensate for high-contact resistance and non- channels selected, thereby cir- linear touch screens, and have built-in parallelogram cumventing the usual step of and trapezoidal linearization correction. Custom and cycling power to restore the private-labeled drivers are also available. bus from a lock-up situation, The board costs $45 which is a significant concern and the chip costs $7 in in critical server applications. quantity purchases. Pricing starts at $0.75 for 10,000-piece quanities. Hampshire Company, Inc. (414) 873-4675 Philips Semiconductors www.tsharc.com www.philipssemiconductors.com

8 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Does your fl ash design idea have what it takes to win? Use Microchip’s fl exible PIC® FLASH microcontrollers to meet all your design needs: • Programming Flexibility • Re-programmability • Remote Self Programming • In-Circuit Serial Programming™ (ICSP™) • Socket & Software compatibility for migration • Flexible peripherals both on and off chip

Be one of nine winning entries and you’ll be eligible for great prizes like MPLAB® certifi ed development tools and FREE registration to Microchip’s Annual Summer Technical Exchange Review (MASTERs) in 2003. At MASTERs, you’ll learn how to solve your greatest embedded control challenges with in-depth training on Microchip products. This rewarding 4-day conference will give you the opportunity to dialog between your peers, consultants/3rd parties, distributor FAEs, design houses and Microchip engineers. So, make a mad dash to the web site below to request your contest registration materials today and compete for fl ash cash. Hurry! The deadline for submissions is December 16, 2002.

MPLAB ICE2000 with Processor Module Grand and Free Registration to MASTERs* 1st Place MPLAB C compiler and Free Registration to MASTERs* 2nd Place PICSTART® Plus and Free Registration to MASTERs* 3rd Place Free Registration to MASTERs* 5 Honorable Mentions MPLAB In-Circuit Debugger 2 (ICD2)

*Please visit the website for alternative cash prizes

The Microchip name and logo, PIC, MPLAB and PICSTART are registered logos and In-Circuit Serial Programming and ICSP are trademarks of Microchip Technology Inc. in the USA and other countries. Circuit Cellar is a registered trademark of Circuit Cellar Inc. ©2002 Microchip Technology Inc. All rights reserved. NEW PRODUCTNEWS

LOW-LOSS POWERPATH CONTROLLER The LTC4412 is a low-loss PowerPath controller that 2.5 to 28 V, which makes it ideal to use with one to controls an external P-channel MOSFET to create a six lithium ion batteries or most AC/DC adapters. It nearly ideal diode function for power switchover or load functions over a temperature range of –40 to 85°C. Its sharing. When conducting, the voltage drop across the internal gate driver includes an internal voltage clamp MOSFET is as low as 10 mV compared to the tradition- for MOSFET protection, and the low quiescent cur- al exponential curve of a comparable Schottky diode. rent of 11 mA is independent of the load current. This permits highly efficient OR'ing of multiple power Finally, a STAT pin can be used to enable an auxiliary sources for extended battery life and low self-heating. P-channel MOSFET power switch when an auxiliary For applications with a supply is detected, or alter- wall adapter or other auxil- natively, it could be used iary power source, the load to indicate to a microcon- is automatically discon- troller that an auxiliary nected from the battery supply is connected. when the auxiliary source The LTC4412 is housed is connected. Furthermore, in a small (1 mm maxi- two or more LTC4412s can mum) six-pin ThinSOT be interconnected to allow package. Pricing starts at load sharing between mul- $1.30 each in 1000-piece tiple batteries or charging quantities. of multiple batteries from a single charger. Linear Technology Corp. The LTC4412 has a wide (800) 4-LINEAR supply operating range of www.linear.com

10 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com CIRCUIT CELLAR T e s t Yo u r EQ

Problem 1—An Arab sheikh tells his two sons to Problem 3—You have two bars of iron. One is race their camels to a distant city to see who will magnetized along its length, the other is not. inherit his fortune. The one whose camel is slower Without using any other instrument (e.g., thread, will win. The brothers, after wandering aimlessly filings, other magnets, etc.), find out which is for days, ask a wise man for advice. After hearing which. the advice, they jump on the camels and race as Contributed by Naveen PN fast as they can to the city. What does the wise man say? Problem 4—A helium-filled balloon is tied to the Contributed by Naveen PN floor of a car that makes a sharp right turn. Does the balloon move while the turn is made? If so, which way? The windows are closed so there is —The following DC measurements are Problem 2 no connection with the outside air. made on a differential amplifier. Vi1 and Vi2 are Contributed by Naveen PN the input voltages. Vout is the output voltage.

Vi1 = 0 V, Vi2 = 0V, Vout = –0.1 V

Vi1 = 0.02 V, Vi2 = 0 V, Vout = 0.4 V Assuming the common mode rejection ratio What’s your EQ?—The answers are posted at (CMRR) is infinity, find the differential-mode gain www.circuitcellar.com/eq.htm and the offset voltage referred to the input. You may contact the quizmasters at Contributed by Naveen PN [email protected]

RS232/RS422/RS485 Converters

RS232 TO RS485 2 wire • Makes your RS232 port an RS485 port • Supports up to 40 RS485 CMC’s low cost converters adapt any devices RS232 port for RS422 or RS485 • Automatically determines operation. These converters provide your data direction. • Signal powered version RS232 device with all the advantages of available RS422 or RS485 including reliable high speed operation (up to 200 kbaud) and ADA485 (requires 9VDC) $79.00 data transmission distances up to 5000 ADA485-1 for 110VAC 89.00 feet. Two AD422s can be used to extend ADA485L signal powered 84.00 any RS232 link up to 5000 feet. Completely transparent to the system; RS232 TO RS485 no software changes of any type are 4 wire necessary. • Converts an RS232 port for use with RS422 or RS485 RS232 TO RS422 devices • Converts bi-directionally • Supports up to 40 RS485 or between RS232 and RS422 RS422 multidrop devices • Use as a short haul modem • Adds multidrop capability to • Plug in and go. No software RS232 devices changes required • Automatically determines data direction. AD422 (Requires 9VDC) $79.00 AD422-1 for 110VAC 89.00 ADA425 (requires 9VDC) $89.00 AD422L signal powered 84.00 ADA425-1 for 110VAC 99.00 Mention this ad when you order and deduct 5% Use Visa, Mastercard or company purchase order code CC83 Connecticut microComputer, Inc. PO BOX 186, Brookfield,CT 06804 (203)740-9890 WWW.2CMC.COM Fax:(203)775-4595 www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 11 tra from a jet engine and you just want to present that data as if it were a sur- FEATURE face. In any case, the problems involved in displaying the information are the ARTICLE same. You need to scale the data, map it from three physical dimensions to Martin Courtney the two dimensions of the computer display, and then render the surface. There are a number of fine texts devoted to this subject. The standard approach uses four-by-four matrices to rotate an object about an arbitrary axis and to scale it to make it appear closer 2-D or Not 2-D? or further away. This approach also allows either perspective or projective drawing, and it permits an object to be located anywhere around the viewer. For engineering data, however, that’s overkill. You can get by nicely doing no more than just rotating the surface about two axes.

BUILDING THE FOUNDATION A few preliminaries are in order before tackling scaling, mapping, and ne thing I’ve rendering. For starters, it helps to o learned: It’s graph- understand the kind of data to which ics that gets people’s this method is suited. The only restric- If you’re at that point attention. People may tion is that it be a single-valued func- not appreciate what it took to create tion of two independent variables—the where 2-D surface your data acquisition masterpiece, but usual case in data acquisition. they’ll appreciate its visual side. In symbols, z = f(x,y), where for images just aren’t So, why restrict users to viewing flat, every x and y there is a unique z value. 2-D color maps? Complement your cre- For example, a basketball would not doing the job anymore, ation with 3-D surfaces that can be qualify. You could drive a stake verti- then it’s time for you to oriented in real time (see Photo 1). cally through it and you would hit two Here’s a step-by-step guide. points, one on the upper side, and the move on to more other on the lower side. But that same THE BIG PICTURE basketball cut in half would qualify. sophisticated 3-D sur- Maybe your data represents the sur- Now think of your data in the face features of a biological sample, or same terms. Each physical sample faces. In this article, maybe your data isn’t really a surface at point is a function of two independent Martin walks us step- all. Perhaps it’s multiple vibration spec- variables. Define the underlying

a) b) z by-step through a proj- c) 1 z v z

ect to create 3-D sur- v zθ faces that can be ori- y u y u yθ ented in real time. y 1 x x x1

Figure 1a—A three-dimensional orthogonal coordinate system is used to define a surface. Note that the coordi- nate system is right-handed. b—The two-dimensional coordinate system of the computer display is a right-handed coordinate system like its three-dimensional counterpart. c—These coordinate systems have a common origin: the

x1-y1-z1 system is the fixed reference system; the x-y-z system is the body system, which is free to tilt and rotate;

the u-v system is the fixed system attached to the display. As you can see, the body system is tilted about the y1-

axis of the reference system and twisted around the reference system’s z1-axis.

12 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com orthogonal coordinate system to be levels as the number of colors in your you render the surface, you’ll need to fit right-handed with axes x, y, and z as palette. Loop through the data looking the largest dimension inside a window. shown in Figure 1a. at four adjacent points at the same Assuming you have more than a few Think of the computer display as a time. Find the largest value and store samples, if you keep the 2000:1 ratio, screen with orthogonal axes denoted u it in the array. Later, you’ll use this the data along the shorter axis will be and v (see Figure 1b). One data type array as a look-up table to select the so compressed that it will be impossi- that will be handy is the three-dimen- color to paint the polygon defined by ble to decipher. Therefore, you’ll want sional analog of a point structure (see the projection of each group of four to scale the data to have the same range Listing 1). The triplet structure makes adjacent points. If you’ll be painting along each axis. There is also code in it easy to handle samples that are not with a 255-color palette, for example, Listing 1 that accomplishes that. uniformly spaced. the relevant code looks like Listing 1. Finally, if you would like the sur- SCALE TO THE WINDOW face you’ll draw to be rendered in NORMALIZE THE DATA To maximize the display size of the color, you’ll want to create an array Suppose your sample measures surface while confining it to a view, with the same dimensions as your 2000 units along the x-axis and one you need to do two things. First, move data. Quantize your data to as many unit along the y-axis. Eventually, when the center of the data to the center of the view. Second, you have to calcu- late a scaling factor. The scaling factor Listing 1—Study this source code carefully. It illustrates some of the most important concepts involved in tells you how many pixels it takes to rendering three-dimensional data on the two-dimensional surface of a computer display. move one unit of data. You’ll use it after you transform your data from ********************************************************************** three dimensions to two dimensions. The triplet structure is used to define a point in 3-D space. ********************************************************************** It’s not difficult to determine the typedef struct TRIPLET { scaling factor. Because you normalized double x; your data it fits inside a cube. A line double y; double z; segment that runs from corner to cor- }; ner of the cube (a diagonal) is the ********************************************************************** greatest distance between any two Find the largest z value of the four vertices in a quadrilateral piece of the surface, and quantize it to 255 colors. points you will encounter. The diago- ********************************************************************** nal will have to fit inside the view no double m = 254.0 / pDoc->m_fSpanZ; matter how the surface, and therefore double b = 0 - m * pDoc->m_fMinZ; for (i=0; im_nNumRows-1; i++) { the bounding cube, may be rotated. for (j=0; jm_nNumCols-1; j++) { This means that with the bounding float zLocalMax = pDoc->m_pXYZ[i][j].z; cube centered in the view, all of the if (zLocalMax < pDoc->m_pXYZ[i+1][j].z) zLocalMax = pDoc->m_pXYZ[i+1][j].z; data will need to be scaled so that the if (zLocalMax < pDoc->m_pXYZ[i+1][j+1].z) diagonal is no greater than either the zLocalMax = pDoc->m_pXYZ[i+1][j+1].z; height or width of the view, whichev- if (zLocalMax < pDoc->m_pXYZ[i][j+1].z) zLocalMax = pDoc->m_pXYZ[i][j+1].z; er of these two is smaller. All it takes m_pnColorIndex[i][j] = is a little Pythagoras (see Listing 1). (int) (m * (zLocalMax + pDoc->m_fMidZ) + b); } } MAP FROM 3-D TO 2-D ********************************************************************** So, how do you represent physical Normalize x and y so the range of data is the same along all axes. data on a flat display? The answer is by ********************************************************************** double dSpanZ = dMaxZ - dMinZ; judiciously choosing your coordinate if (dSpanZ != 0.0) { systems, and then calculating the pro- dScaleX = dSpanZ / dSpanX; jection of one system onto the other. dScaleY = dSpanZ / dSpanY; for (i=0; i

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 13 attached to the surface that represents Listing 1—Continued your data. This is the body coordinate system. Notice that the origin of this } system coincides with the origin of } } the other two. This is important. Even ********************************************************************** though the body system can rotate, Calculate the scaling factor so that the surface always fits inside the location of its origin is fixed. the window. ********************************************************************** How you allow the surface to rotate GetClientRect(&m_rcClient); //Get window size is also of importance. You’ll find that m_nHCenter = m_rcClient.Width() / 2; you get nice results by just twisting m_nVCenter = m_rcClient.Height() / 2; the surface around the z1-axis and tilt- int nMinDmn = (m_rcClient.Width() < m_rcClient.Height()) ? m_rcClient.Width() : m_rcClient.Height(); ing it around the y1-axis of the refer- ence system (see Figure 1c). //Calculate the distance from corner to corner of bounding cube double dDiagonal; Now, in order to determine how a dDiagonal = sqrt(SQR(pDoc->m_fSpanX) + surface that’s been twisted and tilted SQR(pDoc->m_fSpanY) + projects onto the u-v plane of the dis- SQR(pDoc->m_fSpanZ))); m_dPixelsPerUnit = nMinDmn / dDiagonal; //Calculate scale factor play, you have only to consider how ********************************************************************** the axes of the body coordinate system The simple expressions transform from 3-D to 2-D. project. That’s because every point that ********************************************************************** inline POINT xyz2uv(float x, float y, float z) { makes up the surface can be represent- POINT pt; ed as a linear combination of the x-y-z pt.x = axes of the body system (i.e., a point is (long) (m_dPixelsPerUnit * ((+x * m_dSinThetaZ) + (+y * m_dCosThetaZ))); //Along u-axis located by moving so much along the pt.y = x-axis, plus so much along the y-axis, (long) (m_dPixelsPerUnit * plus so much along the z-axis). (-(((-x * m_dCosThetaZ + +y * m_dSinThetaZ) * m_dSinThetaY) + (+z * m_dCosThetaY)))); //Along v-axis To see how this works in practice, return pt; choose a data point with coordinates } A, B, and C in a body coordinate sys- ********************************************************************** The code to render the surface is minimal. tem that initially coincides with the ********************************************************************** reference coordinate system. Twist if (m_zTheta < 90) { // Inc X, Dec Y the body coordinate system by zθ and for (i=0; im_nNumRows-1; i++) { for (j=pDoc->m_nNumCols-1; j>0; j--) { observe how the components along apt[0] = m_pUV[i][j]; each axis project onto the reference apt[1] = m_pUV[i+1][j]; coordinate system. Then, tilt the body apt[2] = m_pUV[i+1][j-1]; apt[3] = m_pUV[i][j-1]; coordinate system by yθ and see how m_pdcData->SelectObject(&m_abr[m_pnColorIndex[i][j-1]]); the components project. m_pdcData->SelectObject(&m_apen[m_pnColorIndex[i][j-1]]); Look first at the vector along x with m_pdcData->Polygon(apt, 4); } length A. After twisting by zθ, where } pDC->BitBlt(0, 0, rect.Width(), rect.Height(), the angle is measured from the x1-axis, its projection onto the reference sys- m_pdcData, 0, 0, SRCCOPY); } θ tem is A sin(z ) along the y1-axis. Its ********************************************************************** projection has no component along The code to render a slice is just as simple. the z -axis of the reference system. ********************************************************************** 1 if (m_zTheta < 90) { //Increase x, decrease y. Notice, however, that there is a com- for (i=0; im_nNumRows; i++) { ponent out of the plane of the display for (j=pDoc->m_nNumCols-1; j>=0; j--) { (i.e., along the x -axis of the reference aptSlice[j+1] = m_pUV[i][j]; 1 } system) with length A cos(zθ). aptSlice[0] = //Attach the vertical sides. Now, tilt by yθ (this angle is meas- xyz2uv(pDoc->m_pXYZ[i][0].x, pDoc->m_pXYZ[i][0].y, fMinZ); ured from the z -axis) and see how the aptSlice[0].x += nRectWidthDiv2; 1 aptSlice[0].y += nRectHeightDiv2; components you just calculated proj- aptSlice[pDoc->m_nNumCols+1] = ect. The projection that lies along the xyz2uv(pDoc->m_pXYZ[i][pDoc->m_nNumCols-1].x, y -axis, A sin(zθ), is unaffected by a pDoc->m_pXYZ[i][pDoc->m_nNumCols-1].y, fMinZ); 1 aptSlice[pDoc->m_nNumCols+1].x += nRectWidthDiv2; rotation about y1. It’s like spinning a aptSlice[pDoc->m_nNumCols+1].y += nRectHeightDiv2; pipe about its long axis. m_pdcData->Polygon(aptSlice, pDoc->m_nNumCols+2); For the component along the x -axis, } 1 pDC->BitBlt(0, 0, rect.Width(), rect.Height(), A cos(zθ), it’s a different story. This is m_pdcData, 0, 0, SRCCOPY); like swinging a pipe by one end. After } tilting, this component has no projec-

14 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com What’sWhat’s inin youryour nextnext projectproject ??

The Basic Atom is an easy to use self contained microcontroller. Download your program, apply 5 volts and your are up and running. From beginners to professionals, programming microcontrollers has never been easier !

Experiment and test code changes on-the-fly! The Basic Atom software includes a built-in ICD (In Circuit Debugger ). Atom 24 Module Atom 28 Module Watch your program run on screen with variables, SFRs and RAM values being updated as each line of code executes on Only $59.95 Only $64.95 the Basic Atom. The Basic Atom’s ICD is so easy to use, even a first time user can have it up and running in minutes ! Atom 40 Module BS2p compatible syntax, with a complete expanded set of Only $79.95 powerful and easy to use commands ! Serin, Serout, If..Then..Elseif..Else..Endif, Do..While, While..Wend, OWin, OWout, ADin, Pulsin, Pulsout, PWM, Xin, Xout and more!

32 Bit Floating Point Math.The Basic Atom supports 32 bit floating point and integer math. This includes 32 x 32 bit divides and multiplies. 300 bytes of RAM. No more wasting time trying to save variable space in your program. Additional features include a built-in Analog to Digital converter, UART, 2 PWMs and more. Atom Super Development Board OEM Atom Order your Basic Atom today ! Only $59.95 Only $69.95 ExplorerExplorer RobotRobot Introducing the Explorer Robot. The Explorer Robot is great for the robot enthusiast, educational programs, hobbyist or just about anybody interested in robotics ! The Explorer Robot chassis is made from anodized brushed aluminum. This high quality chassis provides a sturdy base for mounting servo motors, controller board and any number of add- ons. Each chassis includes elongated slots for mounting flexibility. Easily customize the Explorer Robot chassis to suit your needs. The front style caster wheel allows the Explorer Robot to maneuver easier on carpet, grass or flooring tile. Each Explorer Robot comes complete with two infrared obstacle sensors, ARC controller board (Based on the new Atom Pro), front caster wheel, chassis, modified servos, wiring, battery holder, software and manual. Plus the book “Experimenting with the Explorer Robot”, which contains several useful projects for your new Explorer Robot. The brains of the Explorer Robot, the ARC controller board, includes a socket for an I2C eeprom, L293D motor driver and more ! The ARC board is designed as the ideal robotics controller board. Several Add-ons are available. Explorer Robot Kit Order your Explorer Robot Today ! Only $199.95

To order visit www.basicmicro.com or call us at 1-800-869-5095 (M-F 9 AM to 6 PM EST) The Basic Atom is a registered trademark of Basic Micro Inc. a) b) c)

Figure 2a—The surface is rendered one quadrilateral at a time, starting with the most distant row. When one complete row is drawn, the next closest row to the viewer is ren- dered. Here, only the first few rows of the surface have been drawn. b—The same surface as rendering continues. Note that drawing proceeds in the direction begun earlier, from the back to the front. c—Here, the surface is almost completed. Rendering in this way, drawing every quadrilateral from furthest to closest, and possibly drawing over already rendered quadrilaterals in the process, is called the Painter’s Algorithm.

tion along the y1-axis; it does have a One down, two to go. The same pro- unaffected. The one along the x1-axis, θ projection along the positive z1-axis cedure applies to the other vectors. B sin(z ), has a projection along the θ θ θ θ given by (A cos(z )) cos(y + 90). The The vector along the y-axis with positive z1-axis of (B sin(z )) sin(y ). reason for the addition of 90 is that length B, when twisted by zθ, has a Like before, you don’t have to care θ the angle is measured from the posi- projection along the y1-axis of B cos(z ). about the projection along x1 because tive z1-axis. A trigonometric identity It has no projection along the z1-axis, it’s out of the plane of the display. allows the preceding to be simplified but does have one along the positive Calculating projections for the final θ θ θ to (A cos(z )) (–sin(y )). There is also a x1-axis given by (B cos(z + 90)). This axis of the body system, the z-axis, is θ projection along the x1-axis, but you can be simplified to B sin(z ). a snap. Twist the vector that has don’t care about it because it points Once again, tilt by yθ and find the length C along the z-axis by zθ and it directly out of the plane of the display projection of these components. The will remain orthogonal to both the x1- θ and isn’t visible. one along the y1-axis, B cos(z ), is and y1-axes. Therefore, there’s no pro- jection along those two, only a com-

ponent along z1 with a length of C. Tilt by yθ and you have a projection θ on the z1-axis of C cos(y ). There’s no

projection on the y1-axis. The projection

on the x1-axis doesn’t show up because it’s out of the plane of the display. Delivering Technology Solutions to the World’s Remembering that the u and v com- Design Engineering Community ponents of the display system are coin-

cident with the y1 and z1 components Santa Clara Convention Center, California of the reference system, respectively, Conference Dates January 27–30, 2003 you now have the necessary transforms Exhibition Dates January 28–29, 2003

Timely, useful design solutions Early Conference Registration delivered in 80+ sessions covering Discount – Save $100.00! the following: Includes full CD–ROM – a $495 value! I System-on-Chip and ASIC Design FREE Exhibits-Only Registration I High-Performance System Design – Save $75.00! Includes keynote and plenary panel DesignCon also features the following: discussions! 135+ Exhibiting Companies Register on-line at Reference Design Village www.designcon.com. sponsored by Toll Free: 1-888-486-8736 IEC Executive Forum Photo 1—This mathematically synthesized three- International Engineering dimensional surface illustrates the results of projecting New Product Announcements Consortium data onto the two-dimensional surface of a computer www.iec.org display. The accompanying source code provides everything necessary to build a surface from acquired data, as well as to rotate, tilt, and display it in a window.

16 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com MSP430 Design Contest! www.ti.com/gadgetorama2002 MSP430 TI unveils world's lowest power MCU.

Features

– Ultralow-power consumption as low as 0.7-µA standby, 1.3-µA active mode and 160-µA per MIPS

– Integrated analog comparator ideal for precise mixed-signal MSP430 – The choice in ultralow-power MCUs starting at just $0.49 measurement Experience the ultimate SoC solution for battery-operated applications. The MSP430C1101 features power consumption as low as 0.7-µA standby and 1.3-µA active. Find a solution for all – Modern 16-bit RISC architecture enables new applications at a of your low-power needs with a portfolio that includes the $0.49 MSP430C1101 to high-end fraction of the code size devices with up to 60-kB Flash and integrated high-performance analog and digital peripherals. – Multifunctional 16-bit multichannel Device Flash ROM SRAM I/O WDT Timer_A Comp_A Price* timer with PWM, capture and (kB) (kB) compare capability MSP430C1101 – 1 128 14 $0.49 MSP430C1111 – 2 128 14 $0.93 – The flexibility of pin- and code- MSP430C1121 – 4 256 14 $1.12 compatible Flash and ROM devices MSP430F1101 1 – 128 14 $0.99 MSP430F1111 2 – 128 14 $1.24 MSP430F1121 4 – 256 14 $1.62 – The MSP-FET430X110 integrated development environment is complete *Price quoted in lots of 10 ku for Flash and 100 ku or greater for ROM. with target board, assembler, 4-kB C compiler, linker and debugger for only $49 Start Development Today! MSP-FET430X110 Development Tool for $49, www.ti.com/rd/c1101 x11x1 Datasheet and Samples via Web, call for Product Bulletin 1-800-477-8924, ext. 8367

R EAL W ORLD S IGNAL P ROCESSING™

Real World Signal Processing and the red/black banner are trademarks of . 65-2221 © 2002 TI to map 3-D data to the two dimensions the y values. Draw line segments from of the display. The only problem is that the projection of one triplet to the the graphics device interface for sys- next. At each end of this polyline, draw tems such as Windows is oriented with a vertical line that extends down to the the positive vertical axis pointing projection of the minimum z value of down. But that’s easy to account for. your data. By connecting the two verti- Just multiply each v component by –1. cal lines with one final line, you’ll All of this can be reduced to just two have one slice of data (see Figure 3). statements, as shown in Listing 1. Repeat this for each value of x, and The code I’ve described is in-lined you’ll reconstruct the data as a series because you’ll call it for every data of slices. In practice, rather than draw- point. As promised, the pixels-per-unit ing lines, you’ll use the polygon func- scaling factor is applied here. It’s tion so that you generate a closed, important to apply it before casting the Figure 3—Data can be represented in a different way. filled slice. This will paint over any result from floating point to integer. Instead of mapping out a surface, vertical slices can be part of a previously drawn slice that’s drawn through the data, as if it were a solid object. obscured by the current one. RENDERING Just as with drawing a surface, All of the pieces of the puzzle are of increasing x values and decreasing you’ll want to draw the slices from now in place for rendering the surface. y values. This is illustrated in Figure 2. back to front. As before, what consti- You just need to connect the dots. I put all of these ideas into the code tutes the back and front depends on That’s because you can create the that you see in Listing 1. how the data is oriented. Again, you surface as a collection of filled poly- Here’s how to proceed in the remain- need to consider four cases. gons laid edge to edge. Four adjacent ing cases. When the surface is twisted In the first case, when the data is points that have been projected onto between 90° and 180°, you draw in the twisted between 0° and 90°, draw the display define each polygon. direction of decreasing x and decreasing your slices along increasing values of The polygons are drawn in strips. y values. From 180° to 270°, you draw x (see Listing 1). The strip furthest from view is drawn along decreasing x and increasing y. For the other three intervals, the first, and the strip closest is drawn Finally, when the twist is between slices are drawn as follows: from 90° to last. This way, hidden portions of the 270° and 360°, the drawing is done 180° along decreasing x; from 180° to surface are painted over by closer por- along increasing x and increasing y. 270° along increasing x; and from 270° tions that obscure the view of what’s In terms of speed, you’ll find that the to 360° degrees along decreasing x. behind them. This is like painting a worst bottleneck is the polygon func- picture of the Alps by first painting tion. More sophisticated methods ONE CALL AWAY the more distant mountains, and then reduce the number of polygons to draw The accompanying sample app partially covering them with a moun- by checking if a surface is hidden. If it demonstrates how the ideas presented tain range that is closer. is, it doesn’t need to be rendered. here come together by displaying a sur- That sounds easy, but there’s a catch. An alternative approach is to reduce face that you can orient in space. Which side is the back, and which is the number of polygons required by Because the required calculations are the front? The question arises because visualizing the surface in a different minimal, you can rotate the surface if you twist the surface 180° from way. This works in the following way. in real time (even for large data sets). where you started, what was the back With very little effort you can turn is now the front and vice versa. If you VARIATIONS ON A THEME this code into a useful component of twist the surface 90°, what was one A surface is not the only useful rep- your project. When you do, viewing side becomes the back and the other resentation of your data. It also can be your data as a three-dimensional sur- side becomes the front. The solution is helpful to view it as a series of cross face is just a function call away. I to look at the surface as it’s twisted sections, which is akin to slicing your through each of four 90° increments. data as though it were a Thanksgiving Martin Courtney earned a BS and MS Referring to Figure 1c, when the turkey, and then placing the slices in Applied Mathematics, and is pursu- body coordinate system is not rotated, upright, side by side. ing a graduate degree in engineering. the x-axis points out of the display You already have everything you Currently, Martin is a senior software and the y-axis points along its positive need to do this; no new calculations engineer at Information Systems horizontal axis. When the body coor- are required. It’s just a matter of tak- Laboratory in California. You may dinate system is twisted by 90°, the ing the projections you found and reach him at [email protected]. x-axis points along the positive hori- connecting them a little differently. zontal axis of the display while the y- Suppose you want to slice your data PROJECT FILES axis points inward. Between these two by cutting it into sections parallel to To download the code, go to ftp. limits, you’ll draw from further away the y-axis. In this case, choose a fixed circuitcellar.com/pub/Circuit_ to closer if you draw in the direction value for x and iterate through all of Cellar/ 2002/147/.

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 19 frequency of the VFO, decodes the data, and then displays it on an LCD module. FEATURE The controller itself has only an 8-bit counter, which contains the most sig- ARTICLE nificant 8 bits of the count data at the end of each count period (100 ms). Richard Hosking The prescaler U2 (74HC4020) con- tains the other 14 bits of data. To access this, the prescaler is toggled via U1:C (pin 9) until the prescaler output changes state. The controller keeps track of how many pulses are required, and from this calculates the contents High-Frequency Job of the prescaler. Thus, the overall res- olution is 22 bits. This means that fre- quencies up to about 40 MHz can be Frequency Counter and VFO Controller counted to a resolution of 10 Hz, which should be adequate for most applications. The controller converts the binary data to BCD and ASCII to drive the LCD (see Figure 2).

PLL CIRCUIT The controller compares the fre- quency from one count to the next. If ost receivers the loop is locked, the controller cor- m and transmitters rects any drift in the VFO by out- nowadays use synthe- putting a positive or negative pulse to If you’re looking for a sized local oscillators an integrator/filter circuit. that are locked to a crystal standard; A voltage follower buffers the inte- way to stabilize a free- however, there are still older and grator so that there is no significant homebrew rigs with free-running local voltage sag across the filter capacitor running local oscillator oscillators that are prone to drift. between counts. The voltage follower Many of these rigs don’t have a fre- output is connected to a varactor diode and obtain a frequen- quency readout, which is virtually that must be placed across the VFO cy readout in one fell mandatory in today’s crowded bands. tank circuit. The varactor should pro- This article describes a board that duce a frequency swing of about 5 kHz swoop, then Richard you can use to stabilize a free-running for a controlled voltage swing between local oscillator and provide a frequen- 0.5 and 4.5 V. If the VFO is likely to has the solution for cy readout in one package. As you can drift more than this, then it should see in Photo 1, the board is quite com- probably be redesigned or repaired. you. How about a pact; it can be mounted on the back of If the error between counts is more its LCD if required. than 50 Hz, it’s assumed that the VFO board that’s comprised is being tuned and the loop is unlocked. of an AT90S1200, a FUNCTIONAL DESCRIPTION In this case, the circuit sets the VCO The board consists of a gate/prescaler circuit, front-end gate/prescaler cir- cuit, a microcontroller, and Display and a loop filter/VCO a loop filter/VCO control 14.202340 MHz circuit using a passive inte- control circuit? grator and voltage follower (see Figure 1). Input Loop Timing Flush filter The front-end samples gate gate PLLOUT the VFO signal, squares it, and gates and prescales it Prescaler under the control of the Controller microcontroller. The Figure 1—The controller does most of the work, performing the main microcontroller counts the count and controlling the various peripheral devices.

20 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com control to mid-range and waits usually different BFO frequencies Pin Definition until there are three counts with- for USB and LSB. Thus, the read- out change before locking the loop 1 GND out from the VFO requires a again. There is no need to lock 2 VCC (5 V) method of setting offsets to give 3 Contrast the loop manually; the PLL sys- the actual operating frequency. In 4 RS (register select 1 = data 0 = command) tem is invisible to the user. This 5 R/W (0 = write to display, 1 = read from display) this case, the board has four I/O sequence is shown in Figure 3. 6 OE (enable—data clocked on negative transition) lines available to select offset fre- 7-14 D0–D7 (data) quencies. Therefore, there are PLL ANALYSIS Table 1—This 4- to 8-bit parallel interface seems to have become 16 possible offsets that you can As far as the PLL is concerned, the industry de facto standard for small LCD modules. set to 10-Hz resolution with a the controller is merely an intelli- positive or negative offset. Note gent phase detector. Assuming that the is 34 ms. The 10-Hz reference (i.e., the that it’s only necessary to ground the VFO can be shifted 5 kHz by the PLL correction pulse) isn’t attenuated signif- I/O pin because there are on-board with a swing of 0.5 to 4.5 V, the VCO icantly; it’s audible on the VFO output, pull-ups on these inputs (see Figure 4). gain (Kv) is 5000/4, or 1250 Hz/V. The but this was not a problem in practice. After the data is entered, it’s stored frequency count takes about 120 ms If the 2.2-kΩ damping resistor (R3) in the controller’s nonvolatile EEP- with a pulse duration to the sample and is omitted, the attenuation of correc- ROM memory. To enter the offset hold circuit of 2 ms per 10-Hz error. tion pulses is improved. In such a data, you have to connect two push-

Thus, phase detector gain (Kp) is: case, the resistor is replaced by a short button switches between bits 0 and 1 circuit. In theory, this would result in of port B and the ground. an unstable loop, but because the loop If ENTER (bit 0) is grounded during doesn’t have to capture lock, it doesn’t normal counter operation, then the appear to be a problem in practice. controller enters the offset setup code or 7.5 mV/Hz. Using the PLL analysis routine. You are then prompted to program from KD9JQ with the loop val- OFFSETS enter “POS” or “NEG” for offset. The ues as shown (RC at 82 kΩ and 33 µF, Most rigs use an IF, and many also SCROLL (bit 1) key is used to select damping 2.2 kΩ), then the 3-dB loop have a mixing scheme to allow use on the appropriate option. When Enter is bandwidth is 9.8 Hz, and the lock time several bands. With SSB rigs, there are pressed again, the program moves to

Figure 2—The use of a microcontroller simplifies the circuit dramatically. There are only five ICs for a complete counter and phase-locked loop.

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 21 the offset frequency. The obtaining a sufficient tuning N flashing cursor indicates Loop locked? Count unchanged? range (5 kHz). You will have which digit is being entered. Y N Y to experiment in order to Increment count The Scroll key advances the Error in count? determine this. For example, digit from zero to nine and N number I used this circuit to stabilize Y then rolls over to zero again Error greater than Three identical a 5- to 6-MHz VFO. In this Error high/low if the Scroll button is pressed 50 Hz? N counts? case, the varactor I used was L H N Y repeatedly. When Enter is Y a BB405B VHF diode with C1 Unlock loop Lock loop pressed, the next digit is VCO midrange Let outputs float at 2 pF. Bear in mind that a selected. Note that the final Huff Puff varactor is a low-Q device, digit is always zero to indi- which may add to VFO noise cate the frequency in hertz. or even cause the VFO to

After the final digit is END stop oscillating. entered, the program returns If the varactor loads the to normal counting. The off- VFO too much, the tuning set data is stored in the EEP- Figure 3—The controller acts as an intelligent phase detector. range could be reduced to ROM at an address selected 3 kHz without too much of a by the four offset select lines. You mount directly via 0.1″ spacing con- problem. The VFO will probably have should set these lines appropriately nectors (e.g., IDC style). Alternatively, a buffer circuit. A sample should be before entering the setup program. a cable can be made using an IDC taken at the output of the buffer via C4 When the counter is in operation, it socket/plug or by wiring the connec- for the input of the counter. For this accesses the EEPROM at the address tions individually. If you’re going to article, I’ve shown an emitter follower selected by the offset select lines and use the backlight, it will require about buffer, but remember that each rig will adds/subtracts the offset from the 2.3 V at 70 to 100 mA. have a different configuration. The VFO frequency accordingly. counter input presents an impedance CONTROLLER of about 1000 Ω, so the take-off point DISPLAY The controller is an AT90S1200. It should have reasonably low imped- The board was designed to interface has a 512-byte program memory, EEP- ance. The counter requires about with 2 × 16 displays with a 4-bit paral- ROM, and serial flash memory pro- 100-mVPP for satisfactory operation. lel interface. This interface appears to gramming, which means that it can be be a de facto industry standard for placed in the circuit where it is to be CONSTRUCTION small displays such as the Hitachi used and programmed there if desired. The counter is built on a double- HD44780. In this mode, the display The program memory appears to be sided, plated-through, masked, and requires a 10-wire interface. Take a small, but because of the rich instruc- overlaid PCB. You may download look at Table 1 for a list of the connec- tion set, compact code can be written. the board overlay from the Circuit tions. In the 4-bit mode, only D4 In fact, this program used nearly all of Cellar ftp site. through D7 are used. There are also the memory (510 of 512 bytes)! Take two wires for the backlight if required. a look at Listing 1 for the count At start-up, the display requires a sequence I wrote as pseudo-code. fairly involved sequence to initialize it reliably, unless you can guarantee VFO CONNECTIONS the rise time of the power supply. Connections to the VFO/rig will Unfortunately, it’s not possible to poll depend on the rig circuit. A typical the display before it’s initialized. scheme is shown in Figure 5. Beware of Some displays (e.g., Sharp) should high voltages in valve rigs! If voltages are more than 50 V, then use high-volt- age blocking capacitors at the input to the counter (C4) and for C1 in Figure 5. If the board is to be built into an existing rig, then it’s necessary to make connections to the VFO tank, VFO output, and an 8- to 12-V supply. Consult the rig circuit diagram to determine the appropriate connec- tions. The components D1, R1, and Figure 5—These are connections to the VFO and VFO C1 should be added across the VFO buffer. Suggested components are shown for a typical Figure 4—Up to 16 offsets can be programmed using tank circuit. Use the smallest value rig setup. Some experimentation may be required, two push-button switches and selected via a 4-bit port. of C1 possible that’s consistent with depending on your particular rig.

22 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Make sure you mount the with a more capable one polarized components care- should improve top-end fully (diodes/ICs/tantalums). sensitivity. Build the regulator section As I mentioned before, first, and check that the sup- the PLL damping resistor ply is 5 V before proceeding (R3) can be omitted with- further. Although it’s not out problems. This mandatory, it’s probably a Photo 1—This is the completed module. As you can see, the board is compact enough improves the attenuation good idea to use a socket to be mounted on the back of the LCD. of the 10-Hz correction for the controller. Be care- pulses. The circuit does ful with static-sensitive devices Assuming the regulator works cor- not have to respond to a step (i.e., to (ICs/controller) by keeping them in rectly, check the front-end circuit by capture lock), so stability does not conductive foam before mounting, and applying a ~200-mVPP signal, and then appear to be a practical problem. If do not handle ungrounded objects. If look at the output of the square (U1 there was a problem with stability, you’re going to solder the display in pin 6). A square wave at the input fre- or a failure to lock, R3 could be place, it’s a good idea to wire the dis- quency should be present. Check pins 4 replaced with a low-value resistor play via a temporary harness to check and 5 of the controller where a 4-MHz that is, say, 10 to 100 Ω. the operation of the counter before clock signal should be present. Also, The AT90S2313 is pin-compatible permanently wiring the display. Note verify the continuity of the connec- with the AT90S1200, and it has a that the underside of the board will tions between the board and LCD mod- more capable timer and added code be inaccessible for troubleshooting ule. There should be a series of pulses space. For those of you who wish to after the display is mounted. The at a repetition rate of about 10 Hz on develop the circuit further (i.e., for board is simple, so it should not pres- the control lines to the prescaler and better frequency resolution), this con- ent any great difficulty to a designer LCD data lines. Adjust VR1 to give troller can be used. Just remember of intermediate experience. best display contrast. If you’re still in that some code rewriting (e.g., register trouble, check every connection on the definitions) will be necessary. I TROUBLESHOOTING board for continuity. Assuming the In every project I’ve built, there has counter is working correctly, set the Richard Hosking is a primary care been at least one error in the con- clock to exactly 4 MHz. Apply a sig- physician in Australia. His technical struction. Before powering up the nal of a known accuracy to the count- interests include radio, DSP, and board, you should check your con- er and adjust C5 until the correct healthcare informatics. You may struction again. You may download a reading is obtained. reach him at [email protected]. parts list for this project from the Circuit Cellar ftp site. UPDATE PROJECT FILES Check the polarity of each compo- A number of these modules have To download the PCB layouts and nent, and go over the board with a been successfully built. Current drain parts list, go to ftp. circuitcellar.com/ magnifying glass to inspect for bad is modest at about 10 mA, which pub/Circuit_Cellar/2002/147/. joints and shorts. Look for shorts to makes them suitable for use in ground from 5 V. Make sure that there portable rigs. In theory, the upper-fre- is continuity between 5 V and the rel- quency limit is about 40 MHz, even RESOURCES evant pins on each IC. If the board though the 2N3904 front-end buffer Atmel Corp., “8-bit AVR does not work at first, adopt a system- starts to run out of steam at this fre- Microcontroller with 1K Byte of atic approach to troubleshooting. quency. Replacing this transistor In-System Programmable Flash— AT90S1200,” 0838H, March 2002.

Listing 1—The pseudo-code describes the count sequence. E. Skelton, “Frequency display and VFO stabilizer,” Elektor, February Reset prescaler 1998. Open gate/start count Wait 100ms SOURCES End count Toggle prescaler until the output changes state (keep track of AT90S1200 Microcontroller number of toggles) Atmel Corp. Calculate 22-bit binary count (408) 441-0311 Convert count to BCD Add/subtract offset from EEPROM www.atmel.com Write to display PLL routine Hitachi HD44780 Repeat sequence Hitachi, Ltd. (800) 448-2244 www.hitachi.com www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 23 This is not merely a fun project for freaky engineers or enthusiasts. ROBOTICS SOPHOCLES can perform real tasks such as observing potentially danger- CORNER ous areas and checking air quality. In addition, you can use its wireless radio to connect several robots to each Jens Altenburg other or to a central PC. The robot has two main operation modes, Autonomous and Command. Autonomous mode is powered by the implemented artificial intelligence of SOPHOCLES each robot. The robot works independ- ently, checks air quality, and gives you a signal if any difference has occurred. A Solar-Powered MSP430 Robot In Command mode, you can operate the robot by sending commands such as left, right, go ahead, go back, and so on. Of course, you can also take pictures with the built-in camera. Short picture sequences can be saved as an animated slide show (e.g., for documentation). This is a complex electronics project that can be realized even if you have a esign contests low budget; therefore, this robot can be d are an excellent used for either academic training or fun. Worried about the way to open the mind to special ideas. Without THE DETAILS side effects of that any pressure from customers, bosses, or The MSP430 microcontroller con- other hindrances of the daily grind, you trols SOPHOCLES. Why did I need an presumably noxious can work on a variety of splendid proj- MSP430? There are lots of other ects. The result of such a project is micros, some of which have more gas that’s lingering in SOPHOCLES, which stands for SOlar power than the MSP430, but the word Powered Hidden Observing VehiCLE(S). “power” shows you the right way. your basement? SOPHOCLES is a robot with a detec- SOPHOCLES is the first robot (with the Rather than trying to tor that looks for poisonous gases or exception of space robots like Sojourner dusty air (see Photo 1). When gases are and Lunakhod) that I know of that’s waft samples into an detected, its motors bring it to that location and a built-in camera takes empty jar for your pictures of the dangerous areas. The robot’s radio then gives you informa- local health depart- tion about the detected materials. You can control the robot and how the solar ment to assay, try fol- cells spend power for missions that lowing Jens’ lead by require low-power intermittent opera- tion over the course of many weeks. building your own THE BASICS gas-detecting robot. Since the first microcontroller was produced, robots have been controlled by a piece of silicon. In this article, I’ll describe how I applied the Texas Photo 1—Take a look at the complete SOPHOCLES. Instruments MSP430 (see Figure 1). In The case for the optical gas sensors, consisting of the addition, you’ll learn about my robot’s multicolor LED and the TSL250 in front of the robot, special features, which include an air has been removed to give you a better view. The CMOS camera is placed on top of the robot, and the quality sensor, solar cell, and CMOS radio modem is hidden behind the camera so only the camera sensor that’s used for picture antenna is visible. A flexible cable connects the camera transmission via a wireless radio. with the MSP430 microcontroller.

24 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Photo 2 (left)—On the PCB, the iron plates fix the DC motors. The second motor shaft later carries an optical shutter for counting revolutions. The cylin- drical component is the gold cap for the power.

Photo 3 (right)—The Robot Control Center serves as an interface to control the robot. Its main feature is to display the transmitted pictures and meas- urement values of the sensors. With enough power (maximum charged gold cap), the robot can be controlled by a remote. powered by a single lithium battery ciency cells provide electric energy for supplies the CPU in Sleep mode, dur- and a solar cell for long missions. a minimum of approximately two ing which all other loads are turned How is this possible? The magic minutes of active time per hour. Good off. The other source of power comes mantra is, “Save power, save power, lighting conditions (e.g., direct sun- from a solar cell. The solar cell charges save power.” In this case, the most light or a light beam from a lamp) a special 2.2-F capacitor. A step-up con- important feature of the MSP430 is its activate the robot permanently. The verter changes the unregulated input low power consumption. It needs less robot needs only about 25 mA for voltage into 5-V main power. The than 1 mA in Operating mode and even actions such as driving its wheel, LTC3401 changes the voltage with an less in Sleep mode because the main communicating via radio, or takes pic- efficiency of about 96% (see Figure 2). If function of the robot is sleeping (my tures with its built in camera. Isn’t the input voltage increases to about main function, too). From time to time that impossible? No! Let’s have a look 3.5 V (at the capacitor), the robot will the robot wakes up, checks the sensor, at the inner workings of SOPHOCLES. wake up, changing into Standby mode. takes pictures of its surroundings, and Now the robot can work. then falls back to sleep. Nice job, not POWER SUPPLY The approximate lifetime with a only for robots, I think. The robot has two power sources. full-charged capacitor depends on its The power for the active time One source is a 3-V lithium battery tasks. With maximum activity, the comes from the solar cell. High-effi- with a 600-mAh capacity. The battery charging is used after one or two min- utes and then the robot goes into Sleep mode. Under poor conditions (e.g., low light for a long time), the robot has an Emergency mode, during which the robot charges the capacitor from its lithium cell. Therefore, the robot has a chance to leave the bad area or contact the PC.

WIRELESS RADIO If the robot finds a suspi- cious measurement, it com- municates the information via an alarm system like a PC. Wireless radio works with a 433-MHz low-power device (see Figure 3). Because of the restricted power conditions, an intermittent working regime is implemented. After every 50 ms in Active mode, the robot checks the carrier signal from the radio. When a signal Figure 1—The electronics of SOPHOCLES consists of several blocks, including the transceiver, sensors, power supply, motor drivers, and MSP430 CPU. Some block functions (i.e., the motor driver or radio modems) are represented by software mod- is not found, the radio will be ules. Such combined hardware and software modules can be used in numerous other projects with minor modification. switched to Standby mode.

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 25 Figure 2—Because of the changing light conditions, a step-up voltage converter is needed for generating stabi-

lized VCC voltage. The LTC3401 is a high-efficiency converter that starts up from an input voltage as low as 1 V. The selection of L1, C8, and C11 is important to ensure that the LTC3401 works correctly. Linear Technology rec- ommends X5R capacitors and inductors by Sumida (www.sumida.com).

The robot is also controlled via radio. control, and high short-time overload As soon as power is available, the robot capacity. In short, it’s the ideal power accepts direct commands from an oper- supply for SOPHOCLES (see Figure 4). ator. Theoretically, the highest data I also replaced the integrated com- transmission rate is 64,000 bps. mercial H-Bridge drivers, like L293 and others, with a simple CMOS cir- DC MOTORS cuit. The 74ABT126 drives about Servos for RC models are often used 60 mA. I used two parallel stages in for driving the wheels in small robot the circuit, and 120 mA is more than designs. Usually, these servos have enough for the DC motors. enough power for driving their own In addition, two optoelectronic current needs of approximately 10 mA components serve as a revolution for electronics and about 80 mA for the counter. A shutter interrupts the built-in motor itself. As a result, two of light beam twice per revolution, so these servos need 150 to 200 mA dur- an exact measurement of the moving ing motion. That was much too much distances is possible. for my needs, so I chose another motor. The Black Forrest region of Germany CAMERA is well known for the cuckoo clocks One of the most interesting features produced there; however, high-preci- of my robot is its built-in CMOS cam- sion gear motors are produced there era. The main problem with transmit- too. Take a look at Photo 2 and then ting video signals is the broad channel refer to the FTB Feintechnik Bertsch width for quality videos. Streaming GmbH web site to see what I mean (www.ftb-bertsch.de). The secret of the miniature motor’s low profile is in its flat rotor (not iron), which is composed of three flat, oval-shaped windings that rotate in the axial-magnetized stator air gap. The rotor doesn’t suffer from cogging or iron losses, but benefits from its low inertia. This results in a low start- Figure 3—The Radiometrix BiM 433 module serves ing voltage, high efficiency, excellent as a radio transceiver. Depending on the series, data rates up to 160 kbps are possible. The trans- acceleration capability, smooth low- ceiver works as a low-power device with 10 mW in speed motion, simple linear speed the 433-MHz frequency range.

26 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com video wasn’t necessary for this project; still pictures are sufficient. The solu- tion to the problem of obtaining pic- tures was a direct connection between the CMOS sensor and MSP430 (see Figure 5). The MCU controls the cam- era, gathers the pixel data, and saves a picture before transmission starts. How does the MSP430 do this? The pictures have a resolution of 176 × 144 pixels. To save one picture, the controller needs about 26 KB of mem- ory. But only 2 KB of RAM is avail- able, right? Well, you can reprogram the MSP430’s internal ROM (48 KB of flash memory). About 100,000 writing cycles are typically allowed, and that was enough for my application. The camera offers two working modes, Master (default) and Slave. In Figure 4—The DC motors are controlled by an H-Bridge. Because of the low power consumption of the DC Master mode, the internal logic of the motors, a 74ABT126 works as a power stage. Two stages are connected in parallel, so the maximum output cur- camera chip sends the pixels as an rent is about 100 mA. That’s enough for the motors. The photo interrupter serves for revolution detection and dis- tance measurement. The MSP430 counts every light ray interrupt for motor revolution measurement. endless datastream to the parallel port Y[0..7] (black and white camera). The One solution is the SX28 micro (cam- chip gets an external clock and timing typical pixel clock time is about era in Master mode), which Rowe, signals from the MSP430. With these 112 ns long. This time is too short to Rosenberg, and Nourbakhsh describe in signals the MSP430 controls the camera capture the data bytes from the Y port their paper, “A Simple Low-Cost Color chip. Now there is enough time to store into the MSP430 memory. Vision System.” [1] In Slave mode, the the picture in flash ROM (see Figure 6).

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 27 Figure 5—The heart of SOPHOCLES is the MSP430148 microcontroller. An 8-MHz crystal clocks the MSP430 device. The JTAG interface, which is used for programming and debugging, is available via a JP3 connector. JP4 connects the CMOS camera to the CPU.

GAS DETECTOR built in. One of these stays in contact CONTROL SOFTWARE There are several gas sensors avail- with the air, and the other is in air- The robot is not only useful for able, and most of them use a heated tight packaging. The difference serious applications, it’s also fun, crystal for detection. The crystal’s between the channels is the value for which is important too. Therefore, electrical resistance depends on the detection of bad or poison gases. the control software should be easy gas concentration. It’s easy to and understandable for everyone, measure concentration of poison- especially for kids. ous gases like CO2, NO, and CO, The control software runs on a but the crystals must be heated. Y data normal PC, and all you need is The heating time lasts about two a small radio box to get the sig- PCLK minutes with a heating current of MSP430 nals from the robot. Various VSYNC 150 mA, which is too much. Solar power buttons and throttles give you HSYNC I had to design a new sensor, so RESET full control of the robot when I looked for an optical detector OV6120 power is available or sunlight (see Figure 7). The light absorp- I2C Bus hits the solar cells. In addition, tion depends on the different it’s easy to make short slide gases in the air, and the changing Motor, power supply, radio, sensor shows from the pictures cap- of the proportions changes the SOPHOCLES tured by the robot. Each session optical density. can be saved on a disk and I used the MSP430’s high-preci- Figure 6—The relationships among the MSP430, CMOS camera, and played in the Robot Control peripheral devices are demonstrated here. The MSP430 controls the sion A/D converter in combina- Center, which is shown in camera via an I2C interface. The video data is captured as 8-bit val- tion with a multicolor LED. Two ues, and it should be synchronized by several clock signals (i.e., Photo 3. The software and sam- identical optical channels were PCLK, VSYNC, etc.). ple missions are available.

28 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Figure 7—The sensor unit consists of the gas sensor (multicolor LED and TSL250 photo sensor) and bumpers (microcontroller switches for edge detection). A third sensor for voltage measurement is placed in the power supply unit (R27, C7).

PRICE AND PERFORMANCE REFERENCE The fact that SOPHOCLES is both small and powerful illustrates the [1] A. Rowe, C. Rosenberg, and I. possibilities of modern technology. By Nourbakhsh “A Simple Low combining a high-performance micro- Cost Color Vision System,” controller with less power consump- www-2.cs.cmu.edu/~cmucam/. tion and other electrical components, I came up with a robot that’s both RESOURCES interesting and useful. J. Altenburg and U. Altenburg, Building the robot was an expensive Mobile Roboter, Carl Hanser endeavor, but it was cheaper than you Verlag, München, 2002. might expect. You can purchase the camera for about $60 and the motors J. Labrosse, MicroC/OS-II, R&D for $70. Notably, the powerful Books, Lawrence, KS, 1999. MSP430 is the least expensive of the R. Man and C. Willrich, “A main components. I Minimalist Multitasking Executive,” Circuit Cellar 101. Jens Altenburg is a project leader at Software & Systeme Erfurt GmbH SOURCES in Germany. He studied information technology at the Technical LTC3401 University of Ilmenau, Germany and Linear Technology Corp. qualified as an engineer in 1990. His (408) 432-1900 interests include microcontroller www.linear-tech.com technology, electronics, mechanics, BiM 433 and software. You may reach him at Radiometrix, Ltd. [email protected]. +44 0 20 8428 1220 www.radiometrix.com

PROJECT FILES MSP430 Microcontroller To download the code, go to Texas Instruments, Inc. ftp.circuitcellar.com/pub/Circuit_ (800) 336-5236 Cellar/2002/147/. www.ti.com www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 29 enjoys fun projects, you’d give it a try, wouldn’t you? Besides, an idea as bril- FEATURE liant as this spells dot-com startup, and more importantly, Tom will have ARTICLE a candle for his play! MAKE IT CONVINCING Philip Ching & Bruce Land If you’d like your own candle too, you’re in luck because we’re going to tell you how we did it. Building a can- dle is challenging because it consists of three smaller projects: designing the flame dynamics, adding the breeze Light the Way sensors, and packaging the candle. Our primary concern was to make the candle’s LED be convincing An LED-Based Alternative enough to pass for a real flame. What must be considered so that the candle looks real? Well, the candle must have time-variable light output. Anyone who looks at a candle flame will notice that it’s not always periodic, but seems to have a random component. o you remember The candle also must have breeze d the theme to the sensors. A candle flame dances when Sorcerer’s Apprentice subjected to light breezes, or blows in Disney’s Fantasia? out when the breeze is too strong. In One of the more memorable images addition, everything must be in real Actors get paid big in Fantasia is that of the sorcerer’s time. How convincing would a can- apprentice as performed by Mickey dle look if you blew on it, and the bucks to feign abstrac- Mouse. Now, inside any self-respect- flicker dynamics changed three min- ing sorcerer’s study, you’ll probably utes later? Not convincing at all, tions such as happi- find candles, which provide light for that we can tell you! Last but not the sorcerer to read his book of spells least, the packaging should be made ness. But when it well into the late hours of the night. to look like a real candle. comes to imitating the However, if you have a background in theater, or at least some common FLAME DYNAMICS physical world, sense, then you know that bringing We wanted to simulate the flame an open flame onstage probably isn’t dynamics by using time-variable light Hollywood looks to such a good idea. This is especially output to match the statistics of a real true if you’re around children, unless flame without having to worry about engineers. Philip and you enjoy regular visits from the fire dynamics such as turbulence. After department. Therefore, an open several searches on the Internet, we Bruce describe how flame is one prop you can most like- found an article written by Fujiwara they faked a flame and ly do without. and Kiyozawa called the “Spectral During the fall of 2001, we spoke Model and Statistical Parameters of illuminated an audi- with this fellow from Cornell University’s Neurobiology and ence with a real-time Behavior department named Tom. He Flat mentioned he was participating in a LED-based candle. play and that he wanted to use a can- ≈ 1 Log (power) ƒ2 dle for added effect. However, as we mentioned, having an open flame onstage isn’t a good idea. But what if Cutoff: 0.0185 Hz we could build a candle for him, one Log (f) that used an LED that looked convinc- ingly like a real flame? If you were a Figure 1—Take a look at the time-variable light output. problem solver, or a person who The flame dynamic follows this pattern.

30 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Biostimulation with 1/f flickering as a result of a Fluctuation Power.” [1] breeze as unfiltered white Don’t be intimidated by noise that’s proportional the title, which sounds to blow, in addition to rather technical. Unlike the modification to ISCALE, many of the papers out which we’ll explain next. there, the article was actu- The brightness variable ally quite readable. controls the pulse width The authors found that modulator hardware in the flame dynamics follow the Atmel AT90S8535 a flat power spectrum at microcontroller. When low frequencies and fall the PWM mode is select- off at 1/fn power spectrum ed (Timer 1/Counter 1), with n = 2.12 ± 0.7 at the output compare reg- higher frequencies (see ister 1A (OCR1A) forms Figure 1). The variable n a dual 8-bit, 9-bit, or 10- Figure 2—The final circuit for the candle is based on the Atmel AT90S8535. that Fujiwara and bit free-running, glitch- Kiyozawa found is not dis- free, and phase-correct tinguishable from the slope of a one- Alpha, α, serves as a weight. A PWM with outputs on the port D5 pole, low-pass filter. A simple low- smaller alpha will place more empha- pin. [4] The port D5 pin directly pass filter has a slope of 2.0. Because sis on the white noise input, imply- drives the flame LED. real candles seem unpredictable, we ing a higher cutoff frequency of the tried passing white noise through a low-pass filter. Alpha is calculated as BREEZE SENSORS digital low-pass filter to produce simu- follows: The detection of breezes in the envi- lated candlelight. ronment is accomplished by imple- We generated white noise by using a [2] menting a thermistor (see Figure 2). random number generator that was The principle behind a thermistor is written in C and adapted from Brian Alpha is a measure of how much the that the resistance changes as a func- Kernighan and Dennis Ritchie’s book signal would decay if the filter’s tion of temperature. As the thermistor The C Programming Language: ANSI impulse response were exponential heats up, the resistance decreases; the C Version. [2] The excerpt of code in with a time constant of τ. In resistance increases when there’s a Listing 1 was taken from the final pro- Equation 2, ∆t is equal to 64 ms in decrease in temperature. Enough cur- gram. A uniformly distributed number our code, which determines how often rent will heat the thermistor above between –0.5 and 0.5 is generated, the new number to set the intensity of ambient temperature. with an average value of zero. the light is calculated. The 0603 surface-mount thermis- The following equations were used The complete new number to set tor we used requires 3 mW to heat it to calculate the new number to set the the intensity of the light is calculated 1°C. We picked a DC current so that intensity of the light. A single-pole as follows: the temperature was approximately low-pass filter was modeled as: 50°C. Because it’s self-heated, a gen- ≡ New brightness (zt+1 × Iscale) + tle breeze cools the thermistor so α α [3] zt+1 = zt + (1 – )w [1] Ioffset + (blow × w) that the resistance increases and the voltage across the 100-Ω resistor

Equation 1 was adapted from Samuel where ISCALE sets the standard devia- decreases. The voltage read by the Stearns’ book Digital Signal tion of the filtered white noise, and 8535 ADC value is represented by

Analysis. [3] In the equation, zt is the IOFFSET sets the average intensity. The 8 bits; it’s approximately 20 mV per filter output at time t with an initial last term depends on a breeze sensor bit. We read a change in voltage of value of zero at t = 0. And w is the to supply a variable blow, which rep- around 50 mV for a breeze caused by white noise input. resents the wind speed. We modeled blowing on the sensor. The blow variable depends linearly on the change in voltage read by the ADC.

Listing 1—For this excerpt of code, next is an unsigned long int, and finalRandomNum is a float. PACKAGING next = next * 1103515245 + 12345; Because the candle was destined randomNum = (unsigned int)(next/65536) % 32768; for the stage, several people who finalRandomNum = randomNum; looked at the prototype suggested finalRandomNum = finalRandomNum/32767 - 0.5; that the candle would appear more realistic if the circuitry and wiring were hidden from sight.

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 31

eters that looked convincing in a breeze between the change in voltage and the parameters: I_scale, alpha, and blow. With increasing breeze strength, I_scale and alpha decreased while blow increased. The combina- tion of parameter changes makes the flame appear to flicker faster and more randomly.

PROGRAM THE ’8535 The coding for the AT90S8535 was completed using the CodeVision AVR Photo 1—The LED-based candle burns brightly! If C compiler for Atmel. You may down- you look closely, you’ll notice that it’s an LED and not a real flame. load the final version of the code from the Circuit Cellar ftp site. So, we used a cardboard shipping CodeVision offers several versions tube approximately two inches in of its compiler, which include a free diameter, and cut it to about 7″ in downloadable evaluation version as height. The circuitry and the battery well as a commercial version. The pack were hidden inside, with the bat- difference between the two is that tery pack sitting at the bottom to the free version will not allow you to serve double duty as a stabilizing program the chip when the file size weight. In addition, we applied three exceeds the preset limit and lacks coats of white semi-gloss paint so that some libraries. For our candle proj- the exterior looked waxy, which gives ect, we needed to purchase a license the added effect of looking like a real for the commercial version for its candle. Lastly, the LED was lightly size and libraries. sanded to diffuse the light and covered Because we used the built-in with frosted tape. We cut the tape into CodeWizard automatic program gen- the general shape of a flame. erator, we were able to write all of the code needed for implementing a ADDITIONAL DETAILS great many of the functions (e.g., The basic operating principle is sim- input/output port, timers/counters, ple. At start-up, continuously compare and A/D converter initializations) in the current ADC value to the last five a matter of minutes. The built-in in- ADC values. If there are at least three system AVR programmer is compati- matches with the history table, then ble with the Kanda Systems the current ADC value becomes the STK200+ development board we

VZERO value. The VZERO serves as a base used, with automatic programming to compare future voltage changes in after successful compilation through the system. This scheme compensates the parallel port of the PC. for variability in the thermistor and background air motion. Why did we choose five previous values instead of more (or less)? Four and fewer values did not give a good

VZERO. We wanted the system to have

as accurate a VZERO value as possible, but not stall in the start-up state on the condition when the ADC value bounces between two values. At ini- tial start-up, the thermistor heats up and the ADC changes in one direction only in a still-air environment. After the V value has been ZERO Photo 2—With this view from above, you can see the obtained, we continuously read the LED flame with the thermistor, which is the little black ADC value. We found a set of param- dot on the right.

34 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com After programming the ‘8535 on the Engineering at Cornell University. He STK200+ board, it was taken off and received a BS in physics from Harvey placed in a 40-pin ZIF socket. Taking Mudd College in 1968 and a Ph.D. in the chip off the board is not a difficult neurobiology from Cornell University task; it requires a crystal, a few capac- in 1976. Currently, Bruce teaches two itors, and a resistor to run, in addition neurobiology and behavior courses to the correct supply voltage. and one electrical and computer engi- neering course at the university. PUT IT TOGETHER When time allows, he does some neu- Take a look at Figure 2 to see what ral modeling. You may reach him at the circuit looks like when its com- [email protected]. pleted. The breeze sensor is located on the top right. You can see the LED PROJECT FILES on the bottom left. The rest of the components are added so that the To download the code, go to AT90S8535 can run off the develop- ftp.circuitcellar.com/pub/Circuit_ ment board. The components are fair- Cellar/2002/147/. ly easy to obtain at a local electronics store. What isn’t shown in Figure 2 is REFERENCES the 6-V battery pack (consisting of four AA batteries), switch, resistor, or [1] O. Fujiwara and Y. Kiyozawa, “Spectral Model an additional LED to indicate that the and Statistical Parameters power is on. of Biostimulation with 1/f Fluctuation Power,” A CLOSER LOOK Electrical Engineering in Refer to Photo 1 and Photo 2 for Japan, vol. 121, no. 4, 1997. snapshots of the final candle. The [2] B. Kernighan and D. candle looks real, but in order to do it Ritchie, The C true justice, you need to see it in per- Programming Language: son or in the soon-to-be-available ANSI C Version, Prentice online movie featuring it. Hall, Englewood Cliffs, NJ, 1998. FUTURE WORK [3] S. Stearns, Digital Signal According to several people, our Analysis, Hayden Book candle looks convincingly real. If Company, Inc., Rochelle time permits, we’ll measure the out- Park, NJ, 1975. put spectrum; however, there’s always [4] Atmel Corp., “8-bit AVR room for upgrades. One such upgrade Microcontroller with 4K/8K would involve sensitivity controls. Bytes In-System Depending on whether or not a cer- Programmable Flash— tain, say, button is pushed, the candle AT90S4434, AT90LS4434, may be more sensitive to breezes in AT90S8535, AT90LS8535,” the environment. Another variation rev. 1041C, November 1998. would involve changing the uniform white noise to Gaussian white noise. We hope to implement these SOURCES changes in the near future. I AT90S8535 Microcontroller Atmel Corp. Philip Ching received both a BS and (408) 441-0311 MS in Electrical Engineering from www.atmel.com Cornell University in 2001. His inter- CodeVision AVR C compiler ests include computer engineering Dontronics and digital VLSI. You may reach him www.dontronics.com/cvavr.html at [email protected]. STK200+ development board Bruce Land is a senior research asso- Kanda Systems ciate in Neurobiology and Behavior +44 (0) 1970 621030 as well as Electrical and Computer www.kanda.com www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 35 tation of the desired waveform. In order to generate the analog signal, the FEATURE discrete point-by-point version of the waveform is played in a sequential ARTICLE manner through the generator’s digi- tal-to-analog converter. [1] David Prutchi & Commercial arbs are either stand- alone units or PC add-in cards that typi- Michael Norris cally include high-speed memory and D/A converters to generate one or more arbitrary wide-band waveforms. The complexity of high-performance memo- ry and D/A circuitry, as well as the pro- prietary nature of the software used to Convert Your PC Sound Card design and download waveforms, has kept the price of arbs out of the range of most hobbyists. But it doesn’t have to Make a DC-Coupled Arbitrary be that way, especially if your applica- tion has a bandwidth limited to a few Waveform Generator kilohertz, because $10 worth of hard- ware will turn your PC into a low-fre- quency, precision DC-coupled arb.

ARB IN YOUR PC By the definition above, the PC sound common prac- card is a true audio-range arb; it takes a tice in evaluating the waveform definition stored in the the behavior of signal computer’s memory and plays it back Many consumer-grade processing or control cir- as an analog signal in the range of cuitry is to make use of an analog 20 Hz to 20 kHz. The simplest way of sound cards are insuf- function generator to produce the nec- generating an audio-range arbitrary essary test input signals. The typical wave through the PC sound card is to ficient for inducing sig- cookbook waveforms of the function store it as a .wav file and play it back generator are then used to investigate using Windows’ Media Player utility. nals that have low-fre- the behavior of the circuit when stim- Unfortunately, the typical 20-Hz quency or DC compo- ulated by sine, square, and triangle high-pass cutoff frequency and uncali- waves of different amplitude and fre- brated output level of consumer-grade nents. However, with quency. In most applications, howev- sound cards makes them unsuitable er, repetitive sine, square, and triangle for simulating signals that have low- the right software, a waves are seldom representative of the frequency or DC components. In signals that the equipment being test- addition, the output stage of sound PLL circuit, and a little ed is designed to process. For example, cards doesn’t usually have the output the heart’s electrical signal that’s linearity or passband flatness know-how, you can acquired and processed by cardiac bio- required for the accurate reproduc- convert your PC sound medical equipment is a waveform tion of low-frequency signals. consisting of a complex mixture of In spite of this, a phase-locked loop card into a precision these basic wave shapes intertwined (PLL) circuit and some software can with intermittent baseline segments. turn a sound card into a precision DC- DC-coupled arbitrary The same is true for automotive con- coupled arb. The idea is to use a soft- trols, video, radar, and most other ware FM modulator to turn the arbi- waveform generator. real-world applications. trary signal to be generated into an Enter the arbitrary waveform gener- audio tone that’s played through the ator (also known as an arb). This PC sound card. The tone’s frequency device is a generator capable of direct- varies as a function of the desired arbi- ly synthesizing an arbitrarily complex trary signal. The arbitrary signal (with analog signal from digital data. It has all of its low-frequency and DC compo- memory at its core, which contains nents) is then recovered by hardware the full time-domain digital represen- FM demodulation of the audio signal.

36 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com .WAV FILES A .wav file is a series of samples Offset Length Contents preceded by a header that tells the 0 4 bytes RIFF player program important things like 4 4 bytes , where 8 is the length of the first two entries the sampling rate and number of bits (i.e., the second entry is the number of bytes that follow in the file) in the sample. The player program 8 4 bytes WAVE reads the header, sets up the sound Table 1—The .wav file format starts with the Resource Interchange File Format (RIFF) header, which identifies the card, and then feeds the samples to data as that belonging to a sound wave. the card’s digital-to-analog converter. PC multimedia data is often encod- All numeric data fields are in the signal (20 Hz to 20 kHz) capable of ed in the Resource Interchange File Intel format of low-high byte (usually directly driving 8-Ω speakers with 2 W Format (RIFF). RIFF is based on referred to as “little endian”). Eight- of power. The actual output level is chunks and sub-chunks. Each chunk bit samples are stored as unsigned uncalibrated and will depend on the has a type, represented by a four-char- bytes, ranging from 0 to 255. Sixteen- settings of the volume lever, which acter tag. This chunk type comes first bit samples are stored as two’s-com- you can access by double-clicking in the file, followed by the size of the plement signed integers, ranging the speaker icon in the Windows chunk, and then the contents of the from –32,768 to 32,767. tray. The only way to set the ampli- chunk. The .wav format is a subset of If you’re a Matlab user, you can avoid tude to a known voltage is by observ- RIFF used for storing digital audio, the hassle of file formatting by directly ing the waveform on an oscilloscope. and it requires two kinds of chunks: playing a datastream from within the Because sound cards are meant to format (fmt) and data. The former Matlab environment using the sound output sound, the volume control describes the sample rate, sample command. Matlab can also write .wav usually has a limited number of dis- width, and so on. The latter contains files from data variables, or read the crete steps (e.g., 16) that follow a the actual samples. .wav file PCM-encoded signal into data two-part logarithmic curve. The .wav format can also contain that can be manipulated by Matlab. any other chunk type allowed by RIFF, Another possibility is to use a profes- DATASTREAM CONVERSION including list chunks, which are used sional waveform design package, such Matlab has a function, vco.m, to contain optional kinds of data such as the Pragmatic Instruments which simulates the operation of a as the copyright date and the author’s WaveWorks Pro, to create the desired voltage-controlled oscillator (VCO)— name. Chunks can appear in any order. signal. You can then use software that’s essentially, an FM modulator. The In its simplest form, the .wav format freely available on the Internet that can code in Listing 1 shows how easy it is starts with the RIFF header depicted in play data written in plain ASCII to use this function to generate an FM Table 1. The .wav specification sup- straight through the PC’s sound card. signal by modulating a carrier (of fre- ports a number of different compres- For example, the David Sherman quency FC) with an arbitrary signal sion algorithms. The format tag entry Engineering SoundArb V.1.02 (saset- contained in vector x (sampled at a in the fmt chunk indicates the type of up.exe freeware for Windows 9x/NT) rate FS of more than twice FC, and compression used. A value of one indi- is a free PC sound card signal genera- with an amplitude range of ±1). cates linear pulse code modulation tor program that not only lets you You can use the following Matlab (PCM), which is a straight, or uncom- select standard waveforms, but also command to look at the spectrum of pressed encoding of the samples, which load and play arbitrary waveforms the FM signal that’s played through is the exact amplitude of each sample. from a text wave table file with full the sound card: The fmt chunk describes the sample control over frequency, amplitude, format (see Table 2), and the data and trigger mode. [2] specgram(y,512,Fs,kaiser(256,5),220) chunk contains the sample data, as you The output jack of a typical sound can see in Table 3. card carries an amplified AC-coupled If you aren’t a Matlab user, you can write a program to generate the FM signal from the arbitrary waveform by Offset Length Contents remembering that an FM signal, s(t), 12 4 bytes fmt is expressed by: 16 4 bytes 0x00000010, which is the length of the fmt data (16 bytes) 20 2 bytes 0x0001, which is the data encoding format tag: 1 = PCM 22 2 bytes , which defines the number of channels: 1 = mono, 2 = stereo 24 4 bytes , in samples per second (e.g., 44,100) 28 4 bytes , sample rate × block align where m(τ) is the modulating signal 32 2 bytes , channels × bits/sample/8 (the arbitrary waveform), fC is the car- 34 2 bytes , 8 or 16 rier frequency, AC is the carrier ampli-

Table 2—The format (fmt) chunk of a RIFF file describes the sample rate, sample width, and other important tude, and kf defines the frequency parameters about the way in which the wave file data is encoded. deviation caused by m(τ). The instan-

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 37 taneous frequency of the signal is larg- er than the carrier frequency when the Offset Length Contents signal m(τ) is positive; it’s smaller τ when m( ) is negative. 36 4 bytes data 40 4 bytes FINALLY, THE DEMODULATOR 44 Bytes needed for data The circuit in Figure 1 is used to For multichannel data, samples are interleaved between channels: demodulate the FM signal from the sample 0 for channel 0 sound card, which is AC-coupled by sample 0 for channel 1 C17 and amplitude-limited by IC1D. sample 1 for channel 0 Then, an NE565C PLL IC demodulates sample 1 for channel 1 ... the FM signal. The PLL tracks the incoming carrier signal and internal- where channel 0 is the left channel and channel 1 is ly estimates the signal based on the the right channel. frequency of its internal VCO set by The sample data must end on an even byte boundary. R2, R4, and C2. The error between the actual carrier frequency and the Table 3—The data chunk of a RIFF file contains the actual signal samples. estimate is the data signal when the PLL is locked. tape recorders—an application that A Maxim MAX280 switched-capac- A suitable FM frequency deviation uses the same FM modulation/ itor filter IC is used to remove resid- for this circuit is ±40%, which demodulation schemes. ual carrier-frequency signal compo- allows the bandwidth of the arbitrary The loop output of the PLL IC is fed nents from the desired waveform. signal to be reproduced to be approxi- into a unity-gain differential amplifier This IC is a fifth-order, all-pole, low- mately 18.5% of the carrier frequen- (IC1C). The common-mode rejection of pass filter with no DC error, making cy. Table 4 shows the signal repro- this amplifier is used to eliminate DC it an excellent choice for processing duction characteristics for some of and high-frequency carrier components low-frequency signals. The filter IC the standard frequencies used in FM present at the output of the PLL. uses an external resistor (R9) and

Figure 1—This PLL-based FM demodulator is used to generate DC-coupled signals from FM modulated signals generated through the PC sound card. IC1D is a limiter for the input signal. IC2 is the PLL. The common-mode rejection of IC1C eliminates DC and high-frequency carrier components present at the output of the PLL. IC3 is a fifth-order, all-pole, low-pass filter with no DC error used to remove residual carrier-frequency signal components from the desired waveform. IC1A adjusts the gain of the circuit and removes any offset introduced by the preceding stages.

38 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com

Listing 1—The Matlab program uses the vco.m function to generate an FM signal by modulating a carri-

er (of frequency FC ) with an arbitrary signal contained in vector x sampled at a rate FS.

Fs = 5000; % Select arbitrary signal sampling frequency in Hz Fc = 1687; % Select VCO carrier frequency in Hz moddev = 40; % Percent FM frequency deviation y = vco(x,[1-moddev/100 1+moddev/100]*Fc, Fs); % VCO simulation sound(y,Fs) % Play modulated signal through PC sound card

capacitor (C10) to isolate the fourth- amplitude response, the clock should order filter implemented within the be 100 times the desired cutoff fre- IC from the DC signal path. The quency. The filter has a cutoff fre- external resistor and capacitor are used quency ratio of 100:1. The internal as part of the filter’s feedback loop, and oscillator runs at a nominal frequency they also form one pole for the overall of 140 kHz that can be modified by filter circuit. The values of these com- connecting an external capacitor ponents are chosen such that: (C11) between pin 5 and ground. The clock frequency is given by:

9 × 10 11 where R9 should be around 20 kΩ. Now, for the Matlab code in Listing 1, the demodulated signal bandwidth For the example where the cutoff

is expected to be: should be approximately 300 Hz (fCLK = 30 kHz), C11 would be 120 pF. A

18.5% × FC = 18.5% × 1687 Hz = 312 Hz series resistor (R18) can be added to trim the oscillation frequency. In this which is where the –3-dB cutoff fre- case, the new clock frequency is quency for the low-pass filter should given by: be placed. Selecting the closest stan- dard-value components, R9 = 18.2 kΩ and C10 = 0.047 µF, the –3-dB cutoff – × 18 × 11 × will be 301 Hz. An internal clock that determines the filter’s cutoff frequency drives the where chip’s internal four-pole switched- capacitor filter. For a maximally flat

is the oscillator frequency when R18 is not present (it’s obtained through the prior equation). After filtering, the gain is adjusted through R10, and the offset from the preceding stages is com- pensated with IC1A by setting R3. Lastly, the RC low-pass filter formed by R5 and C6 removes any Photo 1—A real ECG signal that was digitized at a sampling rate of switching noise intro- 5kHz (a) is used to frequency-modulate a 2-kHz carrier using the duced by IC3. Matlab vco.m function (b). The output of the PLL-based FM demodu- lator is shown in (c), depicting how the demodulated signal faithfully The stability of the PLL reproduces the DC offset and low-frequency components of the ECG. circuit depends on the

40 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com

bo st on

Register by October 21st and November 18 – 21, 2002 save up to $400. Hynes Convention Center Boston, MA connect you develop network

The East Coast’s premier event dedicated to processor-based systems development and technologies

> Learn about the latest technologies in 70 classes and 8 full-day tutorials on program- ming, real-time and object-oriented design

> Network and share ideas with fellow developers and industry experts

> Preview the latest products from 125 embedded hardware and software vendors

Visit our website to preview the conference program and register online.

w w w .em be dded.com/esc

Conference Sponsors:

Priority Code: LAR Table 4—Here are Carrier Carrier deviation limits (for 40% FM deviation) Modulating frequency Response band limits (for 100 Hz the signal character- frequency (kHz) Plus deviation (kHz) Minus deviation (kHz) bandwidth (kHz) frequency response) (dB) istics for various standard FM tape 1.687 2.362 1.012 DC – 0.312 ±1% recorder frequencies. 3.375 4.725 2.835 DC – 0.625 ±1% 6.750 9.450 4.050 DC – 1.250 ±1% 13.500 18.900 8.100 DC – 2.500 ±1% 27.000 37.800 16.200 DC – 5.000 ±1% stability of the frequency-setting com- systems do. The U.S. Army’s Inter- David Prutchi is vice president of ponents. Proper performance requires Range Instrumentation Group (IRIG) engineering at Impulse Dynamics, the use of low-temperature-coefficient of the Range Commanders Council where he is responsible for the devel- components with high tolerance. has established a standard, IRIG 106- opment of implantable devices Resistors should be the precision 1% 96, that covers all aspects of frequen- intended to treat congestive heart tolerance type of the RN60D variety. cy modulation (FM) and pulse-code failure, obesity, and diabetes. You And capacitors should be Mylar, poly- modulation (PCM) telemetry, includ- may reach him at [email protected]. ester film, or another type that ing transmitters, receivers, and tape remains stable with age and is not recorders. [3] Because of its success Michael Norris is a senior electronics sensitive to temperature variations. as a proven standard and the support engineer at Impulse Dynamics, where from telemetry equipment manufac- he has developed many cardiac stim- IN CLOSING turers, most commercial data acqui- ulation devices, cardiac contractility Photo 1 demonstrates the perform- sition systems also use the same sensors, and physiological signal ance of the technique. The test signal IRIG standard channels. acquisition systems. He can be reached in Photo 1a is from an electrocardio- The IRIG standard specifies ways at [email protected]. gram (ECG) that was digitized at a of performing frequency division sampling rate of 5 kHz with 12-bit res- multiplexing (FDM) over a telemetry olution. In Photo 1b, you can see the channel (i.e., how to generate a com- REFERENCES spectrum of the FM signal. Photo 1c posite signal consisting of a group of [1] D. Prutchi, “Digital shows how the demodulated signal sub-carriers arranged so that their Generation of High-Frequency faithfully reproduces the DC offset and frequencies do not overlap or inter- Waveforms,” Circuit Cellar low-frequency components of the ECG. fere with each other). Various FM 84, July 1997. Because the sound card output is sub-carrier and deviation schemes [2] D. Sherman, “Program Turns in the audible range, the modulated are available to accommodate differ- PC Sound Card into a signal can be transmitted to the ent channel needs. Function Generator,” EDN, demodulator via a voice radio or For a consumer-grade sound card, September 2, 1999. telephonic link for remote signal the maximum sampling rate is [3] Range of Commanders generation. To do so, however, the 44.1 kHz, which imposes an absolute Council (Inter-Range tone frequencies produced by the maximum tone frequency limit of Instrumentation Group), IRIG sound card for a full-scale input around 18 kHz, which ultimately Standard 106-96, must be limited to the band-pass of constrains the number of channels jcs.mil/RCC/index.htm. the communications channel. For a that can be simultaneously repro- plain telephone line, this range is duced with the FM carrier technique. 400 Hz to 3 kHz, while a commer- Still, selecting channel bandwidths SOURCES cial FM audio link is specified to proportional to their carrier frequen- SoundArb 1.02 cover the 30-Hz to 15-kHz audio cies can accommodate many chan- David Sherman Engineering Co. bandwidth. Another interesting pos- nels of differing bandwidth. www.wavebuilder.com/Index.htm sibility is to use a small 1:1 audio For example, multiple physiological isolation transformer and a floating signals with different bandwidth Matlab power supply to turn the demodula- requirements can be simultaneously MathWorks, Inc. tor into an isolated output stage. generated. A sound card’s bandwidth (248) 596-7920 Lastly, you should note that the suffices to simultaneously generate a www.mathworks.com full bandwidth of a single sound card skin conductance signal simulation MAX280 channel could be shared by multiple through an 11-Hz bandwidth channel. Maxim Integrated Products, Inc. software modulators occupying sepa- A brainwave signal (EEG) can be repro- www.maxim-ic.com rate audio bands to convey various duced through a 45-Hz bandwidth simultaneous low-frequency signals channel, while a 3-lead wideband elec- WaveWorks Pro to an array of PLL demodulators. trocardiogram (ECG) can be reproduced Pragmatic Instruments, Inc. This is exactly what FM telemetry through three 1-kHz channels. I (858) 271-6770

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 43 Table 1 shows how the signals match up between the SED133x on FEATURE the left and a typical display (e.g., a Hitachi SP14Q002) on the right. ARTICLE Now that you’re ready to connect your display to the SED133x controller, Roberto Ferrabone another set of problems is waiting. The SED133x offers a rich set of text modes, giving you the ability to choose between an internal 5 × 7 pixel font and external RAM-based 8 × 8 or 8 × 16 fonts. However, this never matches with the requirements of the cus- Choosing Your LCD tomer, who might need the characters to be a bit taller or wider. What if a customer wants to be able to write the contents of the Bible in a single pixel? At this point, your only choice is to use the graphical mode of the screen, which gives you the ability to build characters and icons in the dimen- sions that best fit your needs.

GRAPHICAL CHOICE Choosing the graphic mode was like n my part of a spring rain for software people, who Italy, there wasn’t immediately began to build an elabo- i enough snowfall this rate architecture of data structures, Choosing the right year to fill the landscape structures of pointers, and so on. After or skyline. But on one cold morning spending some time debugging the ini- LCD and controller during the Christmas holiday, a differ- tialization routines, I was rewarded ent kind of snow filled my mind. with animated icons along with charac- can be difficult, espe- In many applications, I use graphic ters of every possible height, width, displays for building portable and shadow, and focus. However, I found cially when their signal fixed devices. One controller that fits that if I looked at the screen from cer- names don’t match up. all of the different LCD sizes and tain angles, especially when there was a interface types, especially the larger lot of white on the screen, drawing new But, as Roberto ones, is the Seiko SED1330 and its items created a strange dot that wan- derivatives. The LCD maker usually dered across the display. explains, it doesn’t integrates the controller (e.g., the This instigated an exasperating SED133x or another) by soldering it struggle to find a set of initialization have to be a major directly onto the LCD board or offers parameters that would eliminate the the same LCD without a controller. I snow. I tried increasing and decreasing problem. In this article, prefer the latter version because it the TC/R count to maximize the time he will show you how seems to be better in terms of elec- that refresh was inactive, but there tromagnetic compatibility. With the was always some angle from which to pick the appropriate integrated controller, you have to the flickering dot would appear. bring the CPU bus through a flat I consulted the SD133x datasheet devices for your own cable to the display. This creates and tried solutions suggested by the longer bus traces and poorly defined manufacturer. According to the applications. bus timing. datasheet, display flicker may occur if After you’ve chosen the LCD, the there is more than one consecutive next step is selecting the right con- access that cannot be ignored within a troller to generate the interface sig- frame. I also learned that the micro nals. Here’s where the problems begin, could minimize this by either per- because the display that you select forming these accesses intermittently often has signal names that differ or continuously checking the status from those on the controller. flag (D6) and waiting for it to become

44 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com high. All that the factory could sug- gest was to make updates more and Display read cycle more slowly to avoid the problem. I slowed all the way down to one access per frame, but this means that if Ø0 you need to refresh the entire screen, *VCE you had better plan to get a cup of cof- fee (and not an Italian espresso). The alternative is to actively moni- VA Character Graphics Character general tor the busy status of the SED133x read read read and make accesses only when it’s idle. A driver that implemented this proto- col was soon ready for testing, but incredibly, there was still an occasion- LP al flicker on the display! What happened? A simple session XSCL with an oscilloscope showed the terri- ble effects of an interrupt occurring 5 × 9 × Tosc Display memory write time 2 × 9 × Tosc between the status read and the dis- play data write. Essentially, the write Figure 1—The SED133x timing keeps the display memory completely busy during the active portion of each delay cycle would fall well outside the win- line. There’s only a small window of clock periods ((TC/R – C/R – 7) × 9) for display updates between lines. dow allowed for interference-free access (see Figure 1). of the software, so I decided it was time following sequence: character read, Digging deeper into one of the to build a simplified emulation of the graphics read, and character generator numerous datasheets for the chip, I dis- SED1335 in a Xilinx Spartan FPGA that read. This doesn’t vary, even if you covered another suggestion that was would eliminate its constraints. aren’t using the character plane and even more restrictive. You need to wait fonts (internal or external); moreover, 5 × 9 Tosc periods before considering BUILT AT HOME each read cycle is long compared to the bus free, and you have to complete A look at the SED1335’s display modern RAM access times (250 ns) your access at least 2 × 9 clock periods refresh timing convinced me that this using an 8-MHz controller clock. before the next line starts. would not be difficult. The SED1335 applies three clock It became clear that it wasn’t going During the active part of the scan, cycles per memory cycle, using one to be possible to reconcile the limita- the SED1335 controller generates a full clock period as idle time between tions of the controller with the needs continuous series of RAM cycles in the cycles and two clock periods (250 ns

SED133x SED133x function SP14Q002 SP14Q002 SP14Q002 pin name pin number pin name function

XD0–XD3 4-bit X-driver (column drive) data outputs. Connect these outputs to the inputs of the 1–4D0–D3 Data display X-driver chips. XSCL The falling edge of XSCL latches the data on XD0 to XD3 into the input shift 9 CP Data shift registers of the X-drivers. To conserve power, this clock halts between LP and the start of the following display line. XECL The falling edge of XECL triggers the enable chain cascade for the X-drivers. Every sixteenth clock pulse is output to the next X-driver. LP LP latches the signal in the X-driver shift registers into the output data latches. LP 8 LOAD Data latch is a falling-edge triggered signal, and it pulses once every display line. Connect LP to the Y-driver shift clock on modules. WF LCD panel AC drive output. The WF period is selected to be one of two values with the system set command. YSCL The falling edge of YSCL latches the data on YD into the input shift registers of the Y-drivers. YSCL is not used with driver ICs that use LP as the Y-driver shift clock. YD Data pulse output for the Y-drivers. It’s active during the last line of each 6 FRAME First line marker frame and shifted through the Y-drivers one by one (by YSCL) to scan the display’s common connections. YDIS Power-down output signal. YDIS is high while the display drive outputs are active. YDIS 5 Display off High = on goes low one or two frames after the sleep command is written to the SED1335 Low = off series. All Y-driver outputs are forced to an intermediate level (deselecting the display segments) to blank the display. In order to implement power-down operation in the LCD unit, the LCD power drive supplies must also be disabled when the display is disabled by YDIS.

Table 1—When using an external controller, carefully match up the signals between the controller and the selected display (e.g., the Hitachi SP14Q002 shown here). www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 45 to start in state 7 or read and write signals, one bit of Display read cycle 8, it would interfere address (selects between command and with the graphics data registers), and a chip select signal. Ø0 read access of the The Intel interface operates such next refresh cycle. If that when a Write command arrives the (the chip select is low, and then the *VCE initiates a write write signal become active), a latch while the refresh holds the state of the address bit A0. VA controller is in states On the rising edge of two internal 7, 8, 0, or 1, the signals (ISDATA or ISCOMMAND), Graphics Up to three CPU read write cycles memory cycle must two other signals are generated: NEW- be deferred until DATA and NEWCOMMAND. The lat- Figure 2—The FPGA implementation keeps the same basic display cycle timing state 2. This allows ter of the two activates the command as the SED133x, but makes only one read access to the display RAM. This the microprocessor just stored in the command register leaves time for up to three CPU writes in each cycle. to write to the mem- (ACOMMAND bus). This value is ory from one to three compared against specific commands at 8 MHz) for the actual memory times for every graphics read cycle, giv- that the FPGA recognizes; it also resets access time. Three memory cycles fully ing high performance without degrad- the counter that keeps track of the consume the nine clock cycles allowed ing the quality of the display. next set of parameter data when there for each byte of display refresh. are multiple bytes. NEWDATA stores a The emulation controller does only MICRO INTERFACE parameter byte in the appropriate regis- the graphic read cycle, and the timing is The FPGA controller emulates the ter and advances the counter. also much faster in order to maximize parts of the interface of the SED133x With regard to electrical timing, the the time available to the microproces- controllers that relate to the graphics proposed FPGA emulation is certainly sor interface (see Figure 2). The memo- mode of operation. Figure 3 shows a more attractive than the original ry cycle is reduced to two clock cycles, diagram of the FPGA implementation. SED133x (see Table 2 and Listing 1). with a half clock period of idle time and You may download the schematic from The SED133x requires a data setup 1.5 clock periods (187.5 ns at 8 MHz) the Circuit Cellar ftp site. time of 120 ns, which is much more for the memory access time. This Although the SED controllers sup- than the 10 to 20 ns required by the leaves up to six out of nine clocks (67%) port both Intel-style and Motorola- FPGA implementation (depending on of the memory bandwidth, available for style buses, I chose to emulate only the FPGA speed grade you select). interference-free display updates. the Intel mode of operation. The Although the hold time requirement Note that the microprocessor cycles interface signals are an 8-bit data bus, of 10.799 ns is a bit longer than the shown in Figure 2 aren’t SED controller’s specifica- real CPU bus cycles; these tion of 5 ns, it shouldn’t Sheet 1 are internal accesses that Command cause any problems with A0 Command are initiated by the micro- YDIS most . *RD decode processor writing to the Sheet 3 If your application is *WR Microprocessor Parameter controller’s command and *CS interface registers more time-sensitive, the use Data data registers. The micro- D0-D7 of a global clock buffer Line Busy YD processor can complete counter (BUFG) is the correct way Byte those writes at its own *VRD to address this problem. counters pace, and it is only neces- Another way to further *VCS sary for the controller to Sheet 2 Memory improve the timing per- timimg *WVR Memory write Memory read buffer the incoming writes address formance of the system is address and resolve the access as mux VA0-14 to use an 8-bit data-trans- soon as possible. A nine- parent latch (ILD8) con- VD0-7 state counter (0 through 8) Memory write trolled by the inverted controls the refresh state data NWR signal. Use the output machine. In the active part of this as input to the data Memory read of the display, the first data and command registers. two states are used to read Because display refresh mux XD0-3 graphic data to send to the timing is not particularly LCD. The controller’s Refresh state LP critical, another benefit of Sheet 4 decode microprocessor interface is XSCL the FPGA implementation allowed to start a memory is the ability to eliminate Figure 3—The FPGA implements a subset of the SED133x logic. Sheet 1 contains the cycle during states 2 microprocessor interface and emulation registers. Sheet 2 contains the video memory an external clock alto- through 6. If a cycle were interface, and sheets 3 and 4 contain the LCD interface. gether. The internal FPGA

46 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com clock can be used, making the imple- mentation even more EMC compliant. Listing 1—This excerpt from the FPGA timing report shows the good news about the bus interface.

COMMAND SET Setup/Hold to clock $Net00004_ ------+------+------+ The FPGA emulation implements | Setup to | Hold to | just four of the SED133x commands: Source Pad | clk (edge) | clk (edge) | system set (with 8 bytes of data), dis------+------+------+ play on/off control, set cursor address, $Net00011_ | 1.641(R)| 10.799(R)| $Net00001_ | 4.590(R)| 10.549(R)| and memory write. Although the sys- $Net00005_ | 6.486(R)| 8.653(R)| tem set command only implements $Net00021_ | 0.327(R)| 2.903(R)| three of the parameter registers, $Net00023_ | 0.335(R)| 2.895(R)| they’re located in the same positions $Net00024_ | -3.641(R)| 8.223(R)| $Net00006_ | -4.100(R)| 7.936(R)| as on the SED133x in order to main- $Net00007_ | 2.523(R)| 8.270(R)| tain software compatibility between $Net00008_ | 0.672(R)| 6.785(R)| the two implementations. The param- $Net00009_ | -3.263(R)| 5.981(R)| eters supported are C/R, TC/R, and LF. ------+------+------+ The C/R parameter sets the address range covered by one display line; in other words, the number of bytes for one display line. Similarly, the TC/R are written. Clearly, this is simpler BOARD-LEVEL SCHEMATIC parameter sets the total time for a line than the four possibilities offered by The PCB schematic is simple (see (including retrace), and it must contain the SED controller (up, down, left and Figure 4). The Xilinx Spartan XCS10 a minimum value of C/R + 4. right), but I felt that the computational FPGA is in an 84-pin package. The The Set Cursor Address command capabilities of the microcontroller signals to the Hitachi SP14Q002 LCD stores the address for the next display linked to the display controller are are buffered by a 74HC244 to provide update in a counter, which increments more than sufficient to make up for greater drive for potentially long for every byte written by the Memory this. Today’s microprocessors are more cables. A Maxim MAX629 provides

Write command. This effectively powerful than the ones available when the negative VEE supply for the LCD. moves the cursor to the right as bytes the SED133x was first designed. A 10-kΩ trimmer is used to set the

Figure 4—The PCB schematic incorporates the DC/DC converter needed to provide the nega- tive voltage to the LCD.

48 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Srl. You may reach him at roberto. Speed grade –4 Speed grade –3 [email protected]. Description Symbol Minimum Maximum Minimum Maximum Setup times (TTL inputs) Clock enable (EC) to clock (IK), T 1.6 N/A 2.1 N/A ECIK PROJECT FILES no delay To download the code, go to Pad to clock (IK), no delay TPICK 1.5 N/A 2.0 N/A Hold times ftp.circuitcellar.com/pub/Circuit_

Clock enable (EC) to clock (IK), TIKEC 0.0 N/A 0.9 N/A Cellar/ 2002/147/. no delay

All other hold times TECIK 0.0 N/A 0.0 N/A SOURCES Table 2—The raw timing specifications of the FPGA promise high performance. SP14Q002 display display contrast. If the microprocessor ter registers. This will also simplify Hitachi America, Ltd. has a PWM or D/A output, it can be fil- the software driver. www.hitachi.com tered and combined with the trimmer Another interesting possibility is to MAX629 voltage in order to provide a software- mount the LCD upside-down. This Maxim Integrated Products, Inc. controlled contrast adjustment. The can be accomplished by subtracting www.maxim-ic.com PWM could also be implemented in a every address setting from 9599 (320 × spare section of the FPGA; after all, 240 – 1), swapping each bit in a byte 74HC244 Octal buffer/line driver 50% of the XCS10 is still available. (reversing the bus order reading from Philips Semiconductor Other application-specific features can the video memory, using RAMBUS[0:7] www.semiconductor-philips.com be incorporated into the FPGA as well. instead of RAMBUS[7:0]) and using a SED133x LCD controller If you need more FPGA space and down counter instead of the up counter Seiko Instruments USA, Inc. you know up front the initialization for the write address register. I www.seiko-usa-ecd.com parameters for your LCD, you can hard-wire the values and eliminate Roberto Ferrabone earned a BSEE from Spartan FPGAs most of the logic associated with the the Politecnico di Torino in Turin, Xilinx, Inc. System Set command and its parame- Italy. He co-owns Siro Automazione www.xilinx.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 49 former can pass the audio signal while ABOVE THE eliminating the galvanic connection between equipment, thus breaking the GROUND ground loop that produces the noise. Transformers in general, and signal PLANE transformers in particular, seem to be a mystery to many engineers. Let’s take a look at them with a straightfor- Ed Nisley ward application: an isolated mixer for PC sound card audio.

TRANSFORMER 101 Nowadays, transformers are used only when no feasible alternatives exist. Those hulking iron lumps in old Audio Transformation electronic gear have largely given way to fiercely complex chips that simply wouldn’t work if you built them from discrete parts. Apart from wall warts and Ethernet jacks, transformers are hard to find these days. Contrary to popular belief, though, you don’t need many turns of wire or a metallic core to form a transformer. All it takes is one wire, called the pri- urely, you’ve mary, and another, called the second- s encountered one of ary, in reasonable proximity to each these problems: you other. Passing an alternating (or at If you’ve ever had a have more audio sources least changing) current through the than your PC has line-in jacks, or primary wire creates a magnetic field problem connecting you’d like to connect all of your PCs that transfers energy to the secondary to a sound system with real speakers. wire. That’s all there is to it. your PCs to a sound In either case, you cannot simply sol- Everything else is in the nature of der the offending outputs together and fine-tuning: multiple turns of wire system, and chances stuff them into one input jack, increase the coupling, a metallic core are you have, then lis- although I’ve seen that done by folks concentrates the field, and specialized who should have known better. materials tailor the transformer’s char- ten up. In this article, You need what’s called an audio acteristics for specific applications. You mixer, which is a device that combines can make it as complex as you like, Ed shows us how he two or more audio input signals into a which can be very complex indeed. single output. The word “mix” has A fundamental understanding of took the mystery out of two different meanings in the analog transformer action requires getting up domain, however. When you mix audio close and personal with folks named audio transformation signals, their amplitudes add up to pro- by building an isolated duce a linearly related output signal. When you mix RF signals, their ampli- mixer for PC sound tudes multiply in a decidedly nonlin- ear and highly useful manner. We’ll card audio. So, get use linear mixing now and discuss nonlinear mixing in a later column. ready to connect. As you saw in my August column (Circuit Cellar 145), audio signals have large dynamic ranges, low aver- age levels, and a distressing propensi- ty for noise. Anyone who’s ever tried Photo 1—A 6-W audio line transformer dwarfs tele- to wire an audio system has uncov- phone and 8-Ω:1-kΩ output-matching transformers. ered the clearly audible hum that sim- Note that a larger core volume implies a higher power ply won’t go away. An isolating trans- handling capability.

50 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Ampere, Faraday, Biot, Savart, Lenz, appears in current-sampling applica- and Maxwell. For the purpose of this tions such as feedback control of DC- article, however, some simple assump- DC converter power supplies. tions and approximations will suffice. Knowing the input (and output) Dividing the number of turns in the power and the output current gives secondary winding by the number of you the output voltage: turns in the primary winding will give ns vs =vp × you the turns ratio of a transformer. np [2] Usually expressed in primary:secondary form (e.g., 1:1, 2:3, or something simi- Note of the order of the subscripts lar), the turns ratio is a transformer’s in the turns ratio part of Equations 1 single most important parameter. and 2. The secondary current decreases If you assume the primary winding and the secondary voltage increases transfers energy to the secondary with the number of secondary turns. Photo 2—An input board’s audio transformers link sig- winding with 100% efficiency, which An exaggerated example of voltage nals across the separated ground planes, shown at the top of this photo. The mixer board at the bottom had is actually a pretty good assumption, step-up appears in neon-sign trans- only two pairs of analog switches installed for testing. and that the transformer doesn’t really formers that produce 15-kV voltages care which coil you call the primary, at a few milliamps, and in automotive transformer works out anywhere near then most of the useful transformer ignition coils that fire spark plugs 600 Ω. DC resistance measurements formulas fall out almost immediately. from a 12-V source. reveal only winding resistances that Magnetic coupling depends, reason- Because those two relations apply at bear no relation to the AC impedances. ably enough, on both the AC current the same time, you can figure out the Not surprisingly, however, even flowing in the winding and the num- impedance relationship across the though transformers are optimized for ber of turns in the field, which is transformer with: one application, they can be trans- known as ampere-turns. For example, planted into other circuits. Just by 2 1 mA in 100 turns generates the same vs = vp × np looking at Photo 1, you can tell that a n [3] field as 10 mA in 10 turns, or 100 µA is ip s small audio transformer won’t work in 1000 turns. Thus, a given primary for AC power, nor should you use a current produces a secondary current Despite a common notion, a trans- wall wart for audio. You can, however, scaled by the turns ratio: former does not have an inherent use a nominal 600-Ω telephone isola- impedance of its own, at least to a first tion transformer in an audio circuit n i =i × p order approximation. It does, however, with similar impedances. s p n [1] s enforce a relation between the primary With all of that in mind, let’s see and secondary windings that can be sat- how it works out in practice. You may have seen transformers isfied by specific external impedances with a single-turn secondary used in related by the square of the turns ratio. AUDIO INPUTS spot-welding applications that use Thus, neither winding of an 8-Ω to I built an audio mixer that combines 50 kA at a fraction of 1 V. In the oppo- 1-kΩ impedance-matching transformer PC audio outputs for my outboard site direction, a heavy single-turn pri- measures what you might expect, and sound system. As Photo 2 shows, an mary with a multiple-turn secondary no parameter of a 600-Ω isolation input board handles one stereo signal from a single 3.5-mm stereo plug or two RCA-style plugs, while the lower board does the audio switching and mixing. The complete sys- tem has four input boards (one more than I need!), one mixer board, and a power- supply board. Figures 1 and 2 show the right channel of the input and mixer boards, respec- tively, with the missing left channel looking just the same. The power supply board, which I don’t have Figure 1—Input can come through either a 3.5-mm jack or two RCA jacks. The input common connection must be isolated from all other circuit commons to avoid ground loops and their resultant noise. The jumpers and resistors allow many different input room to discuss here, holds impedances, but remain fixed after you find the proper configuration for your source. a straightforward linear

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 51 supply producing ±12 V and 5 V from tive attenuator to cut high-level audio magnetic field cannot induce enough a center-tapped 22-VAC wall wart. down to size. You can pick the resis- secondary current to maintain the My usual volume settings produce a tors to suit your situation; I simply transformer action. As the frequency

75-mVP signal into the external ampli- installed JP2 to pass the signal decreases, the primary side sees an fier’s Line-In jack. Shoving the PC straight through to the transformer. increasing load that eventually leads Volume Control sliders to the top I used a pair of 600-Ω 1:1 audio trans- to severe distortion. boosts that to 1.5 VP, which is a 26-dB formers to isolate the input signal’s The cure involves either a larger increase and louder than even my ears common connection from the mixer core that can carry more magnetic can tolerate for long periods of time. I circuitry. The transformers, originally flux without saturating, or a lower sig- used that range to determine what the designed for a modem, are being used nal level to fit the available flux limit. mixer had to handle; your PC should be outside of their original specifica- The low-frequency limit at 75 mVP is similar, but measure before building. tions, but their frequency response about 5 Hz; at 1.5 VP it’s 50 Hz, which Because every input and output turned out to be surprisingly good. is good enough for this application. gizmo already had volume adjust- The output impedance of my vari- The original modem application han- ments, I needed a unity gain device ous PC Line-Out and Speaker-Out dled 1-V phone line signals with a that simply added the signals together. amplifiers lies in the 3- to 5-Ω range, low-frequency spec of about 300 Hz. Thus, unlike commercial sound mix- so the input board looks like a high At sufficiently high frequencies, a ers, this one doesn’t have adjustable impedance to the PC. The secondary transformer’s intra- and inter-winding volume or tone controls, just an ana- side sees a low impedance, effectively capacitances affect its response. That log switch to mute each input signal. in parallel with the 1.3-kΩ resistor. isn’t a problem in this application, Even low-level sound has a high crest Why not use an 8-Ω to 1-kΩ match- because the circuit’s response is flat to factor, so the common 5-V single-sup- ing transformer? That implies a turns about 100 kHz. I should probably roll ply op-amps don’t have the input or ratio of 1:11, which would step up my off the op-amps well before that! output range required for peak signals. usual 75-mVP input signal to 800 mVP

In my parts box, I had a stock of LF411 and the 1.5-VP maximum to 16 VP. AUDIO MIXING op-amps, which are decent performers Can you see why even transistorized Figure 2 shows you that audio mix- with a moderate input noise spec. audio amplifiers use high supply volt- ing involves nothing more complex Given the audio quality going into the ages? I decided to use 1:1 transformers. than adding all of the signals together mixer, though, they’re adequate. My cheerful “ideal transformer” with an op-amp. That’s something of a Although I didn’t need it in my assumption breaks down at low fre- letdown, no? application, Figure 1 includes a resis- quencies where the slowly varying The advantage of an inverting op- amp adder lies in the fact that its negative feedback holds the summing node, the point where all of the input signals combine at 0 V. This ensures that the input signals cannot creep back out through their neighbors and cause problems upstream. The op-amps on each input board prevent that situation in this cir- cuit, but it’s something to con- sider for more complex mixers. Mixers with numerous input channels must have summing amplifiers that can drive enough current through the feedback resistor to handle the maximum input current through all of the channels. A 32-channel mixer with 1-kΩ input resistors (for lower noise)

and a 1-VP input level could have up to 32 mA flowing into the summing node, which would pose a major problem for Figure 2—The right channel of the audio mixer combines signals from up to four input boards. The LF411 op-amp adds the any of the common op-amps. input signals and must have headroom of at least a factor of four (12 dB) over the maximum input signal. Of course, the input currents

52 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com would almost never add up that way ten to anything that requires more because they’re uncorrelated. You than stereo sound. Also, even though I must, however, ensure that the sum- can report the frequency response of ming amplifier can handle whatever these circuits, I can’t tell you how you define to be the maximum cur- they sound because two years ago a rent. That’s another way of saying that (biological) virus rolled off my ears by SHOP OUR ONLINE STORE the output voltage is the sum of the about 25 dB above 2 kHz. Although I www.allelectronics.com input voltages. If you run the mixed don’t need hearing aids, my graphic 5mm Blue LED Special audio into an ADC, you must allow for equalizer looks like an old dot-bomb enough headroom to handle those financial chart: two rows of LEDs ris- High-brightness blue LED. 1000 MCD. I Water-clear in off state. Special price. additive peaks. Digital clipping sounds ing dramatically to the right. CAT# LED-86 more annoying than analog clipping, 10 for $1.50 each $ 75 100 for $1.15 each so you may wind up feeding only 13 Ed Nisley, PE, is an electrical engi- 1each 1000 for 95¢ each bits of input signal voltage into your neer and a ham radio geek (call sign fancy 16-bit ADC to allow a mere KE4ZNU). You may contact him at Resettable Circuit Protector

18 dB of headroom. [email protected]. Raychem “Polyswitch” # RXE-065S-1 The MAX4520 analog switches pass Unlike traditional fuses, they automatically rail-to-rail voltages under the control reset when fault condition is cleared. Can PROJECT FILES be paralleled for higher ratings. Current: of a TTL logic signal. They are nor- 0.65 Amps. Trip Current: 1.3 Amps. mally open, so a high logic terminal To download the schematics and Max Voltage: 60 Volts. 0.33” dia. UL, CSA. CAT# RXE-065 mutes the audio. You can drive these board layouts, go to ftp.circuitcellar. 100 for $20.00 com/pub/Circuit_Cellar/2002/147/. 00 500 for $85.00 from a simple mechanical switch or, for $ 1000 for $150.00 as you’ll see in my next column, from 3 1 something a bit more complex. RESOURCES 24 Character X 2 Line LCD A larger mixer would use SPDT Audio isolation transformers with LED Backlight switches to short the inputs to ground www.jeffrowland.com/tectalk2.htm 0.21" high Optrex # DMC24201 and eliminate their input noise. If the char- Electrical Engineering course notes acters. inputs are capacitively coupled, you 5 X 8 dot format. must also hold their DC level at Brigham Young University LED backlight. 0.63" x 3.7" viewing area. 1.53" ground to eliminate a nasty pop when maxwell.byu.edu/~spencerr/ x 4.7" module size. Removed in good condi- tion, from new equipment. Prepped with 4" you un-mute the inputs. websumm122/web.html wire leads terminated with 15 pin socket con- nector (0.075" centers). Audio purists will horripilate when Department of Electronics Includes hook-up diagram. $ 50 they discover that this mixer inverts Carlton University CAT # LCD-74 9each the incoming signal phase. If it’s any www.doe.carleton.ca/~gauthier/ 25 WATT POWER SUPPLY consolation, not all sound cards pro- 97315/labs/97315_lab_03.pdf duce phase-correct outputs, nor are all Autec # UPS25-1002T the outputs necessarily of the same Jensen Transformers, Inc. Input: 115v/1.5A or 230V/0.75A phase. Adding a unity-gain inverting www.jensen-transformers.com/ Output: 5V @ 1.9A, buffer to the mixer board will let you apps_wp.html 12V @ 1.6A. 25 Watt switching drive a low-impedance device directly Midcom, Inc. supply mounted on an L-bracket, from the mixer, but this certainly 9" x 2.27" x 2.25" overall. Standard three www.midcom-inc.com/ prong IEC socket power input. On-Off rocker isn’t intended as a speaker amplifier! pdf/TN69.pdf switch. Molex-type connector output. UL, CSA. CAT# PS-251 $ 25 CONTACT RELEASE SoundCraft mixer design 4each 10 for $3.50 each You can also use this mixer on the Shure, Inc. ORDER TOLL FREE other side of the PC audio chain to www.dself.demon.co.uk/ampins/ 1-800-826-5432 combine external inputs for the PC’s mixerdes.htm CHARGE ORDERS to Visa, Mastercard, Line-In jack. Although you might con- American Express or Discover TERMS: NO MINIMUM ORDER. Shipping and handling for the sider building the input and output SOURCES 48 continental U.S.A. $6.00 per order. All others including AK, mixers in a single cabinet, you’ll be HI, PR or Canada must pay full shipping. All orders delivered MAX4520 Analog switch in CALIFORNIA must include local state sales tax. Quantities connecting the PC’s common to the Limited. NO COD. Prices subject Maxim Integrated Products, Inc. CALL, WRITE to change without notice. audio amp’s common through the (408) 737-7600 FAX or E-MAIL MAIL ORDERS TO: mixer power supply. Investigating this ALL ELECTRONICS www.maxim-ic.com for our FREE is worthwhile, but don’t bend any 96 Page CORPORATION sheet metal until you verify it! Transformer testing tutorial CATALOG P.O. Box 567 My tastes in PC audio seem to be Hank Van Cleef Outside the U.S.A. Van Nuys, CA 91408 send $3.00 postage. fairly limited by contemporary stan- www.nostalgiaair.org/NostalgiaAir/ FAX (818)781-2653 dards, particularly because I don’t lis- Articles/singles/xfrmr01.htm e-mail [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 53 of an interstate you think of trucks and trailers. The resulting PCB and APPLIED ATmega128 perched atop the 64-pin IC socket reminded me of a big old PCs flatbed tractor-trailer rolling down the highway. So, the contraption you see in Photo 1 is dubbed “Flatbed.” The Fred Eady Flatbed lash-up works well, and I have an eight-lane Pinewood Derby race timer running with the ATmega128/ carrier board/64-pin IC socket combi- nation on-line out there in Boy Scout land to prove it. Design with STKxxx Parts Although Flatbed serves its purpose well, there are situations when the standard-voltage or commercial-tem- Build an Ethernet Controller perature ATmega128 isn’t suitable for the environment the microcontroller is going to reside in. Therefore, you have to build a fleet of Flatbeds with each little truck carrying a low-power ATmega128L-8AC or industrial tem- perature-rated ATmega128-16AI.

ATMEL’S STK501 s microcon- To avoid having to put together a a trollers and their fleet of Flatbeds, Atmel offers the supporting parts move STK501, which is an add-on product for Fred first introduced from the classic DIP and the STK500 AVR development system. leaded packages to the realm of SMT, As you can see in Photo 2, the STK501 us to the STK500 the tools that support them must also is a daughterboard that couples to the make that migration. Proof in point is original STK500 via the expansion starter kit. Now he’s this month’s subject matter. headers. A TQFP ZIF socket, which is The Atmel ATmega128 MCU can a mechanical marvel in its own right, back with the newest be had only in a 64-pin TQFP configu- takes all of the pain out of switching tool in his Atmel tool- ration. I was drawn to this part by its between the various types of high I/O pin count, speed, and large ATMega128 devices. The ATmega128 box, the STK501. In amounts of internal SRAM and pro- TQFP ZIF socket is spring-loaded, and gram flash memory. To experiment it has fingers for each pin that move this project, he com- with the ATmega128, I had to come out of the way to allow the ATmega128 up with a way to get at its power to be inserted and removed. bines the STK501 without having to solder one down The STK501 is not just a home for an every time I changed applications. ATmega128. The ATmega128 has three daughterboard with After some thought, I came up with additional I/O ports (i.e., E, F, and G), the STK500 and ASIX the package you can see in Photo 1. and the STK501 pins them out. There’s My aim was to use a standard and also an additional serial port that must Ax88796 to build a commonly available through-hole IC be accommodated; the STK501 pins it socket that could carry the ATmega128 out as well. For convenience, the 10/100-Mbps Ethernet and a PCB that would extend the STK501 includes a MAX3232E RS-232 ATmega128’s pins out to larger hard converter IC and nine-pin shell connec- controller. points. The 64-pin IC socket that sup- tor that are tied directly to the extra ports the ATmega128/PCB duo is the ATmega128 serial port. same one that carries the venerable The ATmega128 has the ability to 68000 series of micros. use a 32.768-kHz crystal that can be Because I’m from the South, I spend tied across the TOSC pin set. A slide a lot of time on the interstate highway switch on the STK501 switches the system traveling between Florida and on-board 32.768-kHz crystal in and Tennessee. Of course, when you think out of this circuit arrangement.

54 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com STK500, and I/O ports E, F, and G on AX88796 development board’s address, the STK501. Each port is pinned out data, and control lines are pinned out to identically (i.e., pin 1 of the I/O port 10-pin male headers. The pinout of the header is bit 0, pin 2 is bit 1, and so AX88796 development board headers forth). This consistent pinout allows matches the header pinout pattern of for the use of simple 10-pin female-to- the STK boards. In addition to provid- female ribbon cables as the I/O signal ing a means of easy access to digital sig- carriers between the STK boards and nals on the development boards, each between the STK boards and external male header includes pins that trans- hardware under development. port power and ground as well. Pin 9 Photo 1—This is a handy 64-pin IC socket package because you can throw it in a socket and wire wrap or To complement the services provid- is ground; pin 10 is VTG (V Target). solder it into your project. ed by AVR Studio, I will be using the The AX88796 is a 3.3-V part with ImageCraft ICCAVR Professional C 5-V tolerant I/O. Therefore, a couple Other features of the STK501 compiler to produce the firmware for of things must happen on the STK500/ include solder pads for an additional the new Ethernet IC. Because I will be STK501 end to accommodate this. ATmega128 test socket and external porting code in the Ethernet applica- First, the STK500 AVR target voltage SRAM or flash memory. A 6-pin con- tion, I don’t plan to employ the servic- (VTG) must be set for 3.3 VDC in nection is provided to allow a pro- es of the JTAG ICE unless things get AVR Studio. Second, the standard gramming cable to be fitted between really sticky. I’ll debug using the sec- ATmega128-16AC must be replaced the STK500 and STK501 ISP program- ond serial port of the ATmega128L run- by the ATmega128L-8AC because the ming headers. For JTAG ICE users, the ning at 57.6 Kbps. The pins for the pri- ATmega128-16’s operating voltage STK501 has a JTAG pin set that mates mary serial port will be used for ISP range is 4.5 to 5.5 VDC. The L version perfectly with the Atmel JTAG ICE (in-system programming). I’ve already of the ATmega128 extends the voltage header. Take a look at Photo 3 to see written a module that will allow me to range down to a 2.7-VDC minimum. the STK500/STK501 configuration I use printf statements aimed at the Another trade-off for moving to the used for this project. secondary serial port. According to the L version of the ATmega128 is that the AX88796 datasheet, the AX88796 is maximum clock speed decreases from DRIVING THE TOOL SET compatible with the NE2000 register 16 to 8 MHz. Neither the need for the The STK500, STK501, and JTAG set, which means I can use most of the L version of the ATmega128, the 3.3- ICE all are designed to be driven using same code that makes the RTL8019AS- VDC operating voltage, nor the micro- hooks in Atmel’s AVR Studio. After based Packet Whacker hum. [1] controller speed is a showstopper with connecting the STK500/STK501 hard- OK, it looks like I now have all of the STK500/STK501 tool set. Even at ware to my PC’s serial port, I down- the necessary AVR tools assembled 8 MHz, the ATmega128L is speedy, and loaded the latest version of AVR on the bench to begin working with the 8-MHz speed limit is more than fast Studio from Atmel’s web site. After the AX88796. The next step in the enough for this application. In fact, I’ll discovering the STK5xx hardware, process is to gain easy access to the use a 7.3728-MHz crystal to clock the AVR Studio requested that I update 128 pins that hang off the AX88796 ATmega128L. That’s as close to 8 MHz the STK500’s firmware to enable the LQFP package. as I can get and still clock the data rate enhancements offered by the new ver- generator accurately. sion of software. Likewise, AVR DEVELOPMENT BOARD Obtaining the 3.3 VDC for the Studio performed a similar upgrade to The AX88796 development board is AX88796 is as simple as a mouse click the JTAG ICE firmware. designed to be easily interfaced with inside AVR Studio. The spring-loaded I’m in the process of evaluating a the Atmel STK500 and STK501 AVR ZIF allows the ATmega128 to be new Ethernet IC from ASIX. The part development boards. All of the replaced by an ATmega128L in seconds. I’m looking at is the AX88796 As you can see in Photo 4, three-in-one Local Bus Fast the AX88796 development Ethernet Controller. I will board has four 10-pin male need a minimum of three of headers. One header pins the ATmega128’s I/O ports to out five of the AX88796’s provide address, data, and 10 address lines. The lower control signals for the five address lines are used to AX88796. The port set access the AX88796’s inter- included with the STK500 nal NE2000 (MAC) register becomes an extension of the set. The remaining address ATmega128 port set when the lines are hardwired to a base STK501 daughterboard is address of 0x200, which is attached. This gives you I/O Photo 2—The addition of the STK501 allows the STK500 to support all of the the default base address for ports A, B, C, and D on the Atmel 8-bit microcontrollers with a single development board. the AX88796. Using the

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 55 DTACK line and address line BOARD MEETING SA[0] doubles as the LOWER Now that you’re familiar with all of DATA STROBE (LDS) signal. the development boards, let’s put them AX88796 chip select (CS) and together and explore the AX88796’s RESET can be accessed on the internals. Of course, I always begin header. To accommodate 16-bit with a smoke test. In my haste, I designs, the BUS HIGH ENABLE attached the AX88796 development (BHE) signal is also pinned out to board to a 5-V VTG STK500/ STK501 this header. AX88796 CS also system. To my amazement, nothing can be permanently enabled was damaged on the AX88796 develop- with a jumper or controlled by ment board. That was a good omen. the AVR at the header. According to the AX88796’s In addition to being a 10/100- datasheet, you should be able to port Mbps Ethernet controller, the NE2000-compatible code to the AX88796 can be configured to AX88796 with little pain and no tears. interface to a printer. All of the I’m going to test this because I plan to standard printer control lines, use much of the same code that the including a bidirectional data bus, now world-traveled RTL8019AS-based are pinned out on the AX88796 Packet Whacker (it’s also hooked up development board. These lines to a web cam) employs. double as media-independent After reviewing the datasheet for the Photo 3—The standardization of the 10-pin headers on the STK500 and STK501 made for a clean I/O connection to the interface (MII) signals by default. AX88796, I determined that I had to AX88796 development board. When MII signals are activated, make some minor changes in the MAC an external PHY can be accessed register definitions. I also had to add default address allows the three base to implement other types of networks. some definitions because the AX88796 address pins (i.e., I/O_BASE[0], In either mode, special-purpose regis- includes registers and bits that the I/O_BASE[1], and I/O_BASE[2]) of the ters inside the AX88796 manipulate RTL8019AS does not have. The MAC AX88796 to be left unconnected and the feature signals. core register set is identical in the follow their internal pull-up and pull- Moving to the opposite side of the buffer ring control areas. The same page down circuitry. The address header printer interface pins, you can see a start, page stop, current page, and also pins out the *IORD and *IOWR socket area for an 8-pin EEPROM. boundary registers described in the I/O control signals and the interrupt Unlike the RTL8019AS, the AX88796 National Semiconductor documents request line (IRQ). does not automatically look for this exist on the AX88796. The SRAM The ATmega128 is an 8-bit micro- EEPROM at power-up. Instead, the buffer area is also mapped to the stan- controller, and the AX88796 is EEPROM is placed under your control, dard NE2000 location of 0x4000 designed to run in 8- or 16-bit mode. and it’s accessed with an internal through 0x7FFF. I was pleasantly sur- So, there is a header for the lower AX88796 EEPROM register set. prised by the inclusion of content in eight data bits and another for the The AX88796 development board’s the AX88796’s datasheet that is similar upper eight data bits of the AX88796. magnetics are housed within the to the original National Semiconductor Data bits 8 through 15 are pinned out NU1S041C-434 Lan Mate. The datasheet content describing the ins on the AX88796 development board NU1S041C-434 complies with the and outs of using the buffer ring and for those of you who want to operate IEEE 802.3u standards. The Lan Mate DMA resources of the NIC. in 16-bit mode. Setting a bit in the is configured with a 1:1 AX88796’s data configuration register center-tapped turns ratio, (DCR) selects 8- or 16-bit mode. and it incorporates all of The fourth header contains pins for the necessary electronics the ISA mode AEN and RDY signals. to interface to the in-can The AX88796 is billed as a Local Bus RJ45 connector. Ethernet Controller, and CPU[0] and In addition, the CPU[1] pins on the AX88796 can be NU1S041C-434 includes configured for one of four local bus three in-can status LEDs. CPU modes. These modes include ISA, You may download a dia- 80186, 68K, and 8051. The AX88796 gram of the NU1S041C- pins morph with the CPU selection. For 434 from the Circuit instance, in 8051 mode, the AEN pin Cellar ftp site (it’s becomes the PSEN signal. When the included in the schemat- CPU[X] pins are jumpered for 68K ic for the main AX88796 Photo 4—Every pin that isn’t tied to a power rail is pulled out to the head- mode, the RDY line becomes the development board). er pins. Because I’m new to this IC, I wanted everything to be accessible.

56 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Need an MCU? Put a SoC in it.

The Cypress PSoC.™

Customized MCU design in 20 minutes or less. Build your custom PSoC™ microcontroller with programmable analog and digital functions from our extensive mixed-signal library.

Option #8926

Option #1530 8-bit PWM Inverting Amplifier

Option #625 Low Pass Filter 24-bit Timer

Option #4237 16-bit CRC Notch Filter IrDA Transmitter Analog 12-bit Incremental A/D 8-bit DAC Comparator 8-bit DAC More flexibility. Fewer parts. Lower cost. 12-bit Incremental A/D The versatile PSoC™ Programmable System-on-Chip™ Band Pass Filter IrDA s Semiconductor Corporation. Band Pass Filter 8-bit Counter Analog microcontroller, winner of EDN magazine’s Innovation of Transmitter Comparator the Year Award in the 8- and 16-bit microcontroller category, Instrumentation11-bit AmplifierDelta Sigma A/D is the world’s first MCU that lets you custom configure the Instrumentation Programmable Amplifier CPU Gain Amplifier8-bit Counter exact part you need. Analog Comparator Graphically select, place, and interconnect 11-bit Analog 16-bit PWM the peripherals you want and adapt the Delta Sigma A/D Comparator architecture with PSoC Designer™software

Dynamically reconfigure a single PSoC There are many more blocks to work with—and thousands chip multiple times—changing functionality of MCU configurations. PSoC Designer™ software is free on the fly in any application for download with emulation hardware starting at $248. Reduce BOM cost by reducing the number of external components To learn more about our innovative PSoC solutions and to enter a drawing to win a professional PSoC Development Kit (a $1495 value), visit us at www.cypress.com/ad/psoc2. Cypress, PSoC, Programmable-System-on-Chip, and PSoC Designer are trademarks of Cypress Semiconductor Corporation. ©2002 Cypres

Unlike the RTL8019AS, there are original Packet Whacker code and in reset, 10BASE-T in reset, Reset no pages two and three of the the AX88796 ported code is the way Busy, and Auto-Negotiation Done. AX88796 MAC register set. That’s the AX88796 handles NIC reset. The Some of the reset results are based on because the EEPROM is not auto- RTL8019AS uses the interrupt status the auto-negotiation process. Reset matically accessed, so there is no register (ISR) RST bit to indicate Busy or RST_B is the replacement for need to reserve space for that when the NIC is out of reset. The the RST bit in the ISR, and it indi- “expected” data. Also, Duplex mode AX88796 RST bit is simply an indi- cates whether or not the AX88796’s is easily selectable using bits in the cator that is set when reset is PHY is in reset. Because the AX88796 transmit configuration register (TCR) entered; it’s cleared when a start can operate in 10BASE-T or 100BASE- in the MAC/MII register area. The command (0x22) is issued to the TX mode, the PHY contains logic for RTL8019AS contains this mode and command register (CR). both modes with the modes being the LED activity mode stuck in a There are many other interesting mutually exclusive. hard-to-reach page-three area of the ways to monitor reset on the Auto-negotiation is a means of MAC. The LED mode for the AX88796. To accomplish this, the establishing the highest performance AX88796 is pin-selectable by using AX88796 adds a test register (TR) at link between stations on a network. the I_OP pin of the AX88796. MAC register offset 0x15. Within the For instance, if a station on a network A notable difference between my TR register are four bits: 100BASE-TX can operate only in 10BASE-T Half- Duplex mode, the auto-negotiation process determines this and sets up

From register (Internal PHY) the link accordingly. Each node knows offset 14h MDC MDIO-OUT MDIO-IN about the other through advertise- MDC Pin 67 ments of each node’s abilities. These MDO MDC Pin 66 MDIO advertisements are transmitted using MDI Y 0 fast link pulses, or FLPs. An FLP burst MDIR (MUX) 1 contains 33 link pulses that occur at S If (PHY_ID==10h), then S = 1 or S = 0 the same intervals as 10BASE-T nor- mal link pulses (NLPs). NLPs occur every 16.8 ms. Each FLP burst is 100 ns wide. FLP bursts

Field Description interleave clock pulses with data puls-

Pre Preamble—the PHY will accept frames with no preamble. This is indicated es. The 17 odd link pulses are clock by a 1 in register 1, bit 6. pulses, and the 16 even link pulses are ST Start of frame—indicated by a 01 pattern the data. The absence of a pulse fol- OP Opcode—10 for a read; 01 for a write lowing a clock pulse encodes a logic 0. Conversely, a pulse within the time PHYADD PHY address—5 bits, allowing for 32 unique addresses. The first PHY address bit transmitted and received is the MSB. window following a clock pulse A station mangement entity that is attached to multiply PHY entities must have prior knowledge of the appropriate PHY address for each entity. encodes a logic 1. This invisible

REGAD Register address—5 bits, allowing for 32 unique registers within encoding process ultimately becomes each PHY. The first register address bit transmitted and received is the a 16-bit word or link-code word MSB of the address. (LCW). Bits within the LCW represent TA Turnaround—2-bit time spacing between the register address field and the data field of a frame to avoid drive contention MDIO during a read the abilities of the nodes that are transaction. During a write to the PHY, these bits are driven to 10 by the station. During a read, the MDIO is not driven during the first bit time; it is establishing the communications link. driven to a zero by the PHY during the second bit time. Using the datasheet, you can see the DATA Data—16 bits; the first bit transmitted and received will be bit 15 of the AX88796’s abilities listed in the MR1 register being addressed. register of the AX88796’s embedded PHY register set. IDLE Idle condition—the idle condition on MDIO is high-impedance state. All three state drivers will be disabled, and the PHY’s pull-up resistor will pull I wrote some simple code to read the MDIO line to logic 1. the TR register bits and connected the AX88796 development board to a 10BASE-T network. After performing Read/Write Pre ST OP PHYAD REGAD TA DATA IDLE (R/W) an NIC reset, reading the TR register indicated that the 100BASE-TX logic Z R1…1 0110 AAAAA RRRRR Z0 DDDDDDDDDDDDDDD was in reset. I then connected the AX88796 development board to a W1…1010101 AAAAA RRRRR Z0 DDDDDDDDDDDDDDD Z 100BASE-TX network and performed a NIC reset. Just as I expected, the Figure 1—Although I slowed the clock to 1-s intervals to watch the LEDs, this interface can run at 12.5 MHz 10BASE-T logic was in reset when against the internal PHY. connected to the 100BASE-TX net-

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 59 work. In both cases, the PHY reset bit was set and later cleared, indicating Listing 1—The ability to read and write the MII interface is a plus because you have access to informa- that the PHY reset successfully. So tion about the auto-negotiation process and what the PHY is really doing. far, so good. //Write to MII registers Although accessing the MII is not void write_mii(unsigned char phyad,unsigned char regad,unsigned int required, I thought that it would be a mii_data) { good idea to have AVR code to read unsigned char mask8; and write the AX88796’s embedded unsigned int i,mask16; PHY registers. As it turns out, if I mii_write; //Macro that sends ST and OP for write operation mask8 = 0x10; want the AX88796 to behave, I must for(i=0;i<5;++i) //Send 5 bits of PHY address be able to write to the MII’s MR0 con- { trol register. There’s a statement in the switch ((mask8 & phyad)) { datasheet that basically says you must case 0: put the AX88796’s embedded PHY in clr_mdo; //Macro clears MDO bit Power Down mode for 2.5 s, and then break; default: restart the auto-negotiation process to set_mdo; //Macro sets MDO bit assure that a good link is established. } To do this, you must write two mii_clk; //Macro clocks bits out of MDC by setting and clearing the MDC bit sequences to the MR0 embedded PHY mask8 >>= 1; register. This brought about the addi- } tion of another MAC register, the mask8 = 0x10; for(i=0;i<5;++i) //Send 5 bits of PHY register address MII/EEPROM Management Register { (MEMR), at offset 0x14, to my original switch ((mask8 & regad)) MAC definitions. { case 0: The MEMR register is the origin clr_mdo; and endpoint of data going to and break; from the AX88796 embedded PHY default: set_mdo; and the external 8-pin EEPROM. The } upper four bits of the MEMR repre- mii_clk; sent all of the EEPROM signals— mask8 >>= 1; } EECLK, EEO, EEI, and EECS. The mii_w_ta; //Macro that drives two turnaround bits 10 lower nibble of the MEMR is dedi- mask16 = 0x8000; cated to the MII interface. Follow for(i=0;i<16;++i) //Send 16 bits of data to PHY { along using Figure 1 as I describe switch (mask16 & mii_data) how to interface with the AX88796’s { embedded PHY. case 0: clr_mdo; Notice that pins 66 and 67 can be break; used to communicate with an exter- default: nal PHY. These pins also can be used set_mdo; } during debugging. I connected them mii_clk; to a couple of LEDs on the STK500. mask16 >>= 1; The clock for the communications } } session is provided by alternately loading the MDC bit (bit 0) of the //Read the MII registers MEMR with a one and zero. I slowed unsigned int read_mii(unsigned char phyad,unsigned char regad) { down this clock to 1-s intervals in unsigned char mask8,i; order to observe the clock and data unsigned int mask16,result16; activity on pins 66 and 67. Everything mii_read; //Macro that sends ST and reads OP bits mask8 = 0x10; is synchronized to the rising edge of for(i=0;i<5;++i) //Send 5 bits of PHY address the MDC clock pulse. { So, to send a one to the embedded switch (mask8 & phyad) { PHY, simply set the MDO bit (bit 3 case 0: of the MEMR) and write a one-zero clr_mdo; sequence to the MDC bit location. break; default: To read a bit from the PHY, you must clock the MDC bit and check (Continued) the status of the MDI (bit 2) bit of the MEMR. The secret to success,

60 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Listing 1—Continued about the AX88796 development board, head over to the EDTP set_mdo; Electronics web site (www.edtp.com). } mii_clk; Now that you know how to read mask8 >>= 1; and write the AX88796’s MAC and } MII registers with an ATmega128L, mask8 = 0x10; for(i=0;i<5;++i) //Send 5 bits of PHY register address you too can be on your way to build- { ing a 100-Mbps Ethernet using an 8- switch (mask8 & regad) bit AVR microcontroller, proving { case 0: along the way that it doesn’t have to clr_mdo; be complicated to be embedded. I break; default: set_mdo; Fred Eady has more than 20 years } of experience as a systems engineer. mii_clk; //Sets, and then clears MDC bit, He has worked with computers and providing the clock mask8 >>= 1; communication systems large and } small, simple and complex. His forte mii_r_ta; //PHY output buffer turnaround time is embedded-systems design and mask16 = 0x8000; result16 = 0x0000; communications. Fred may be for(i=0;i<16;++i) //Read 16 bits of data from PHY reached at [email protected]. { mii_clk; read_rtl(MEMR); PROJECT FILES switch (byte_read &= 0x04) { To download the code and board case 0: schematic, go to ftp.circuitcellar. nop; com/pub/Circuit_Cellar/2002/147/. break; default: result16 |= mask16; REFERENCE } mask16 >>= 1; [1] ASIX Electronics Corp., } “AX88796 L 3-in-1 Local CPU return result16; } Bus Fast Ethernet Controller,” AX796-18, V1.8, June 2002.

SOURCES when reading and writing the embed- would mux the input from pin 66 ded PHY, is to know that it’s into the MEMR. The GPO and AX88796 Ethernet controller addressed as 0x10. Control (GPOC) register (another ASIX Electronics Corp. The bottom of Figure 1 contains the addition to the MAC register defini- 886 3 5799500 frame format used to communicate tions) allows you to choose between www.asix.com.tw with the embedded PHY. The pream- an external and the internal PHY. ATmega128 Microcontroller, ble is not required because a bit (bit 6) The AVR code to access the embed- STK500/STK501 is set in the MII MR1 register to ded PHY is shown in Listing 1. Atmel Corp. bypass it by default. A simple start-of- (408) 441-0311 frame sequence is clocked in (ST) fol- REGISTER TO WIN www.atmel.com lowed by the read/write opcode (OP). It’s pretty obvious that you can The bits are clocked in just as you see easily control the AX88796 if you ICCAVR C compiler them, from left to right. know how to manipulate its regis- ImageCraft Creations, Inc. So, to talk to the embedded PHY, ters. I also added the SPP Data Port (650) 493-9326 10000 is clocked in as the PHY Register (SPP_DPR) at offset 0x18, www.imagecraft.com address. There are 5 bits in both the the SPP Status Port Register MAX3232E PHY address (PHYAD) and PHY reg- (SPP_SPR) at offset 0x19, and the Maxim Integrated Products, Inc. ister address (REGAD). This allows SPP Command Port Register (408) 737-7600 32 PHY addresses to be defined, and (SPP_CPR) at offset 0x1A to support www.maxim-ic.com it gives access to 32 registers within bit banging from the AX88796’s bidi- each of the 32 PHYs. Note that a rectional I/O printer port. RTL8019AS Ethernet controller PHY address of 0x10 muxes the You may download the complete Realtek Semiconductor Corp. embedded PHY’s output to the AX88796 AVR code from the Circuit 886 3 578 0211 MEMR. Any other PHY address Cellar ftp site. For more information www.realtek.com.tw

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 61 umes low and costs high. Because cost was of great concern, it was deemed FROM THE foolhardy to consider a flash memory part for production use. After all, BENCH when the code works, there’s no need for further tweaking and higher costs for erasable parts. Jeff Bachiochi Upgrading a product with external program space consists of replacing the code-bearing ROM/EPROM devices. Thanks to the companies that used socketed parts, this replacement was easy even though it was expen- 12, 16, 18, Hike! sive. When a product used a micro- processor with internal code, the costs were higher, even if it was socketed. Dashing for Flash Cash On the production line, it took months to use up the old revision stock. This, of course, would lead to unhappy customers further down the road. In terms of inventory, there were advantages to using a reprogrammable part in production, such as the lack of waste and immediate revision updates without the loss of stock. n the past few Early programmable parts required issues while cover- special voltages for the programming i ing my SmartMedia process and high programming cur- Whether project, I’ve been talking rents prevailed. Although using inter- about Microchip’s PIC18F252. I didn’t nal voltage-boost converters hid some you’re spend much time discussing the proces- of this, flash memory technology has sor then, but it’s an apropos topic now now advanced to the point where gearing that Circuit Cellar is kicking off the devices are fully reprogrammable in- up to par- Mad Dash for Flash Cash Microchip circuit, even using normal operating Design Contest 2002. In addition, to voltages. Today, a product can be ticipate in give you a leg up in the contest, I’ll updated without having to remove the cover the rest of the Microchip prod- processor from the circuit. In fact, the Microchip 2002 uct basics in this article. RISC-based MPUs began like most PC<20:0> design contest or get- with ROM parts for production and CALL, RCALL, RETURN 21 EPROM-based parts for development. RETFIE, RETLW ting ready to follow Although EPROM (windowed) parts Stack level 1 … the action from your are erasable via UV, one-time pro- Stack level 31 grammable (OTP) parts don’t have a RESET Vector 0000h favorite recliner, now window and cannot be erased even though they’re conveniently user-pro- High-priority interrupt vector 0008h grammable. For many years, develop- is the perfect time to Low-priority interrupt vector 0018h ment was accomplished with expen-

tune in for Jeff’s pre- sive emulators or blow-and-go, using On-chip slow-turnaround (erase time) EPROM- program memory game analysis. based parts. Some frustrated engineer 7FFFh 8000h User memory space asked about using the new EEPROM/ Read 0 flash memory technology in a micro, allowing it to be quickly erased elec- 1FFFFFh 200000h trically. Although the packaging would not require the expense of a Figure 1—Program memory space for the PIC18Fx52 is a full 32 KB of flash memory. That’s up to 16K sin- ceramic-windowed part, using the part gle-word instructions. A separate stack space allows only for development would keep vol- 31 levels of calls and interrupts.

62 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com many products that are currently on Instruction Description the market can be updated through a phone/cable/network connection. INDFx Moves data to the location pointed to by the FSRxH/L pair POSTDECx Moves data to the location pointed to by FSRxH/L, then decrements the FSRxH/L pair DRIVING DOWN COST POSTINCx Moves data to the location pointed to by FSRxH/L, then increments the FSRxH/L pair PREINCx Increments the FSRxH/L pair, then moves the data to the location pointed to by FSRxH/L OK, so it doesn’t start out that way. PLUSWx Moves data to the location pointed to by the combination of the WREG and FSRxH/L pair Investing in technology costs money; however, when the long-term benefits Table 1—Use direct addressing to move your data. Indirect addressing is the proper method when you need to outweigh the costs, the end product’s move based on a register’s value. cost can go down. For example, take the PIC16C6x/7x, which is one of set, which is referred to as the 12-series. familiar with the processor before Microchip’s most useful parts. It was (Remember asking yourself, “What you dash off to start your contest redesigned using flash memory tech- good is a micro with only six I/Os?”) entry (see Photo 1). nology, and now it sells for about half New devices bragged an increase in If you take a look at Figure 1, you’ll of the original OTP part and one-third instructions to 35 with an increase in see some of the important features the cost of the EEPROM version. instruction width to 14 bits and the associated with the program memory Essentially, you’re getting a better part addition of interrupts. Reprogrammable organization. The ’F252 has 32 KB of for a cheaper price. parts began to hit production (the code flash memory, 1536 bytes of From day one, Microchip’s top prior- PIC16C84) and simplify development. data RAM, and 256 bytes of data ity was to keep future products code- Success triggered a natural progression EEPROM. There are also 31 levels of compatible. Their “seamless migra- toward a 16-bit instruction set that hardware stack space available in the tion path” objective is not an easy one used 58 instructions. As a result, the micro. And, because the stack point- to obtain. Even though the word 17-series was born. er is read/write, you can set up a “seamless” probably originated in C compiler-optimized architectural software stack in RAM if you need Microchip’s marketing department, enhancements gave rise to the 18-series more space. Speaking of RAM, banks the engineering department has obvi- micros and an increase of the instruc- of RAM are much easier to use with ously attempted to hold onto this tion set to 77. Meanwhile, flash mem- the PIC18F252. mantra with both hands. ory technology has been applied to Figure 2 shows six 256-byte banks many devices in the 12-, 16-, and now of RAM. Note that one bank of RAM LINE ’EM UP 18-series of micros. is identified by a bank select register The product lineup began with 12-bit (BSR). Alternately, there’s an access instruction products using only PIC18F252 register bank that always contains the 33 instructions (i.e., the 16C5x-series The PIC18F252 is one of the newest first 128 bytes of RAM (from bank 0) parts). The industry’s first 8-pin micro members of Microchip’s PIC18Fxxx plus the last 128 bytes from bank 15 also used this 12-bit RISC instruction family of micros. Let’s get more (i.e., the special function registers, or SFRs). The SFRs are RAM used by the CPU for core functions; peripheral BSR<3:0> modules use SFRs for control functions. The data EEPROM is a single bank 000h = 0000 00h Access RAM 07Fh of 256 bytes. This might be used as Bank 0 GPR 080h configuration data for a sensor that’s 0FFh = 0001 FFh incorporated in your application. The Bank 1 00h 100h GPR FFh 1FFh configuration data might need to be = 0010 Bank 2 00h GPR 200h changed; however, it must be non- = 0011 FFh 2FFh Bank3 00h 300h Access bank volatile in nature. GPR = 0100 FFh 3FFh 00h 400h Access RAM low The PIC chips incorporate a few safe- Bank 4 GPR 7Fh 4FFh = 0101 00h 80h ty techniques to assure this memory 500h Access RAM high Bank 5 GPR 5FFh (SFRs) FFh isn’t changed arbitrarily by errant code. = 0110 FFh 600h Bank 6 First, the EEPROM data area is not Unused to = 1110 Read 00 When a = 0, mapped into the data (register) space. Bank 14 the BSR is ignored and the EFFh access bank is used. To read from the EEPROM block, you = 1111 F00h 00h Unused The first 128 bytes are general- Bank 15 F7Fh must place the address of interest into purpose RAM (from bank 0). When a = 1, F80h FFh SFR The second 128 bytes are the BSR is used to specify the the EEADR register in the FSR bank. FFFh special function registers RAM location that the instruction uses. (from bank 15). Note that the EEPGD bit must be cleared to point to the EEPROM area, Figure 2—Data memory is divided into 256-byte static RAM banks. Data addressing is available via the access and the RD bit must be set to enable bank or through the bank select register (BSR). The BSR’s lower nibble selects one of the 16 RAM banks (0 to 15). The access bank is always available. It consists of the first half of RAM in bank 0 plus the special function a read. Both bits are found in the registers (SFR) in the last half of bank 15. EECON1 register located in the FSR

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 63 bank. The data stored in the EEPROM Mnemonic, 16-bit instruction word Status at address EEADR is available in the Description Cycles Operands MSb LSb affected EEDATA register in the FSR bank. Byte-oriented file register operations Writing an address in the data EEP- ADDWF (f, d, a)Add WREG and f 1 0010 01da ffff ffff C, D, Z, OV, N ROM involves a similar process. Place ADDWFC (f, d, a) Add WREG and carry bit to f1 0010 00da ffff ffff C, DC, Z, OV, N ANDWF (f, d, a) AND WREG with f1 0001 01da ffff ffff Z, N the address of the write into the CLRF (f, a) Clear f 1 0110 101a ffff ffff Z EEADR register. Then, insert the data COMF (f, d, a) Complement f1 0001 11da ffff ffff Z, N CPFSEQ (f, a) Compare f with WREG, skip = 1 (2 or 3) 0110 001a ffff ffff None to be written into the EEDATA register. CPFSGT (f, a) Compare f with WREG, skip > 1 (2 or 3) 0110 010a ffff ffff None CPFSLT (f, a) Compare f with WREG, skip < 1 (2 or 3) 0110 000a ffff ffff None The EEPGD bit must be cleared to DECF (f, d, a) Decrement f1 0000 01da ffff ffff C, DC, Z, OV, N point to the EEPROM area, and the DECFSZ (f, d, a) Decrement f, skip if 01 (2 or 3) 0010 11da ffff ffff None WREN bit must be set to enable a DCFSNZ (f, d, a) Decrement f, skip if not o 1 (2 or 3) 0100 11da ffff ffff None INCF (f, d, a) Increment f 1 0010 10da ffff ffff C, DC, Z, OV, N write. Next, disable the global interrupt INCFSZ (f, d, a) Increment f, skip if 0 1 (2 or 3) 0011 11da ffff ffff None to prevent interference by any other INFSNZ (f, d, a) Increment f, skip if not 0 1 (2 or 3) 0100 10da ffff ffff None peripheral. The following sequence IORWF (f, d, a) Inclusive OR WREG with f 1 0001 00da ffff ffff Z, N MOVF (f, d, a) Move f 1 0101 00da ffff ffff Z, N must be executed exactly: Write 0x55 MOVFF (fs, fd) Move fs (source) to first word 2 1100 ffff ffff ffff None 1111 ffff ffff ffff to the EECON2 register; write 0xAA to fd (destination) second word the EECON2 register; set the WR bit in MOVWF (f, a) Move WREG to f 1 0110 111a ffff ffff None MULWF (f, a) Multiply WREG with f 1 0000 001a ffff ffff None the EECON1 register to begin the NEGF (f, a) Negate f 1 0110 110a ffff ffff C, DC, Z, OV, N actual write; and then execute an NOP RLCF (f, d, a) Rotate left through carry 1 0011 01da ffff ffff C, Z, N instruction. The global interrupt can be RLNCF (f, d, a) Rotate left (no carry) 1 0100 01da ffff ffff Z, N RRCF (f, d, a) Rotate right through carry 1 0011 00da ffff ffff C, Z, N enabled once again. It’s a good practice RRNCF (f, d, a) Rotate right (no carry) 1 0100 00da ffff ffff Z, N to clear the WREN bit when finished SETF (f, a) Set f 1 0110 100a ffff ffff None SUBFWB (f, d, a) Subtract f from WREG with borrow 1 0101 01da ffff ffff C, DC, Z, OV, N writing data to the EEPROM data area. SUBWF (f, d, a) Subtract WREG from f 1 0101 11da ffff ffff C, DC, Z, OV, N SUBWFB (f, d, a) Subtract WREG from f with borrow 1 0101 10da ffff ffff C, DC, Z, OV, N SWAPF (f, d, a) Swap nibbles in f 1 0011 10da ffff ffff None ADDRESSING TSTFSZ (f, a) Test skip if 0 1 (2 or 3) 0110 011a ffff ffff None If you’ve had the privilege to pro- XORWF (f, d, a) Exclusive OR WREG with f 1 0001 10da ffff ffff Z, N gram 12- or 16-series PICs, you’re probably familiar with the page- Figure 3—Byte-oriented instructions manipulate a RAM or SFR. f is the register file, d is the destination bit, and a

is the RAM access bit. C/P TCP/IP

NEW Products

µFlashTCP-EP* LogicFlex* Dual-E* LogicFlex-EPX* Solutions 10Base-T Ethernet 10Base-T Ethernet 2 Ethernet Ports 10Base-T Ethernet 2 Serial Ports 2 Serial Ports 2 Serial Ports 2 Serial Ports 7-34 VDC 46 Digital I/O’s 3 Counter / Timers 16 Opto-Isolated inputs Optional I/O Interface Programmable Xilinx CPLD 5 Digital I/O’s 16 Relay Outputs @ 500mA ea. Rugged Enclosure w/ Hardware Clock/Calendar Onboard Connectors Quick-Disconnect Connectors Industry Standard Expansion Bus for USNET TCP/IP Rack Mount Enclosure Connectors Peripheral Boards Software in Kits LCD & 6 Pushbuttons Starts at $229 Starts at $189 Starts at $199 Starts at $499

*All products based on the Intel 386Ex with DOS and NE2000 compliant, 10Base-T Ethernet. Standard memory includes 512K RAM & 512K Flash plus DIP socket to accept an M-Systems DiskOnChip. Development systems contain necessary hardware and software tools for fast development. Tools to Move Data

JK microsystems connects you with embedded control solutions. Our cost-effective DOS based controllers are ideal for data acquisition, networking or industrial technology applications.

1403 Fifth St., Suite D Visit us on the web www.jkmicro.com JK microsystems, Inc. Davis, CA 95616 USA Call 530-297-6073 Fax 530-297-6074

64 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com switching requirement Even though the FSRxH 16-bit instruction word Status Mnemonic, Description Cycles that’s the result of the lim- Operands MSb LSb affected Notes and FSRxL cover the data ited width of the address Bit-oriented file register operations area, another useful set of BCF (f, b, a) Bit clear f 1 1001 bbba ffff ffff None 1, 2 field in single-word GOTO BSF (f, b, a) Bit set f 1 1000 bbba ffff ffff None 1, 2 registers cover the code and CALL instructions. A BTFSC (f, b, a) Bit test f, skip if clear 1 (2 or 3) 1011 bbba ffff ffff None 3, 4 area. This is useful for BTFSS (f, b, a) Bit test f, skip if set 1 (2 or 3) 1010 bbba ffff ffff None 3, 4 larger 21-bit program BTG (f, b, a) Bit toggle f 1 0111 bbba ffff ffff None 1, 2 retrieving table informa- counter provides a linear tion stored in code space. reach of 2 MB. And the Figure 4—Bit-oriented instructions manipulate a single bit within a RAM or SFR. It works a bit differently paging ugliness has been from the indirect address- done away with, thanks to multi- location. Indirect addressing is handy ing registers. Because the code area is word GOTO and CALL instructions. when you need to move dynamically, much larger than the RAM area, three Program memory is handled in byte based on a register’s value as opposed address registers are needed TABP- increments instead of the previous to the register itself. Although the orig- TRU/H/L. A single register TABLAT is word-sized (12, 14, or 16 bits) incre- inal PICs had a single indirect register, used to hold the table read’s data. ments. Although this means the PC is the 18-series has three sets of indirect Instead of using registers to read the now incremented by two for each registers. Each set contains a register table data, there are four TABRD instruction or four for each two-word pair, FSRxH and FSRxL (x = 0–2), instructions you can use. Each instruc- instruction, the instruction flow (i.e., where the registers hold a 12-bit tion will affect the TABPTRU/H/L reg- the use of pipelining) still exists. This address covering the total RAM space. ister differently (see Table 2). allows each instruction to be execut- In addition to this pointer pair, five Remember that these instructions ed in a single execution cycle (after an other registers are used to access the are performing access to the code area. initial fetch) except for any instruc- data being pointed to, and they poten- Normally, with non-flash memory tion that changes the PC (i.e., a tially affect the pointer pair (see parts, the data in the code area is branch instruction), which requires a Table 1). The indirect registers work read-only. Flash memory parts open new fetch to fill the pipe again. the same way when retrieving data Pandora’s box because the code area Direct addressing is used for most from them (i.e., the location pointed can be reprogrammed using the data moves—get this here, put that to by the FSRxH/L pair). Notice any TABWR instructions similar to the there. The moves are based on a fixed similarity to C operators here? TABRD instructions. If you recall from Get your motor running

Visit our website for special pricing!

Shown Here: BS2 Carrier Board, Motor Mind C, 2 Easy Roller Wheel Kits

Up to 4.0A Current • 10-24VDC Motors Motor Mind C Controls 1 or 2 Motors • 40 Pin DIP Package Serial, Analog or R/C Pulse Control SolutionsSolutions CubedCubed Simple & Sturdy (530) 891-8045 Easy Roller Wheel Kit Robot Wheel Kit www.solutions-cubed.com

66 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com last month how a byte of a sector of a SmartMedia block is changed, then you Instruction Description can already guess how reprogramming TABRD Retrieves data from the location pointed to by the TABPTRU/H/L registers a byte in code space must be handled. *TABRD– Retrieves data from the location pointed to by the TABPTRU/H/L registers, then A byte of code area (flash memory) decrements the FSRxH/L pair that’s not erased cannot be written *TABRD+ Retrieves data from the location pointed to by TABPTRU/H/L registers, then incre- ments the FSRxH/L pair on a byte or word basis; it requires *TABRD+ Increments the FSRxH/L pair, then retrieves data from the location pointed to by an erasure of a 64-byte block (e.g., the TABPTRU/H/L registers TBLPTRU/H/L uses only bits 6 to 21, bits 0 to 5 are ignored). This means Table 2—These are the four instructions you can use to read the table data. that if data in the other 63 bytes is important, you must have a 64-byte To write to the flash memory, the INSTRUCTION SET RAM buffer set aside to read the 64- TBLPTRU/H/L registers are set to the Instructions are grouped into five byte block into before erasing it or the beginning address of one of the partial categories: byte-oriented, bit-oriented, data stored there is lost. blocks (the LSb would be xxxxx000). literal, control, and table-oriented. To erase a 64-byte block of the code Eight writes to the TABLAT (using The byte-oriented operations are list- area, place the address of the block *TABWR+, post-increment) actually ed in Figure 3. They contain an into the TBLPTRU/H/L registers. The write to eight holding registers. opcode and up to three operands: a EEPGD, WREN, and FREE bits must These registers will be used by the file register (f), a destination bit (d), be set to point to the flash memory hardware when the programming and a RAM access bit (a). area to enable a write and an erase. takes place. To initiate the write to The file register is the location in a All bits are found in the EECON1 reg- flash memory, the EEPGD, WREN, RAM bank on which the operation is ister located in the FSR bank. and FREE bits must be set to point to to be performed. The destination bit Next, disable the global interrupt to the flash memory area to enable a indicates where the result of the oper- prevent interference by any other write and an erase. ation will be placed. When d = 0, the peripheral. Then, execute the following Next, disable the global interrupt result goes into the WREG. When d = sequence to begin the internal erasure to prevent interference by any other 1, the result is put back into the file process: Write 0x55 to the EECON2 peripheral. Now, the following register. The RAM access bit indi- register; write 0xAA to the EECON2 sequence is executed to begin the cates where the file register will be register; set the WR bit in the EECON1 internal programming process: Write found. When a = 0, the file register is register to begin the actual erase; and 0x55 to the EECON2 register; write taken from the access register bank. If then execute an NOP instruction. 0xAA to the EECON2 register; set the a = 1, the file register is taken from Further instructions will be halted WR bit in the EECON1 register to the RAM bank indicated by the BSR. until the internal process is complete. begin the actual write; and then exe- Note that this is a source of confu- The global interrupt can be enabled at cute an NOP instruction. sion, so it must be chosen wisely. that time. After the data is in RAM, Further instructions will be halted For instance, if the file register of bytes can be changed and the block until the internal process is com- interest is the SFR TXREG, you may written back into the code space. But plete. The global interrupt can be use a = 0 to indicate it’s in the access wait, writing to the code area writes enabled once again. This entire bank. If the BSR = 0x0F, you may use 8 bytes (i.e., a partial block) at a time, process is repeated eight times for a = 1, otherwise using a = 1 (RAM so the write process must be done the remaining data bytes in the block. bank) when BSR points to any other eight times to completely write the Note that it requires about 18 ms to bank will make use of the wrong reg- 64-byte block back into the code area. update the whole block. ister (see Figure 2). Most byte-oriented instructions are single-word instructions that execute

Mnemonic, 16-bit instruction word Status in a single instruction cycle (except Description Cycles Notes Operands MSb LSb affected where the PC is altered). In the byte- Literal operations oriented category, there’s also a regis-

ADDLW (k)Add literal and WREG 1 0000 1111 kkkk kkkk C, DC, Z, OV, N ter-to-register move, which requires ANDLW (k) AND literal with WREG1 0000 1011 kkkk kkkk Z, N two words because it’s a direct move IORLW (k) Inclusive OR literal with WREG1 0000 1001 kkkk kkkk Z, N

LFSR (f, k) Move literal (12-bit) second word 2 1110 1110 00ff kkkk None avoiding the use of bits a and d. As to FSRX first word 1111 0000 kkkk kkkk such, it must contain the 12-bit address MOVLB (k) Move literal to BSR<3:0> 1 0000 0001 0000 kkkk None MOVLW (k) Move literal to WREG 1 0000 1110 kkkk kkkk None of each register. This instruction takes MULLW (k) Multiply literal by WREG 1 0000 1101 kkkk kkkk None RETLW (k) Return with literal in WREG 2 0000 1100 kkkk kkkk None two instruction cycles to execute. SUBLW (k) Subtract WREG from literal 1 0000 1000 kkkk kkkk C, DC, Z, OV, N The bit-oriented instructions are XORLW (k) Exclusive OR literal with WREG 1 0000 1010 kkkk kkkk Z, N listed in Figure 4. These contain an opcode and three operands: a file reg- Figure 5—Literal instructions involve a constant in the manipulation of a register, usually WREG. ister, a bit position (b), and a RAM

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 67 are both direct and relative GOTO interrupts can be optionally defined Interrupt source Description (BRA) and CALL (RCALL) instructions. as either high or low priority (see The direct instructions require two Table 3). Each priority has a separate TMR0 Timer 0 overflow TMR1 Timer 1 overflow words. Because all of them affect the interrupt vector address. A high-pri- TMR2 Timer 2 overflow PC, they all require two execution ority interrupt can interrupt a low- TMR3 Timer 3 overflow cycles. Even though all conditional priority interrupt immediately. RB Port B change of state branch instructions are single words, Therefore, a high-priority interrupt INT0 External interrupt 0 INT1 External interrupt 1 they too affect the PC, and as such, has the lowest interrupt latency. INT2 External interrupt 2 they require two execution cycles. An interrupt automatically saves PSP Parallel slave port The eight table operations were dis- the WREG, STATUS, and BSR bits (PIC18F4x2 only) cussed earlier and are listed in Figure 7. into a one-level fast stack. The con- AD End of A/D conversion RC USART Receive trol instruction RETFIE (return from TX USART Transmit INTERRUPTS interrupt) has an s operand that con- CCP1 Capture compare PWM 1 If you’ve worked with the 12-bit trols whether or not the return from CCP2 Capture compare PWM 2 PICs, then you know it’s not easy cod- the interrupt is with or without EE EEPROM/flash memory write complete ing without interrupts. Even with the restoring these registers from the fast BCL Bus collision advent of interrupts, many applications stack. Care must be used because the LVD Low-voltage detect suffer from long interrupt latencies fast stack is only one level. If a high- SSP Synchronous serial port (i.e., the time from the initial interrupt priority interrupt interrupts a low-pri- Table 3—Interrupts make coding a much easier event to the time when the interrupt is ority routine, the low priority’s auto- process. Here are the interrupt sources for the ’18Fxx2. actually serviced). This might be the matic save is overwritten when the result of having to save registers, poll high-priority interrupt begins. The access bit (a). The file register is the the interrupt register, or another inter- control instructions CALL and location in a RAM bank on which the rupt routine having control at the time. RETURN also have the s operand and operation is to be performed. The bit The 18-series micros have a number can make use of the fast stack, but position specifies on which bit (from of latency-reducing features. should be used only if interrupts are 0 to 7) the operation is to be per- The first is two levels of priority. disabled or not used. formed. The RAM access bit indicates Often, your project will include more where the file register will be found. than one interrupt routine. When all CLOCK OSCILLATOR When a = 0, the file register is of the interrupts are equal, a pending The PIC18Fxx2 micros support taken from the access register bank. interrupt must wait for any in-process eight oscillator modes. The low- And when a = 1, the file register is interrupt to complete. Eighteen-series power (LP) mode supports crystals up taken from the RAM bank indicated by the BSR. All bit-oriented instruc- tions are single-word instructions and Mnemonic, 16-bit instruction word Status Description Cycles execute in a single instruction cycle Operands MSb LSb affected (except where the PC is altered). Control operations The literal instructions are listed in BC (n)Branch if carry 1(2) 1110 0010 nnnn nnnn None BN (n) Branch if negative1 (2) 1110 0110 nnnn nnnn None Figure 5. These contain an opcode and BNC (n) Branch if not carry1 (2) 1110 0011 nnnn nnnn None one or two operands: a constant (k) BNN (n) Branch if not negative 1 (2) 1110 0111 nnnn nnnn None BNOV (n) Branch if not Overflow2 1110 0101 nnnn nnnn None and an FSR (f). In most cases, an oper- BNZ (n) Branch if not zero 1 (2) 1110 0001 nnnn nnnn None ation is performed using an 8-bit con- BOV (n) Branch if overflow 1 (2) 1110 0100 nnnn nnnn None BRA (n) Branch unconditionally 1 (2) 1101 0nnn nnnn nnnn None stant and the WREG, with the result BZ (n) Branch if zero1 (2) 1110 0000 nnnn nnnn None CALL (n, s) being placed back into the WREG. Call subroutine first word 1 1110 110s kkkk kkkk None second word 1111 kkkk kkkk kkkk One instruction uses an FSR to point CLRWDT Clear watchdog timer 1 0000 0000 0000 0100 *TO, *PD to one of the three indirect file regis- DAW Decimal adjust WREG 1 0000 0000 0000 0111 C ter sets, which will accept the 12-bit GOTO (n) Go to address first word 2 1110 1111 kkkk kkkk None second word 1111 kkkk kkkk kkkk direct RAM memory address (k). This NOP No operation 1 0000 0000 0000 0000 None move is a two-word instruction NOP No operation (Note 4) 1 1111 xxxx xxxx xxxx None requiring two instruction cycles. POP Pop top of return stack (TOS) 1 0000 0000 0000 0110 None PUSH Push top of return stack (TOS) 1 0000 0000 0000 0101 None Control operations have to do with RCALL (n) Relative call 2 1101 lnnn nnnn nnnn None instructions that can change the path REST Software device RESET 1 0000 0000 1111 1111 All of execution. These contain an opcode RETFIE (s) Return from interrupt enable 2 0000 0000 0000 000s GIE/GIEH, PEIE/GIEL and up to two operands (see Figure 6). RETLW (k) Return with literal in WREG 2 0000 1100 kkkk kkkk None Opcodes without operands have direct RETURN (s) Return from subroutine 2 0000 0000 0001 00ls None operations like CLRWDT (clear watch- SLEEP Go into Standby mode 1 0000 0000 0000 0011 *TO, *PD dog timer), NOP (no operation), and SLEEP (go into a Standby mode). There Figure 6—Control instructions alter the execution of a program or perform a given task.

68 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com to 200 kHz. Crystals or resonators up further execution can be Bit Function Register location to 4 MHz can be used with XT mode. delayed by 1024 oscillator For frequencies up to 20 MHz, the cycles plus 2 ms, depending STKFUL (7) Stack overflow STKPTR high-speed (HS) mode is used. on the mode. STHUNF (6) Stack underflow STKPTR To reduce EMI, the PLL mode accepts RI (4) Software reset RCON TO (3) Watchdog time-out RCON crystals or resonators up to 10 MHz and HARDWARE MULTIPLY PD (2) Power down RCON internally multiplies them by four. Math-intensive applica- POR (1) Power-on (hardware) reset RCON These modes require both OSC1 (input) tions can benefit from the BOR (0) Brownout RCON and OSC2 (output) pins. The RC resis- hardware multiply function tor/capacitor (RC) and external clock included in the 18-series Table 4—There are several functions that can cause a reset. (EC) modes require only the OSC1 PIC processors. WREG is input. The OSC2 output will have a multiplied by any 8-bit register to pro- and PORTE, the parallel slave port clock output derived by an OSC1 divid- duce a 16-bit result in a single instruc- (PSP) is worthy of being mentioned ed by four. Alternatively, the OSC2 out- tion cycle. This unsigned function here. This peripheral allows the micro put can be disabled and the pin used saves about 68 instruction cycles over to be interfaced directly to another as an extra I/O with RCIO and ECIO using a software routine. For signed processor’s data bus. The 8-bit data modes. Timer 1 can be configured as a and other larger multiplies, including port and three control signals (CS, RD, low-power clock by attaching a 32-kHz the hardware multiply, the algorithm and WR) camouflage it as a peripheral watch crystal to its oscillator pins. will reduce execution time by a factor chip. This little gem lets you design The system clock can be sourced and of seven to 15 times. custom smart peripherals. switched between either of these oscillators, making for some rather PORTS TIMERS interesting speed/power trade-offs. Like many micros, some port I/O Four 16-bit counter/timers are pins are multiplexed for alternate included in the PIC18Fxx2 microcon- RESET peripheral functions. Each port has troller. Each has several special features Numerous sources can cause a three registers associated with it. associated with it. Timer 0 is selec- reset, so knowing where the reset These registers are PORTx, TRISx, table as an 8- or 16-bit timer with came from can often allow an applica- and LATx (where x = A/B/C for the appropriate rollover interrupt; it has a tion to respond differently based on PIC18F2x2 and D/E for the ’18F4x2). dedicated 8-bit prescaler and clock the cause. Table 4 lists the functions The TRISx register is a read/write edge selection when clocked externally. that can cause a reset. register that determines the direction Timer 1 and Timer 3 have dedicated To ensure that the power supply of each port pin. When a bit position 3-bit prescalers and clock edge selec- and internal functions have stabilized, equals one, the corresponding I/O pin tion when clocked externally. Their special power-up delays are invoked is configured as an input (high imped- clock source can also come from the depending on the mode of the micro. ance). When a bit position equals zero, auxiliary low-power external oscillator

If MCLR is tied to VCC (i.e., no RC the corresponding I/O pin is config- and synchronized to the system clock. delay has been applied to the MCLR ured as an output, and the logic level Both timers can be cleared by a trigger pin), the power-up timer (PWRTE) can of the corresponding data latch bit is from the CCP module (Compare mode). be enabled to hold the micro in reset placed on the I/O pin. Writing data to Although Timer 2 has an 8-bit for an initial fixed 73-ms delay. If a the LATx or PORTx will update a data timer register (TMR2), it can achieve a crystal or resonator is used, the micro latch. Reading the LATx register 16-bit count with the 4-bit prescaler is held in reset for an additional delay retrieves the present state of the data and 4-bit postscaler. A second 8-bit of 1024 oscillator cycles to ensure that latch. Reading the PORTx register period register (PR2) is compared to the oscillator has stabilized. When retrieves the present state of the port’s the TMR2 and used as a reference. configured for PLL, the delay is I/O pins (not the data latch). When the registers match, the TMR2 extended for another 2 ms to allow Even though it’s only available on register is cleared (data rate generator). the phase loop to fully lock. the PIC18F4x2, which uses PORTD Prescalers are normally cleared with When enabled, the a write to the lower byte brownout detector can be of any timer. Mnemonic, 16-bit instruction word Status Description Cycles set for one of four volt- Operands MSb LSb affected ages (2, 2.7, 4.2, or 4.5 V). Data memory ↔ Program memory operations CCP *TBLRD Table read 2 0000 0000 0000 1000 None Any time VCC falls below Each PIC18Fxx2 con- *TBLRD+ Table read with post-increment 0000 0000 0000 1001 None this level, the micro is *TBLRD– Table read with post-decrement0000 0000 0000 1010 None tains two identical CCPx held in reset for a total *TBLRD+ Table read with pre-increment 2 (5)0000 0000 0000 1011 None modules (where x = 1 or *TBLWT Table write0000 0000 0000 1100 None power-up delay after VCC *TBLWT+ Table write with post-increment 0000 0000 0000 1101 None 2). In Capture mode, a 16- has been restored. On a *TBLWT– Table write with post-decrement 0000 0000 0000 1110 None bit timer count (Timer 1 *TBLWT+ Table write with pre-increment 0000 0000 0000 1111 None wake-up from sleep or an or Timer 3) is transferred oscillator source switch, Figure 7—Table instructions allow the program memory space to be read or modified. into a 16-bit CCPRxH/L

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 69 register pair on a selected event. An CCPRxH + 2-bit internal latch by The I2C interface uses two bidirec- event is defined as every falling edge, the Timer 2 trigger. This 10-bit tional pins, data and clock. In Master every rising edge, every fourth rising value is compared with Timer 2’s mode, a clock output is supplied and edge, or every sixteenth rising edge. 10-bit register (TMR2 + 2 bits). A data flows in and out of the data pin. In Compare mode, the value in the match between these 10-bit registers In Slave mode, the clock becomes an 16-bit CCPRxH/L register pair is clears the CCPx output pin. input and the data flows in and out of compared to a 16-bit timer count So, the period equals the amount of the data pin. Multimaster mode (Timer 1 or Timer 3). A match initi- time it takes TMR2 to count up to allows masters to compete for the bus, ates an interrupt and triggers a clear PR2. The on (i.e., CCPx output pin is with the loser(s) of arbitration allow- to the counter/timer. A match can high) time is the time it takes TMR2 ing the winner to complete its mes- also toggle an output pin or produce a to match CCPRxH. If the CCPRxH is sage. The clock for the I2C interface rising or falling edge on a match. zero, the output never gets set. If comes from a dedicated data rate gen- Timer 2 is used for the PWM period CCPRxH is greater than TMR2, the erator (BRG). This is an auto-reload timer servicing both PWMs. When output never gets cleared because 8-bit counter with an optional divide- implemented as the PWM period CCPRxH will never match TMR2. by-16 prescaler off of the system clock. timer, two additional least significant The universal synchronous asyn- bits are used, either from the Timer 2 SERIAL PORT chronous receiver transmitter prescaler or the Q clock when the The synchronous serial port (SSP) (USART) module can be configured for prescaler is 1:1, to produce a 10-bit module can be configured to support both sync and async modes. Both value. When Timer 2 matches SPI or I2C. The SPI supports Master modes use BRG as the clock source. (TMR2 = PR2), TMR2 is cleared, the and Slave modes. Master mode pro- Asynchronous mode allows data to CCP output pin is set, and a CCP vides a synchronous clock out to sup- flow independently in both directions reload is triggered. The duty cycle port data output and input pins. Slave (TX and RX) at the same time. period is determined by the 8-bit mode accepts a synchronous clock to Because Synchronous mode supplies value in CCPRxL + 2 bits from the support data output and input pins. a clock (by the master on TX), data CCPxCON register. This 10-bit refer- The clock comes from the system, can flow only in one direction at a ence value is loaded into the 8-bit prescaler, or Timer 2. time on RX. The data format is the

a) Power-up Normal record reset b)

N Want to A24–31 = 0? Bootload? N Y (Button pressed) Y A16–A23 = 0×20? ID memory Y Execute Set-up TBLPTRU/H/L with A0-A23, N application at write block 8 bytes Set-up serial port 0×0200 for ASC transfer Y A16–A23 = 0×30? Configuration memory

N Set-up TBLPTRU with A16–23, Start of line Send XON table write x bytes receive a line of Y A16–A23 = 0×F0? ASC text EEPROM memory send XOFF N Set-up EEADR with address/2, write eight 16-bit words N N A15 = 0? Good Intel.hex line? Y Y Halt N Y A8–A15 < 2? Normal record? Flash memory Y Set-up TBLPTRH/L with address to erase, N erase 16 bytes Go to Go to Normal record Y start of line Last record? N Erased? N Halt Y N Extended record? Set-up TBLPTRH/L with address to write, table write 16 bytes, block write first 8 bytes, block write second 8 bytes Save address in record as address Go to A16–A31 error (file addresses are limited N Write verified? to 16-bits (A0–A15) Y

Figure 8—This flowchart will help you write your own boot load application.

70 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com same for both modes: 8(9) data bits per byte, with the asynchronous mode requiring one start and one stop bit per byte sent.

A/D Between the eight- channel multiplexer ahead of the 10-bit ana- log-to-digital converter module and the ability to choose whether or not pins are configured as digital, analog, or reference, this module Photo 1—Look inside before taking your first step in the dash for flash cash. is highly user-friendly. Both the upper and lower references to set up CCPx and TIMER1 (or 3) to for the analog-to-digital converter can provide an acquisition delay and auto- be configured for internal VDD and VSS matic conversion start. or external voltages via port pins. This allows the input span to be care- LOW-VOLTAGE DETECTOR fully tailored for maximum resolu- When using batteries, it’s often nec- tion. The 10-bit A/D result can be essary to prepare the application for right or left justified in the 16-bit reg- shutdown by executing housekeeping ister pair, making it easy for a single- tasks. Sure, the brownout detector can byte read to retrieve the 8-MS or least stop execution before things go hay- significant bits of the result. wire, but how do you prepare for this? It’s recommended that the analog A low-voltage detector can be set source impedance be less than 2.5 kΩ. somewhere above the brownout volt- This will allow the converter to meet age so that it gives warning of impend- the specified accuracy by permitting ing doom with time to make ready. the internal sampling capacitor to The detector in the PIC18Fxx2 can be charge fully in a predetermined set to one of 14 levels or through an amount of time (i.e., a minimum external pin (LVDIN). These levels are acquisition time). tapped off of a voltage divider powered

After a channel is selected, the by VDD. The level is compared to a application must wait this acquisition 1.2-V internal reference also powered time before beginning a conversion by VDD. Therefore, the LVDCON regis- (setting the GO bit in ADCON0). The ter has a bit (IRVST) that indicates GO bit will be cleared when the con- when you can trust the detector’s out- version result is ready. You may wish put and enable the interrupt.

WATCHDOG TIMER Watchdog timers (WDT) are used to grab hold of an application that’s executing errant code stuck in never- never land, and then reset the system to regain control. The ’18Fxx2 has a watchdog timer that uses a completely autonomous RC oscillator. If the device is configured with the watchdog enabled, Photo 2—I’ve used Microchip’s IDC1 before, but the IDC2 would it can be arbitrarily enabled have made some of my earlier projects a little easier. and disabled using the

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 71 the other system events will wake up of the associated block. Table reads the processor and restart the oscillator, within the block are always allowed. allowing execution to continue where Protection bits are enabled (cleared) it left off. Wake-up events can come during the programming. After they’re from WDT, INTx, RB, PSP, TMR1, programmed, protection cannot be TMR3, CCP, SSP, USART, ADC, EEP- removed from any block unless the Photo 3—A view into the hardware stack will give you ROM/flash memory write, and LVD. chip or block is totally erased. important feedback as to the depth of the nested call and interrupt routines. CODE PROTECTION IN-CIRCUIT The code space within a PIC18Fxx2 The PIC18Fxx2 parts offer a few addi- SWDTEN bit in the WDTCON register. is divided into blocks. The first 0x200 tional and significant features: in-circuit If it’s configured as off, it cannot be con- bytes are considered the boot block, serial programming (ICSP), in-circuit trolled through software. The nominal and the following 0x1E00 bytes belong debugging (ICD), and low-voltage in-cir- watchdog time out is 18 ms. A 7-bit to block 0. The remaining address space cuit serial programming (LVICSP). postscaler can extend this time to over is divided into 0x2000 byte blocks. ICSP is a five-wire connection to 2 s if required. A WDT overflow will Each block can be protected in three the micro: SCLK, SDATA, V , V , DD SS reset the microprocessor. If it’s sleep- ways. The CPx bit prevents the code and MCLR (VPP). The micro automati- ing, it will wake up and continue exe- from an associated block cution. To prevent the WDT from from being read by an timing out, the application must issue external source. Because a CLRWDT instruction periodically. code can be modified by executing code, two addi- SLEEP tional protection bits are A power-down mode is entered included. The WRTx bit when the SLEEP command is execut- prevented a table write to Photo 4—The file register window shows the RAM locations, including ed. The oscillator is stopped, but all an associated block. The any defined variables. You can create a watch window to hold a group of I/O remains in its present state. An EBTRx bit prevents a specific registers. When debugging, limiting the registers of interest will MCLR will reset the micro, but all of table read from outside reduce the time it takes to update registers upon a code execution break.

72 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com cally enters ICSP mode at power- ICD2 up if SCLK and SDATA are held I’ve been using Microchip’s low while VDD rises and MCLR ICD1 for a long time now. is raised to VPP. The serial format Because I’m a crash-and-burn consists of 20-bit instructions, kind of guy, using Microchip’s with the first 4 bits identifying a Photo 5—The EEPROM window displays values stored into any of the integrated development envi- command, and the following 256-byte nonvolatile EEPROM data bank. ronment (IDE software) in con- 16-bit data to be acted on. junction with a flash memory Nine out of the 10 commands are powering up with the same signal part and the in-circuit debugger really table read and write commands for requirements as ICSP mode above lets me develop in a designer-friendly moving data in and out of code memo- (with the exception of MCLR requir- way (see Photo 2). With this setup, I ry. The tenth command (core com- ing VCC instead of VPP), the micro will get to interrogate registers within the mand) allows actual microcontroller enter LVICSP mode. The format usage working device. This allows me to instructions to be executed by the is the same as ICSP mode, but the dif- learn about the foolish mistake I’ve micro. This allows register setup for the ference is that the programming volt- made that’s causing a crash. table commands. Note that the low- age VPP isn’t needed. The design of the ICD2 integrates a voltage programming (LVP) bit in the The ICSP interface makes an ideal DB9 for those of you who still require CONFIG4L register can only be cleared connection to do helpful debugging. In RS-232 serial. In addition, the ICD2 has in ICSP mode. Clearing the LVP bit will fact, a special debugging mode is built an alternate USB interface. Your target prevent the LVICSP mode from being in to the PIC18Fxx2 devices. Clearing connection is through an RJ-11 jack. used; therefore, additional programming the BKBUG bit in the CONFIG4L reg- Designing an RJ-11 into your PCB will can only be done in ICSP mode. ister enables this mode. Background literally make interconnections a snap. For the micro to power-up in LVIC- debugging using Microchip’s in-circuit I wish I had an ICD2 available for my SP mode (LVP bit must not be equal to debugger (ICD) uses the ICSP interface SmartMedia project. I guess that’s one of zero), an additional signal PGM is and requires a 10-byte RAM space, the downsides of trying to stay on the used (this brings the programming two stack levels, and 512 bytes of code cutting edge. Now, with support for the connection to six wires). If the PGM space on the target microcontroller to PIC18Fxxx parts, the ICD2 is destined signal is held high while the micro is perform its magic. to be one of those must-have items.

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 73 debugger. With the Without the debug code, the target resources available to the can run your application at reset. PIC18Fxxx parts, this is With the debug code, you’ll be ready hardly a problem. The to run or step through your applica- debugger resources use tion. With the run command, execu- only minimal upper tion can be halted at any time. Step RAM and program mem- will execute a single instruction and Photo 6—The special function registers are the interface between the ory, in addition to two then halt. Whenever the target execu- user and all of the microcontroller’s core and peripheral functions. The levels of stack. When tion is halted, the IDE is updated with SFRs are grouped by function. your code is written and the present value of every register, To use the debugger, you must make compiled using the IDE, you can trans- including the stack space (see Photo 3), sure that your application doesn’t use fer the hex file to the target device RAM (see Photo 4), EEPROM (see any of the resources required for the either with or without the debug code. Photo 5), and special function regis- ters (see Photo 6). Also, execution can be halted at a match of address (see Photo 7). With Frustration? No, thanks. breakpoints, you have control over NeW when the program halts, so you can Fun? Yes, please. Version check register values at that critical Satisfied customers - the key to our success point in your application. > that´s why every new EAGLE version is based BOOT LOADER on the feedback from our customers OK, you know that these PIC18Fxxx > that´s why all our customers have access to our highly acclaimed, comprehensive support, free parts can reprogram their own code of charge space. How can this be used to update > that´s why EAGLE has no hidden costs for EAGLE 4.0 an application? Well, the device can libraries or modules which prove to be be totally reprogrammed using ICSP. indispensable after purchasing Schematic Capture • Board Layout Autorouter What about the user who may not > that´s why we really want customers to enjoy ® for Windows have programming tools available? working with EAGLE The low-voltage programming option > that´s why EAGLE is one of the top-rated and programs for schematic capture and board along with a simple boot application W d   a d ad a  Mc   C  a affords you reprogramming capabili- layout L   a d ad a  L  T ad ties. You have to use a serial connec- tion on the target system along with a Version 4.0 Highlights ! New Library Management with terminal program on the PC. Component Browser Microchip’s bootload.asm program ! Technology and Package variants for components can be used to accomplish this. ! Design your own commands via User Although it was written for use on the Language ! Unlimited length for component PICDEM 2 PLUS demo board (push names/values buttons), it can be altered. In fact, ! Design Rules define pad/via dimensions and shapes you’ll notice it was written for a 10- ! Net Classes for Autorouter and DRC MHz oscillator and uses a BRG_VAL ! Minimum Autorouter grid: 0.02 mm ! SMD pads can be rounded or round constant of D’10’ (56 Kbps). My PIC- ! Different pad shapes for Top, Bottom, DEM 2 has a 4-MHz oscillator, so I or Inner layers

EAGLE 4.0 Light is Freeware! FREE You can use EAGLE Light for testing and for Prices Light Standard Professional non-commercial applications without charge. The Freeware Version is restricted to boards up to half Eurocard format, Layout 199$ 399$ with a maximum of two signal layers and one schematic Layout + sheet. All other features correspond to those of the 398$ 798$ Professional Version. Download it from our Internet Site Schematic or order our free CD. Layout + 398$ 798$ The Standard Version is suitable for boards in Eurocard Autorouter format with up to 4 signal layers The Professional Version Layout + has no such limitations. Schematic + 49$ 597$ 1197$ Autorouter http://www.CadSoftUSA.com Photo 7—The program memory window lists the pro- Pay the difference for Upgrades gram instructions and indicates which instruction is 800-858-8355 next to execute. The ICD’s breakpoint is also displayed CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483 (if it’s used). This window shows the bootload.asm pro- Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : [email protected] gram following reset with a breakpoint set at the high- priority interrupt, which is redirected to 0x0208.

74 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com changed the BRG_VAL to D’12’, which micro, in addition to a V tempera- OUT SOURCES at 4 MHz sets up communication for ture sensor (TC1046AVNBTR), op-amp ICD1/2, MCP1541/3302/42100/ 19.2 Kbps. Note that lowering the (MCP6022-I/P), ADC (MCP3302-BI/P), 6022, PIC16C6x/7x, PIC18Fxx2, oscillator to 3.579 MHz would allow digital potentiometer (MCP42100-I/P), TC1046, PICSTART PLUS, PRO- 56 Kbps with a BRG_VAL of D’3’. and V (MCP1541-I/TO). How cool is REF MATE II The code fills about three-fourths that? So, all you designers out there Microchip Technology, Inc. of the boot block from 0x0000 to get ready, get set, dash for flash cash. I www.microchip.com 0x0200. Both interrupt vectors are Jeff Bachiochi (pronounced BAH-key- EPIC Plus programmer redirected from 0x0008 and 0x0018 to AH-key) is an electrical engineer on microEngineering Labs, Inc. 0x0208 and 0x0218. This means that Circuit Cellar’s engineering staff. His www.microengineeringlabs.com any application that needs to be boot background includes product design WARP-13 programmer loaded must be ORG’d for 0x0200. If and manufacturing. He may be reached Newfound Electronics the boot load code finds (in this case) at [email protected]. www.newfoundelectronics.com a high on PORTA.4, it will transfer execution to address 0x0200 (i.e., the programmed application). If PORTA.4 is low at reset, the boot load applica- tion executes. Figure 8 is a flow dia- gram of the boot load application. You can use this as a guide for writing your own boot load application. Note that this is the point where the code protect bits really come into play. Because the boot load application requires less than 0x200 bytes and resides in the boot block, full code protection will prevent inadvertent application-controlled code memory erasure and writes in this block. At the same time, it allows the boot load application to erase and rewrite the remaining blocks of code memory.

GETTING TOOLS I’ve written and debugged plenty of code with Microchip’s free simulator (part of the IDE). But, if you wish to put that code into a device, you’ll need some kind of programmer capa- ble of handling the device you are designing with. There are many PIC programmers on the ’Net, but few can boast about being able to program the newest PIC18Fxxx devices. Refer to the microEngineering Labs and New Found Electronics web sites to learn more about two programmers (i.e., EPIC Plus and WARP-13) that cost less than $100. Microchip has a complete line of tools, including the free IDE software suite and reasonably priced develop- ment and production programmers, emulators, and debuggers. I’ve been told that Microchip has put together a small kit of parts for the contest. My scouts indicate that it includes the newbie PIC18F252 www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 75 which subsequently appeared as the 8085, but it’s just a holding action SILICON until we get our 8086/88 act together. Faggin, Shima, and the others aren’t UPDATE happy. Be the 16-bit and beyond world as it may, there’s still great untapped potential for better 8-bit chips. A new Tom Cantrell company, , and a new chip, the Z80, are born. In the late ’70s and early ’80s, while Intel and Motorola battled for domi- nance in the nascent PC business, Zilog Watch Me Pull A Rabbit was cranking 8-bit Z80s and peripheral chips into embedded applications like there was no tomorrow. Out of My Hat If Zilog had stayed focused, the story might have turned out differently. But instead they repeatedly fell victim to all manner of self-inflicted, ill-conceived product strategies and corporate machi- nations. The founders left, an oil com- pany took over, the Z8000 choked, and, though sales continued coasting along, Zilog fiddled while the Z80 burned. The next chapter in the saga comes from overseas where Hitachi, looking s you’ll see, no for a way out of a messy love-hate rela- a one can argue that tionship with Motorola, came up with the new and improved the HD64180, a spiffed-up Z80-compat- It’s clear Rabbit 3000 8-bit micro ible CPU with handy built-in glue that the doesn’t live up to the latter expectation. logic and I/O functions. Subsequently, How new it is, though, is another Hitachi moved on with their H8 archi- Rabbit question. The silicon may be hot off of tecture, and Zilog remains as the source the assembly line, but the 3000 has for the Z180 and it’s derivatives along 3000 is roots that go way back. with their own eZ80 next-generation Flash back to the mid-’70s. Messrs, design (Circuit Cellar 139). an Faggin, Shima, Mazor, et al of Intel sit I suppose with all of the excitement down to craft a follow-on to their 4004 over the years, it’s no surprise that a improved 8-bit micro. calculator chip and 8008 terminal chip. long-time Z80/180 customer, the aptly But how “new” is it? The result—the 8080—is a big hit in named Z-World, decided to take mat- spite of management’s skepticism. ters into their own hands. Enter Rabbit In this article, Tom After all, companies like IBM and the Semiconductor, a sister company cre- “BUNCH” (Burroughs, Univac, NCR, ated to carry forward the 20-plus-year takes a look at the CDC, and Honeywell—remember legacy of the 8080/Z80/180. them?) don’t sell that many computers, And lest you think a legacy is more micro’s history, focus- so just how many computer chips can like baggage, just remember that we expect to unload? while new players (e.g., the Atmel ing on the evolution- Meanwhile, those cowboys in Texas AVR and aforementioned Hitachi H8) ary track leading up to are making hay with their 6800. The are starting to get traction, the 8-bit 8080 crew goes to their battle stations market is still well served by long-in- its current features. ready to craft a new version of the tooth classic architectures. 8080 that will send the Motorola horse to the glue factory for good. RABBIT 3000 But wait, Intel management is start- Fortunately, the history and basic fea- ing to get it about these newfangled tures of the Rabbit design are excellent- microchips. From on high, word ly documented in the pages of Circuit comes down that it’s 16 bits or bust. Cellar, including words of wisdom Yeah, we’ll let you make a new 8080, from one of chip’s developers, Monte

76 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Dalrymple, and a five-part article series On this historic scale, basic evolu- indeed argue that the ostensible virtue from our own Fred Eady. [1, 2] You can tionary trends can be seen in the of object-code compatibility is check them out (not to mention the instruction set, performance, periph- overblown in the embedded world. copious documentation on the Rabbit erals, glue logic, and interfacing. As For embedded applications, you web site) for the inside story. you examine each trait, you can see almost always have to change your Perhaps the Rabbit 3000 is easiest how the Rabbit Semiconductor 3000 software when you use a new chip. As to understand as the next step in the continues along the trajectory set by a practical matter, with software evolution of the ’80 species (see the ’80 chips of yore. defining so many of an embedded Figure 1). At each chip along the way product’s features, the scenario is usu- between the 8080, Z80, ’180, and now NO-RISK CISC ally, new chip = new product = new the Rabbit 3000 (and EZ80), designers The Rabbit 3000 is by no means features = new software. figured out ways to add new and object-code compatible with the And even if you really want the new improved features while retaining the Z80/180, because a number of opcodes chip to run old software, you’re going essence that made the predecessor were deleted or moved around. I don’t to have to tweak the files at least a lit- popular in the first place. really consider this a problem and tle bit. For instance, the Z180 is con- sidered object-code compat- ible with the Z80 because all of the opcodes are the OUT OUT same. But still, to upgrade

RES *RESET *IOWR *IORD *BUFEN SMODE0 SMODE1 STATUS *WDT CLK from a Z80 you would have to add some ’180-specific Data D[7:0] External interface buffer initialization code and be CPU ready to hack around subtle changes in timing. What matters isn’t com- Memory Address Memory chip *CS2, *CS1, *CS0 patibility, but rather famil- A[19:0] management Buffer interface *OE1, *OE0 control *WE1, *WE0 iarity. Z80/180 users will Spectrum Clock feel right at home with a spreader doubler Parallel ports Rabbit 3000, and it’s easy (8 bits) Port A PA[7:0] Adress bus Port B PB[7:0] to discern the relatively XTALA1 Fast Global power Port C PC[7:0] few significant changes. XTALA2 oscillator save and clock distribution Port D PD[7:0] One of the novel features Port E PE[7:0] added to the Z80 was an Port F PF[7:0] Port G PG[7:0] extra register bank, which Timer A is a concept that remains Serial port A Async Sync TXA, RXA,CLKA, popular to this day. The Timer B serial serial ATXA,ARXA premise behind the scheme Async Sync bootstrap bootstrap was that it would allow CLK32K 32.768-kHz clock input Async serial IrDA faster interrupt response by IrDA bootstrap virtue of simply switching Serial ports TXB, RXB, CLKB, between register banks B,C,D ATXB, ARXB Async Sync TXC, RXC, CLKC rather than pushing and

(8 bits) serial serial

Real-time Data bus clock Sync serial IrDA TXD, RXD, CLKD popping all of the registers Serial ports on and off the stack. Watchdog E, F This makes a lot of sense timer Sync HDLC TXE, RXE serial SDLC TCLKE, RCLKE in principle, but how about Periodic Sync serial IrDA TXF, RXF interrupt TCLKF, RCLKF in practice? As someone HDLC/SDLC IrDA who’s dabbled a fair bit Pulse width PWM[3:0] modulation with Z80s and Z180s over QD1A, QD1B, QD2A, Quadrature ID[7:0] External I/O QD2B, AQD1A, AQD1B the years, I personally can’t decoder IA[5:0] chip interface AQD2A, AQD2B recall ever using the alter- I[7:0] Input PC[7,5,3,1], PD[7,5,3,1] INT0A, INT1A External capture PF[7,5,3,1], PG[7,5,3,1] nate register set in this INT0B, INT1B interrupts Slave port SD[7:0] manner, or in fact at all. Slave interface SA[1:0] Similar experience pre- Bootstrap interface *SCS,*SRD, *SWR, *SLAVEATTN sumably inspired the Rabbit designers to make better use of these valu- Figure 1—The Rabbit 3000 is the latest in a long line of ’80 chips that goes all the way back to the dawn of micros. able, underutilized regis-

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 77 ters. Instead of being restricted to just changed to better suit the memo- exchanges, the alternate registers can be ry management strategy employed 15 dB accessed directly by using an alternate by the C compiler. Strong spreading destination (ALTD) prefix (e.g., via loads 10 and stores and pushes and pops). PECK-O-PERIPHS Normal spreading Another use of the prefix trick is The Rabbit 3000 has 128 pins to 5 EMI Noise reduction with I/O, which is handled in a differ- play with. That’s 28 more than ent manner than before. On the earlier the , twice as many as 50 100 150 200 250 300 350 Z80/180 models, I/O devices were the ’180, and more than three Megahertz accessed with unique opcodes (IN, times the 40-pin originals. Figure 2—Three spread-spectrum settings (i.e., off, nor- OUT, and variations). I’m not sure that Two-dozen of them are devoted mal, and strong) are available. Spreading interference this was ever a good idea to begin with, to power and ground, notably around isn’t the same as reducing it, which makes the tech- but it’s certainly archaic at this point. because of the fact that separate nique a bit controversial, though it no doubt facilitates meeting FCC regulations. Instead, for the Rabbit 3000, an I/O pre- power supplies (though both 3.3 V) fix (IOI for internal and IOE for external are used for the processor core and I/O) can be used with any conventional I/O. That minimizes the leakage of Note that support for dynamic RAM, memory access instruction to cause EMI generated by the former out of which made sense in the old days when the memory address to be interpreted the latter. Note that inputs are 5-V DRAM densities were measured in as a 16-bit I/O address. tolerant, which is something that’s kilobits, is arguably no longer relevant Going way back, the 8080 did have still useful in the embedded world. for 8-bit chips and has been eliminated. an advantage over other 8-bit chips at The remaining pins are divided The on-chip I/O functions are given the time; it had the ability to perform between the external memory bus and seven 8-bit ports (A through G) to play some 16-bit operations (e.g., load, various I/O functions. with. As usual, particular ports can store, add, etc.), albeit a limited set. As for the former, the Rabbit 3000 is take on dedicated I/O functions or be Rabbit has boosted the 16-bit capabili- designed to use standard byte-wide used as generic parallel I/O. ty significantly to include, for exam- memories, typically SRAM and flash If you’ve ever wished you had an ple, shifts and other logical operations memory. The 20-bit address bus and 8- extra serial port (and who hasn’t?), the such as AND and OR. bit data bus are supplemented with the Rabbit 3000 is the chip for you with a There’s also the interesting new familiar control lines (*CS, *OE, *WE) whopping six on tap. Now, it isn’t BOOL instruction that works with the for direct no-glue connection to as likely that you’ll need to use all six as 16-bit HL register pair, the de facto many as six commodity memory chips. UARTs (with IRDA format thrown in 16-bit accumulator. It’s really for good measure), so four of simple: BOOL HL sets HL to one them can work as SPI clocked if the contents of HL are nonzero serial ports instead. This is espe- and leaves it zeroed otherwise. A4 cially handy for using multiple This proves useful to the C com- clocked serial peripheral chips piler for handling conditional A1 A5 without having to multiplex evaluation; it also provides the perclk/2 the connection externally. basis for short instruction A6 Furthermore, two of the ports sequences that perform 16-bit even include SDLC/HDLC capa- signed and unsigned compares. A7 bility for applications that need The traditional vector table to connect to the wider world of interrupt system is enhanced LANs and WANs. with a four-level priority 10-bit Another I/O option is a slave scheme. The worst-case inter- counter interface comprised of an 8-bit Compare rupt latency for the highest pri- f/8 10 bits bidirectional port and a few Timer_B1 ority is just the length of the Timer B system Match register address and control lines. This longest instruction (or longest provides a handy way to connect sequence of uninterruptible Match preload a Rabbit 3000 to another proces- instructions), which is approxi- Timer_B2 sor, which could be another mately 20 clocks. Match register Rabbit 3000, but doesn’t have to The MMU is tweaked to man- be. A simple dual-port register age the 1-MB address space dif- Match preload mechanism makes it as easy to ferently than before. The basic talk to the CPU as any conven- notion that a 64-KB portion of tional peripheral chip. Besides handling the mundane chores such as serial data the physical memory is always Figure 3— Historically, external I/O and rates, the Rabbit 3000 timer subsystem goes well beyond the typical present remains the same. MCU’s reload timer with features like high-speed input capture, PWM, memory chips all would connect However, the details have been and quadrature decode. to the same data and address

78 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com L NEW Data Conversion Seminars www.ti.com/sc/training Data Converters Lowest noise precision data acquisition system on a chip. L

– Industrial process control – Medical instrumentation – Liquid/gas chromatography – Weigh scales – Portable instruments – Smart transmitters – Intelligent sensors L

ANALOG – 24 bits: no missing codes – 8 differential/single-ended inputs – PGA of 1:128

– Precision VREF – Low-power operation: 4 mW – Single supply: 2.7 V to 5.25 V – Packaging: 64-lead TQFP DIGITAL The MSC1210 from Texas Instruments achieves a new level of high performance and Microcontroller Core – 8051-compatible µcontroller core functionality in mixed-signal processing. This 24-bit, low-power (4 mW) delta-sigma ADC – Up to 6-MIPS operation integrates an enhanced 8051 processor core, Flash memory and a variety of on-chip Memory ™ peripherals including an additional 32-bit accumulator and an SPI -compatible serial port. – Up to 32-kB Flash program memory The high-performance 8051 core executes up to 3X faster and at lower power than a standard – External 64-kB memory 8051 core. With its high level of analog and digital integration, the MSC1210 is ideally – 100k erase/write cycles suited for a wide range of precision applications requiring small size, high Peripheral Features – 32-bit accumulator integration and user-selectable features. – Power management – Voltage supervisory

Res. Sampling No. of Input Program SRAM Price L Device (Bits) Rate (kSPS) Channels Memory (kB) (kB) 1K www.ti.com/sc/msc1210 MSC1210Y2 24 0.78 8 Diff/8 SE 4 1.2 $8.95 Datasheets, FREE Samples, MSC1210Y3 24 0.78 8 Diff/8 SE 8 1.2 $9.50 EVMs and the Data MSC1210Y4 24 0.78 8 Diff/8 SE 161.2 $10.75Acquisition Product Catalog MSC1210Y5 24 0.78 8 Diff/8 SE 32 1.2 $12.25 1-800-477-8924, ext. 7643

R EAL W ORLD S IGNAL P ROCESSINGTM

Real World Signal Processing and the red/black banner are trademarks of Texas Instruments. SPI is a trademark of Motorola. 0869-02R © 2002 TI lines. That option is available for the Rabbit 3000, as well; however, the Listing 1—Language purists will have none of it, but I like the fact Dynamic C is custom tailored to the chip also offers an auxiliary I/O bus hardware with language extensions for I/O, interrupts, memory management, and, in this case, multitasking. mode that splits I/O operations onto their own 8-bit data/6-bit address bus. main() This provides benefits that may { initPort(); //Initializes port G only prove compelling in certain designs. while (1) For example, if top performance is { your goal, you’ll likely find (as usual) costate that memory access time is a concern. { //DS1 LED Moving I/O devices onto their own DS1led(ON); //On for 50 ms bus reduces capacitive loading on the waitfor(DelayMs(50)); memory bus that would otherwise slow things down. DS1led(OFF); //Off for 100 ms Similarly, although the Rabbit 3000 waitfor(DelayMs(100)); can tolerate 5-V inputs, a particular } 3.3-V memory chip might not be so costate obliging. If mixing 3.3-V memories { //DS2 LED and 5-V I/O chips on the same bus DS2led(ON); //On for 200 ms proves to be problematic, then split- waitfor(DelayMs(200)); ting the busses is the way to go. Finally, practical product evolution DS2led(OFF); //Off for 50 ms and packaging considerations often waitfor(DelayMs(50)); call for an I/O bus or backplane that is } physically accessible and expandable. } Both of these criteria can compromise } critical memory bus performance and raise EMI concerns. With the split bus Need a better bridge?

ICON H-Bridge DC Motor Interface Module

Up to 40VDC Motors 12A Continuous/25A Peak Over Current -use Over Temperature -use 3 Serial or Direct Drive Mode Solutions 2.5” X 1.9” -ootprint SOLUTIONS CUBED • (530) 891-8045 PHONE • WWW.SOLUTIONS-CUBED.COM

80 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Application timing tasks are well Operation/program Dhrystone 1.1 Whetstone Sieve served by a plethora of clocks, counters, 1000 loops per second 1000 loops per second (milliseconds) and pins. In this case, a picture is easily Rabbit 3000 6570 813 53 worth the thousand words it would at 50-MHz Dynamic C take to describe all of the options (see AMD 188ES 3603 61 120 Figure 3). It’s definitely a sophisticated at 40-MHz Borland 3.31 C Zilog eZ80 2914 20 158 and high-resolution setup compared to at 40-MHz Zilog C compiler run-of-the-mill 8-bit micros. Dallas DS80C320 (8051) 1251 140 160 A registered output option means at 33-MHz Keil C even parallel output gets precise. You Phillips 80C51 598 61 350 at 33-MHz Keil C can configure output port updates to trigger off timers for superior timing Table 1—As usual, a simple benchmark summary raises as many questions as it answers. Nevertheless, it’s clear precision without the CPU having to that the combination of the Rabbit 3000 and Dynamic C is no tortoise when it comes to floating point. babysit the port in software. scheme, the relatively quiet auxiliary I/O bus can act as the backplane for external add-ons, while the faster and noisier memory bus can be kept tight and light (i.e., in close proximity with the CPU and minimally loaded with only a few memory chips).

TIME TRAVELER The Rabbit 3000 has a lot of features in the time domain, starting with the clock pins. Make that clocks, because the chip provides connections for sepa- rate low- (32.768 kHz) and high-speed (up to 30 MHz) inputs. An on-chip doubler boosts the to the 50-MHz-plus maximum specification. The low-speed input (i.e., watch crys- tal) drives the real-time clock (imple- mented as a 48-bit counter with dedi- cated battery backup pin) and watchdog timer while the high-speed clock drives the processor and peripherals. The low-speed clock can also drive the processor and peripherals, which is the basis for the low-power Sleepy mode that can throttle the CPU down to almost 2 kHz (i.e., 32.768 kHz divided by 16). Slowing the clock to reduce CPU power consumption isn’t a new concept, but Rabbit shows attention to detail with short and self-timed chip-select options that minimize memory chip power con- sumption as well. EMI reduction is a hot topic that I predict will only get hotter. The Rabbit 3000 is one of the first micros to incorporate spread-spectrum clock- ing as an option. When enabled, pseu- do-random jitter is automatically injected into the clock, spreading the radiated noise (see Figure 2).

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 81 ONE-STOP SHOPPING other big advantages to one-stop com- Yes, the Rabbit 3000 is a neat chip, piler and chip shopping. Have you but there are a lot of those on the ever struggled to make a C compiler market to choose from these days. deal with an interrupt? Access an I/O What I really like about the Rabbit device? Store a variable in flash mem- 3000 isn’t merely the chip itself, but ory rather than RAM? Perform multi- the entire package—documentation, tasking (see Listing 1)? For C on the tools, libraries, and so on—that make Rabbit, these are all built-in and bless- for a successful project. edly easy to use. Notably, Rabbit gains a lot of syner- I had the chance to plug and play gy by virtue of supplying both the with the Rabbit 3000 development chip and C compiler. Way back when, Photo 1—The Rabbit Core Module (RCM) 3000 kit, which I found to be polished, this was common, but it fell out of serves as the basis of the $299 development kit. With user-friendly, and a relative bargain built-in Ethernet (using a Realtek PHY) and up to favor as chip companies’ afterthought 512 KB each of flash memory and SRAM, it’s a natural at $299, considering that the C com- in-house compilers fell to superior for embedded web applications too. piler is included. As you can see in third-party offerings. Photo 1, the kit is based on the But remember that Rabbit/Z- beast. Instructions can easily balloon Rabbit Core Module 3000 (RCM), a World was doing C compilers long into double-digit clock cycles, viable contender for embedded before they did their own chip. The depending on how baroque they are Internet applications thanks to the result is a fine mesh between hard- (i.e., fancy addressing modes, multi- built-in Ethernet interface and roy- ware and software that’s rare to find ple memory accesses). Nevertheless, alty-free (source code is included) in an era of promiscuous couplings even with all of the usual bench- protocol stacks. between standard tool suites ported marking caveats, it’s safe to say the Although I’m not in a position to to any and all chips. Rabbit/Z-World compiler brings it make an authoritative statement When it comes to performance, a on, especially when it comes to about correctness and performance, good compiler can do wonders. Even floating point (see Table 1). the Rabbit networking support feels though the Rabbit 3000 is a frisky Even if you don’t care about per- relatively comprehensive, credible, chip, it is, after all, still a CISCy formance or Rabbit’s claims, there are and confidence-inspiring. That’s

82 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com more than I can say for a lot of the IMSAI could have only dreamed [3] J. Labrosse, MicroC/OS-II, mini-me network stuff I run across, about. And whether you’re using C or The Real-Time Kernel, CMP too much of which borders on snake ASM, even the most die-hard designer Books, Gilroy, CA, 2002. oil. Kudos to Rabbit Semi for offering must admit it’s a step up from tog- more hope and less hype when it gling front-panel switches. comes to putting embedded gadgets Yeah, there have been plenty of SOURCES on the I-way. twists and turns, not to mention a HD64180 Microprocessor Not that Rabbit 3000 support is an few fender benders, along the Route Hitachi entirely in-house proposition. ’80 way. But there always comes a (650) 589-8300 There’s also a chip-specific port of time when I look forward to zooming www.hitachi.com MicroC/OS-II, the popular RTOS up the next on-ramp in a shiny new Microcontroller/OS-II RTOs written by Jean Labrosse, and a C chip. Thanks for the ride, Rabbit. I Micrium, Inc. compiler from Softools. [3] (954) 217-2036 Tom Cantrell has been working on www.uCOS-II.com KEEP MOTORING chip, board, and systems design and About 25 years ago, I was running marketing for several years. You may Rabbit 3000 machine language blink-em programs reach him by e-mail at tom.cantrell@cir- Rabbit Semiconductor on my beautifully LED-laden IMSAI cuitcellar.com. (530) 757-8400 8080. That puppy must have weighed www.rabbitsemiconductor.com 50 pounds, thanks largely to the C compiler for Rabbit 3000 100-W boat anchor power supply. All REFERENCES Softools that big iron got you was barely more [1] M. Dalrymple, “Rolling Your (860) 236-4201 than 1 MHz and few kilobytes of Own Microprocessor,” Parts 1 www.softools.com RAM and ROM. and 2, Circuit Cellar 111 and Today, I’m looking at a few square 112. Z180, eZ80 Microprocessors inches, a couple of ounces, and less [2] F. Eady, “Rabbit Season,” Zilog, Inc. than 1 W delivering MIPS and memo- Parts 1-5, Circuit Cellar 123- (408) 558-8500 ry, not to mention I/O, that the old 127. www.zilog.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 83 IDEA BOX THE 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 e-mail [email protected]. For more information call Sean Donnelly 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!

Meet BOB-3. phyCORE Modules: NEW GENERATION BOB-3 is a team player. SINGLE BOARD COMPUTERS BOB-3 will only say what you want. I Insert-ready sub-mini SBCs (small as 47x55 mm.) supporting the BOB-3 plays well with NTSC and PAL. Philips 8xC5918xC591, 89C51Rx289C51Rx2, XACxXACx, XAGx, Infineon C167Cx, Motorola MPC555 & ST Microelectronic ST10F168 BOB-3 is your new best friend. I Low EMI design achieved via GND circuitry, 6 to 8 layer PCB, by- Decade Engineering's new BOB-3 module pass capacitor grid and short signal traces achieved via small easily overlays text on video. BOB-3 displays footprint and use of 0402 SMD passive components up to 17 lines of 40 characters, including 63 I 32 KB to 8 MB external SRAM & Flash (controller-dependent) custom characters. Other features include I FlashTools enable on-board in-system (ISP) programming vertical scrolling, a stand-alone display option, 2 I RS-232, RS-485, I C & CAN interfaces; ADC; Chip-Select signals faster serial communication, automatic video I Controller signals extend to standard (2.54 mm.) or high-density generation, and much more. Molex (0.625 mm.) header pins on two sides of the board, allowing the SBC to be plugged like a "big chip" into targets Get to know BOB-3 at I Available in Rapid Development Kits including Development Board, AC adapter, serial cable and SPECTRUM CD with eval software tools www.decadenet.com (Keil, TASKING), FlashTools, electronic documentation and demos Decade Engineering PHYTEC America LLC I 255 Ericksen Avenue I Bainbridge Island, WA I USA 98110 503-743-3194 www.phytec.com (800) 278-9913 Turner, OR, USA

84 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com PC KEYBOARD EMULATION Interface Keypads, Switches, or RS-232 to your PC Keyboard Input MODEL KE24 ONLY $9995 • Up to 12 x 12 matrix • Programmable • RS-232 Port • Macro Capability

The KE24 is the ultimate in flexibility. Inputs or serial data can emulate any of the 101 keys from a standard keyboard.

MODEL KE18 ONLY $4495

• Up to 9 x 9 matrix • 2.5" x 3.0" Size • PC Keyboard Port • PCXT, AT Compatible

The KE18 combines a multitude of features with small size at an economical price. Custom units available.

HAGSTROM Toll ree: 888-690-9080 Phone: 607-533-4441 $ax: 607-533-4443 ELECTRONICS www.hagstromelectronics.com 11 $iddlers Green Lansing, NY 14882

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 85 RS232 to Windows

WinWedge inputs real-time serial data from any device direct into Excel, Access, VB or any Windows program. www.taltech.com

New CE version!

86 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 87 88 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Rapid PCI Development

PCI Interface Chipset: • 128 KByte Read & Write FIFO’s • 132 KByte/sec DMA Master • FIFO Style Interface to FPGA • 24 Bits Programmable I/O Choice of FPGA: PCI ProtoBoard • Xilinx XC2S200 or Altera EP1K30. • Design Your Application with Free HDL Software from Xilinx or Altera. Driver Software & API Included: • Access DMA Data with C/C++ Stream Functions • C/C++ Functions to Control 24 I/O Bits Complete Prototyping Tools: • 24 I/O Pins Available from FPGA • LED's, Switches, Numeric Display Now Only • Removable Wirewrap Area $395 • Connectors to Attach Custom PCB’s • Documentation & Sample Apps. TECHNIPRISE INC. (614) 431 -5610 www.pciprotoboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 89 90 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com Email: [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 91 92 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com www.circuitcellar.com CIRCUIT CELLAR® Issue 147 October 2002 93 ADVERTISER’S INDEX The Advertiser’s Index with links to their web sites is located at www.circuitcellar.com under the current issue. Page Page Page Page 91 Abacom Technologies 1 Earth Computer Technologies 89 Micro Digital Inc 88 Sealevel Systems Inc. 85 Abia Technology 26,40 ECD (Electronic Controls Design) 92 microEngineering Labs, Inc. 35 Seattle Robotics 73 Accutek 86 EE Tools (Electronic Engineering Tools) 85 MicroSystems Development, Inc. 86 Senix Corp. 86 ActiveWire, Inc. 11 EMAC, Inc. 47 Mid-Atlantic System Consultants, Inc. 85 Sensory, Inc. 53 All Electronics Corp. 40 ePROTOS.com 87 MJS Consulting 84 Signum Systems 84 Allied Component Works 91 EVB Plus 72 Mouser Electronics, Inc. 40,91 Softools 86 Amazon Electronics 42 ESC Boston 58 MVS 66,80 Solutions Cubed 10 Amulet Technologies 26 ExpressPCB 93 Mylydia Inc. 92 Spectrum Engineering 92 AP Circuits 85 FDI-Future Designs, Inc. 65 NetBurner 84 Square 1 Electronics 90 Appspec Computer Tech. Corp. 85 Hagstrom Electronics 95 Netmedia, Inc. 88 SUMBOX Pty Ltd. 88 Atlantic Quality Design, Inc. 82 HI-TECH Software, LLC 87 OKW Electronics, Inc. 34 Systronix 7 Atmel 91 HVW Technologies Inc. 75 On Time 86 TALtech Instrumental Software 90 Avocet Systems, Inc. 87 IMAGEcraft 87 Ontrak Control Systems C3 Tech Tools 71 B+K Precision 91,92 Intec Automation, Inc. C2 Parallax, Inc. 89 Techniprise Inc. 87 Bagotronix, Inc. 90 Intronics, Inc. 84 Phytec America LLC 32,33 Technologic Systems 15,85 Basic Micro 29 Intuitive Circuits, LLC 84 Phyton, Inc. 91 Technological Arts 90 Bellin Dynamic Systems, Inc. 85 Ironwood Electrics 91 Picofab Inc. 88 Tern Inc. 74 CadSoft Computer, Inc. 39 Jameco 90 Prairie Digital, Inc. 17,79 Texas Instruments 86 CCS-Custom Computer Services 64 JK microsystems, Inc. 89 Pulsar, Inc. 90 Triangle Research Int’l Inc. 86 Cermetek Microelectronics Inc. 29 JR Kerr Automation & Engineering 89 R2 Controls 73 Trilogy Design 88 Concept Circuit Design 35 LabJack Corp. 18 R4 Systems Inc. 93 Weeder Technologies 92 Conitec 90 LabMetric 41 Rabbit Semiconductor 91 Xeltek 11 Connecticut mircoComputer, Inc. 35 Lakeview Research 82 Remote Processing 93 Xilor Inc. 91 Cyberpak Co. 93 Lemos International 89 RLC Enterprises, Inc. 87 Z-World 57 Cypress MicroSystems 2 Link Instruments 88 RPA Electronics Design, LLC 29 Zagros Robotics C4 Dataman Programmers, Inc. 93 Lynxmotion, Inc. 92 Rutex 86 Zanthic Technologies Inc. 90 DataRescue 81 MaxStream 5 Saelig Company 84 Decade Engineering 89 MCC (Micro Computer Control) 88 Scidyne 87 Delcom Engineering 9 Microchip Design Contest 3 Scott Edwards Electronics Inc. 16 DesignCon 2003 90 Microcross 27 SeaFire Micros, Inc.

Preview of November Issue 148 ATTENTION ADVERTISERS Theme: Embedded Development December Issue 149 MCS-51 SBC for the Classroom—Part 1 Deadlines The Air Data Computer Space Close: Oct.10 Material Due Date: Oct. 17 Embedding Real-Time Java in an MPU Efficient, Practical Adders for FPGAs Theme: A Low-Power Embedded Thermal Sensor Wireless Communication Robotics Corner: Ultrasonic Homing Device Reserve your space today! I Applied PCs: Geckodriving Your Motor Control Applications I From the Bench: Don’t Put All of Your Eggs in One Basket—Smart RF Call Sean Donnelly 860-872-3064 I Silicon Update: Sensors and Sensibility

94 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com

PRIORITY INTERRUPT Linguini with Clam Sauce

s most of you know, I lead a fairly reclusive lifestyle. Yes, by central Connecticut’s standard of shopping malls and a condos, we rustic upstate Yankees live in the boonies among the trees. Of course, someone from Washington state would laugh at what we call the woods. On the other hand, a New York City native living only 100 miles away would think he was on a wilderness trek when visiting our part of Connecticut. It’s all relative. While I live in a wooded area, about the only thing around here that’s really rustic are the trees. Our house is a hexagonal California redwood contemporary that exemplifies the personal style and expression of a mad scientist with carpentry tools. Think of a wooden octopus and you have a reasonably accurate description of the ground plan. It would look out of place next to a traditional New England saltbox or Cape Cod, but, isolation has its advantages (very few neighbors). And, to me it’s always been the official Circuit Cellar. Being an engineer whose expertise is embedded process control has left its mark. Our home contains about as much copper as wood. There are wires everywhere. The security system connects to the home control system; the driveway sensors talk to the video and security system; the video and entertainment electronics talk to the home control and lighting system, and so on. Everything was mostly direct-wired, so the result is one gigan- tic wiring maze. In all the time I’ve lived there, I’ve installed computerized controls on everything except the heating and air-conditioning systems. It’s not that I can’t instrument them, but rather that I’ve had little success proving enough tangible benefit to justify complicating an otherwise uncomplicated environmental system. We just built a large kitchen addition, and I thought I would try it once again. As the contractor was constructing the kitchen, I added what seemed like another mile of copper for temperature sensors, heat and vent controls, and a shade canopy extension. In combination with sensors detecting outside temperature and humidity, I presumed I could calculate heating and cooling ramps and anticipate demand more efficiently. Then, I could tie it all into the home control system and let it control everything. When the crew finished, I was ready to begin doing my thing. Typically, that means blowing holes in the walls for the control devices, kludging control schemes for equipment that wasn’t originally intended to be computerized, and stringing yet more wires. Ten years ago this would have been a no-brainer. I would have jumped right in and then written articles about the electronic transformation. Today, I’m a little more practical about such adventurous ideas. This time, I decided to make linguini with clam sauce (it’s a kitchen after all) and think about it for a while. In fact, I decided to cook for a couple of months. It was déjà vu all over again. I could rip apart the whole place and call it “computerized,” but in this particular Connecticut location, I doubt that I’d see a significant advantage over traditional controls. The benefit provided by trees that give shade, extending the shade canopy, and opening a few windows seemed to be adequate for all but extreme weather. The real extremes I hadn’t encountered before, however, were the ones the kitchen created. Kitchen vent hoods have reached new levels of performance. While they certainly exhaust smoke and smells efficiently, it’s what they don’t tell you in the kitchen store that you have to be careful about. When my 1300-CFM blower winds up, if it hasn’t sucked everything including the furnace out the vent, somewhere between the first and second flips of the steak au poivre, it’s dropped that cozy kitchen about 30° in the middle of January. Of course, the opposite can be true in the summer. Turning on a six-burner Viking stove is about the same as firing up a medium-sized furnace in the middle of your kitchen. Ultimately, the environmental control solution isn’t a duel between Linux and Windows CE. The solution is straightforward: Add about 60′ of baseboard heating and a 2-ton air conditioner. The primary lesson I learned during the couple of months of gathering data was basically that I like to eat too much. Being able to claim that it’s all computerized won’t make it a better place to cook and entertain. As for the environment, it seems that the extremes are the dominate issue, and centralized environmental control wouldn’t add any advantage over the distributed individual heating and cooling controls standard with conventional installations. Every time I’ve tried to justify it, I’ve come away with the same answer: In this tech-crazy world it’s hard to admit it, but, if it ain’t broke, don’t fix it.

[email protected]

96 Issue 147 October 2002 CIRCUIT CELLAR® www.circuitcellar.com

STILL THE WORLD’S MOST POWERFUL PORTABLE

$795 PROGRAMMERS? inc 4mb ram

NEW MODEL $1295

Surely not. Surely someone somewhere has developed a portable programmer that has even more features, even greater flexibility and is even better value for money. Actually, no. But don’t take our word for DATAMAN-48LV it. Use the feature summary below to see how other manufacturers’ products compare. • Plugs straight into parallel port of PC or laptop S4 GAL MODULE MONEY-BACK • Programs and verifies at 2, 2.7, 3.3 & 5V 30 DAY TRIAL • True no-adaptor programming up to 48 • Programs wide range of 20 and 24 pin pin DIL devices logic devices from the major GAL vendors If you do not agree that these truly are the most powerful portable programmers you can • Free universal 44 pin PLCC adaptor • Supports JEDEC files from all popular buy, simply return your Dataman product • Built-in world standard PSU - for go- compilers within 30 days for a full refund anywhere programming SUPPORT • Package adaptors available for TSOP, PSOP, QFP, SOIC and PLCC • 3 year parts and labor warranty • Optional EPROM emulator • Windows/DOS software included DATAMAN S4 • Free technical support for life • Next day delivery - always in stock Orders received by 4pm will normally be despatched same day. • Programs 8 and 16 bit EPROMs, Order today, get it tomorrow! EEPROMs, PEROMs, 5 and 12V FLASH, Still as unbeatable as ever. Beware of Boot-Block FLASH, PICs, 8751 cheap imitations. Beware of false microcontrollers and more promises. Beware of hidden extras. • EPROM emulation as standard If you want the best, there’s still only one choice - Dataman. • Rechargeable battery power for total Dataman Programmers Ltd portability Order via credit card hotline - phone 215 East Michigan Avenue • All-in-one price includes emulation today, use tomorrow. Orange City, FL 32763 leads, AC charger, PC software, spare Telephone (904) 774-7785 Alternatively, request more detailed Fax (904) 774-7796 library ROM, user-friendly manual information on these and other market- Home page: http://www.dataman.com • Supplied fully charged and ready to use leading programming solutions. Email: [email protected]