Top Banner
7 9 25274 75349 07 > CIRCUIT CELLAR ® www.circuitcellar.com THE MAGAZINE FOR COMPUTER APPLICATIONS $4.95 U.S. ($5.95 Canada) #168 July 2004 GRAPHICS & VIDEO Waveform Monitor Smart Touchscreen User Interface Color Video Frame Grabber Multimedia Thermometer WWW.GiURUMELE.Hi2.RO
100

GRAPHICS & VIDEO

Mar 12, 2023

Download

Documents

Khang Minh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: GRAPHICS & VIDEO

7 925274 75349

07>

®

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

Waveform Monitor

Smart Touchscreen User Interface

Color Video Frame Grabber

Multimedia ThermometerWW

W.G

iURUMELE

.Hi2

.RO

Page 2: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 3: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 4: GRAPHICS & VIDEO

Digital Oscilloscopes

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

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

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

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

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

Logic Analyzers

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

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

All prices include Pods and Software

WW

W.G

iURUMELE

.Hi2

.RO

Page 5: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 6: GRAPHICS & VIDEO

Presentation is everything. You don’t have to look any further thanyour local mall or supermarket to see the major effect of display.Manufacturers spend millions creating packages that sell—packagesthat clearly and concisely relay essential information about the productthey contain and look good doing it. You might call it user-friendly pack-aging. The package is an extension of the advertising campaign that hasbeen painstakingly researched and tested to ensure sales. In fact, theway in which products are displayed has become so important that col-leges now offer degrees in supermarket display and packaging.

When designing electronic displays, the same principles apply. Thegoal is to create a display that is eye-catching, readable, easy to under-stand, and most likely easy to program (if you’re making the display fora client). We have a couple of articles this month that discuss excellentdisplay projects ideally suited for use by consumers. Alberto Ricci Bitti’sDVD-Thermometer (p. 12) and Bruce M. Pride’s Smart-E-Touch (p. 56)are definitely attractive designs that meet the demand for user-friendlytechnology. Anyone who followed the Motorola Flash Innovation 2003Design Contest will be especially interested in these contest winners.

Alberto designed a system to display temperature on a TV with full-color graphics, which can be still or animated. Graphics that correlate tovarious temperatures (for example, a chilly Linux penguin with the back-drop of snow-capped mountains for 15°F) are stored on a DVD. Albertoimagines his DVD-Thermometer being used in public spaces like mallsor retail shops, perhaps incorporating advertising. The DVD-Thermometer’s versatility lends itself to a variety of other uses as well.You can use the system to gather and display any type of data.

Bruce’s Smart-E-Touch is an intelligent touchscreen user interfacethat’s perfect for just about any setting. The design relies on a MotorolaNitron microcontroller to control and monitor Motorola e-field sensors.Using the e-field sensors enabled Bruce to build the user interface direct-ly on the circuit board, which makes the system extremely reliable, not tomention easy to create.

In addition to these great projects, we have a number of other equal-ly terrific graphics and display projects. The video frame grabberdesigned by Eric Gagnon digitizes a single image of full-field color videointo a field buffer, and offers a cost-effective solution to traditional off-the-shelf systems (p. 22). The waveform capture and display system creat-ed by Dick Cappels is designed around three Atmel microcontrollers (p.42). This simple project, which consists of a graphic display unit and acapture and control unit, is a great addition to your workbench. Last, butnot least, we have a graphics library written in C for the Zilog Z8 Encore!family designed by Brian Millier (p. 62). Brian’s library enables Z8 micro-controllers to utilize the full functionality of graphic LCD panels.

4 Issue 168 July 2004 www.circuitcellar.comCIRCUIT CELLAR®

EDITORIAL DIRECTOR/FOUNDERSteve Ciarcia

MANAGING EDITORJennifer Huber

TECHNICAL EDITORC.J. Abate

WEST COAST EDITORTom Cantrell

CONTRIBUTING EDITORSIngo CyliaxFred Eady George MartinGeorge NovacekJeff Bachiochi

NEW PRODUCTS EDITORJohn Gorsky

PROJECT EDITORSSteve BedfordKen Davidson David Tweed

ADVERTISINGPUBLISHER

Dan Rodrigues E-mail: [email protected] PUBLISHER/DIRECTOR OF SALES

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

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

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

CONTACTING CIRCUIT CELLARSUBSCRIPTIONS:

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

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

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

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

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

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

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

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

CHIEF FINANCIAL OFFICERJeannette Ciarcia

CUSTOMER SERVICEElaine Johnston

CONTROLLERJeff Yanco

ART DIRECTORKC Prescott

GRAPHIC DESIGNERMary Turek

STAFF ENGINEER John Gorsky

QUIZ COORDINATORDavid Tweed

Cover photograph Chris Rakoczy—Rakoczy PhotographyPRINTED IN THE UNITED STATES

Presentation is Everything

[email protected]

TASK MANAGER

WW

W.G

iURUMELE

.Hi2

.RO

Page 7: GRAPHICS & VIDEO

Their boards come with apacking slip. Ours comewith a MicrosectionAnalysis ReportIn today’s competitive climate, offering thebest product at a competitive price is a mustto satisfy your customers. Sierra ProtoExpress offers the fastest, most reliable, turnsat the highest quality. And we’ll prove it inevery shipment with our unique Evidence ofQuality reports, so you know your board isright the first time. One proof of quality isour Microsection Analysis Report, asfeatured here, so you can see the qualityinside your board. And that is just part ofour comprehensive quality tests. It’s in ourprocess, not in our price. In fact, it is ourcommitment to total quality that enables usto run our operation cost effectively. Andthat comes back to you in our competitiveprice. Talk to a Sierra Proto Express AccountManager about our commitment to quality,our range of technology, and our 99% on-time track record of delivery. Call1.800.763.7503 from 6 a.m. to 6 p.m. PSTor email your design [email protected] and receive a quote.Mention code: PPDC00093

For proven quality that never costsextra, put Sierra Proto Express onyour team today.

14 Layer BoardMicrosection

Qual i ty On Time

Learn more about our unique Evidence of Quality report that comes with every PCBat www.protoexpress.com

q

ua l i t y l e a d e

r

MIL -P -55110 ISO90

02•800-763-7503 www.protoexpress.co

m•

WW

W.G

iURUMELE

.Hi2

.RO

Page 8: GRAPHICS & VIDEO

6 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

July 2004: Graphics & Video

4 TASK MANAGERPresentation is EverythingJennifer Huber

8 NEW PRODUCT NEWSedited by John Gorsky

11 TEST YOUR EQedited by David Tweed

78 SILICON UPDATEMotoring (Part 1)Motor BasicsTom Cantrell

FEATURES

COLUMNS

DEPARTMENTS

94 INDEX OF ADVERTISERS August Preview

96 PRIORITY INTERRUPTWar DrivingSteve Ciarcia

50 APPLIED PCsUncomplicated dsPIC ImplementationFred Eady

74 FROM THE BENCHLose the CrystalLinear’s LTC6903/4 Programmable OscillatorJeff Bachiochi

12 Adaptable Multimedia ThermometerAlberto Ricci BittiFlash Innovation 2003 Design Contest Winner

22 Full-Field Color Video Frame GrabberEric Gagnon

32 Easy ReflowBuild an SMT Reflow Oven ControllerRobert LacosteRenesas Design 2003 Grand Prize Winner

36 Designing with the Nios (Part 2)System EnhancementGeorge Martin

42 Triple AVR Waveform Capture and DisplayThree Controllers Make a Waveform MonitorDick Cappels

56 Smart-E-TouchAn Intelligent User InterfaceBruce M. PrideFlash Innovation 2003 Design Contest Winner

62 Graphics LCD Library for the Z8 Encore!Brian Millier

DVD-Thermometer (p. 12)

Smart User Interface (p. 56)

Waveform Monitor (p. 42)

WW

W.G

iURUMELE

.Hi2

.RO

Page 9: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 10: GRAPHICS & VIDEO

converts base-band analog video into digital video, sup-porting up to 10 component video inputs including com-posite (NTSC, PAL and SECAM), S-Video, and component(YPbPr) video signals.

The device also includes an analog video output for TVvideo out signals and connection to other external devices.Video signal processing has been optimized to produce high-quality video from weak broadcast signals or nonstandardVCR video. Additionally, the decoder outputs ITU-R BT.656and supports Macrovision copy protection as well as advancedVBI functionality. The TVP5147 includes two 10-bit, 30-mspsADCs. Each analog channel contains an analog circuit,which, prior to each converter, clamps the input to a ref-erence voltage and applies a programmable gain and off-set. The TVP5147 digital video decoder includes a 2-D five-line adaptive comb filter.

Evaluation boards, software tools, and application notesare available for the TVP5147. The device costs $9 in1,000-piece quantities.

Texas Instruments, Inc.www.ti.com

8 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

NEW PRODUCT NEWSHIGH-QUALITY DIGITAL VIDEO DECODER

The new TVP5147 is a high-performance digital videodecoder (NTSC/PAL/SECAM) that digitizes and decodesall popular base-band analog video formats into digitalcomponent video. The device is a mixed-signal videodecoder optimized for use in the U.S., Japan, and China. It

Edited by John Gorsky

HIGH-RESOLUTION DISPLAYHalf and full VGA-size LCDs put the power of high-reso-

lution graphics and detailed screen content in the handsof embedded developers. High-resolution LCDs make theGUI ideal for developing innovative point-of-sale termi-nals and introducing unique touchscreens for high-endconsumer electronics.

Creating attractive GUI screen content is as easy andas time-saving as with the Graphics OS in silicon; how-ever, the final output can now be more elaborate andornate. These higher-resolution displays enable morecontent per GUI page as well. This solution comes withits own microprocessor, graphics library, and LCD con-troller so that the host microprocessor or microcon-troller is never burdened by the GUI’s operation.

The half VGA-size LCD is 5.4″ with a resolution of 320 ×480 pixels. The full VGA-size LCD is 7.5″ with a 480 ×680 resolution. The new displays complement a line ofmodules that supports a 5.7″ QVGA LCD with a resolu-tion of 240 × 320 pixels.

The half VGA-size LCD is available for $150 each forproduction volumesof 10,000 units ormore. The full-sizeVGA LCD is availablefor $250 each for pro-duction volumes of10,000 units or more.

Amulet Technologies(408) 244-0363www.amulettechnologies.com

LOW-CURRENT, SINGLE-DIGIT, SEVEN-SEGMENTDISPLAYS

The new TDSR family of high-intensity, low-current,single-digit, seven-segment displays provide excellent read-ability even in direct sunlight. The displays, which useAllnGaP technology in the color red, offer high performancefor extremely low-power applications, delivering a typicalluminous intensity of 1,500 µcd while being driven withjust 1 mA of current.

Featuring a wideviewing angle, thenew displays can beused in panel meters,test and measure-ment equipment,point-of-sale termi-nals, control units,and battery-operatedsystems requiringextremely low-power consumption.

The six TDSR displays offer designers a choice of com-mon anode (TDSRxx50) or common cathode (TDSRxx60)versions with minimum and maximum luminous intensityratings from 180 to 3,600 µcd, respectively, enabling opera-tion in direct sunlight or in “black front” designs usingtinted filter glass. A maximum forward current of 10 mA isallowed for an ambient temperature range of –40° to 85°Cwithout current derating.

Pricing in 10,000-piece quantities is $60 per 100 pieces.

Vishay Intertechnology, Inc.(619) 336-0860www.vishay.com

WW

W.G

iURUMELE

.Hi2

.RO

Page 11: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 9

NEW PRODUCT NEWSINDUSTRIAL GRADE FLAT-PANEL DISPLAY INTERFACE

The new industrial grade AD9883A is the industry’sfirst fully integrated analog interface to operate over theindustrial temperature range of –40° to 85°C. The device

enables superior image quality in rugged environmentsthat require wider temperature ranges and robust designfeatures. The AD9883ABST is ideally suited to automotiveand aerospace applications where displays operate in rigor-ous, taxing environments and need to withstand extremefluctuations in temperature.

The AD988A is optimized for XGA and SXGA LCDs,HDTV, and Advanced TV applications. The AD9883ABSTfeatures three high-bandwidth, 8-bit, 140-msps ADCs and anultralow jitter PLL (less than 500 ps at 140 MHz), ensuringmaximum robustness and image quality. Its architecture iscompatible with LCD, plasma, projection, and other types ofdigital display technologies. The IC performs other functions:composite sync processing, mid-scale clamping, input signaldetection, automatic power-down control, and programmablegain/offset control—all of which help maximize ease-of-useand robustness in graphics and video applications.

The AD9883ABST flat-panel interface, which is availablein 80-pin LQFP packaging, is sold in both industrial andcommercial temperature-grade versions.

The part costs $8.50 per unit in 1,000-piece quantities.

Analog Devices, Inc.(800) 262-5643www.analog.com

WW

W.G

iURUMELE

.Hi2

.RO

Page 12: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 13: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 11

What’s your EQ?—The answers are posted at www.circuitcellar.com/eq.htm

You may contact the quizmasters at [email protected]

CIRCUIT CELLAR—Test YYour EEQ

Problem 3—Each phase of a three-phase power

system is a sine wave displaced by 120° from the pre-

vious one. If you connect a resistor across two of the

phases, what is the waveform of the current that flows

in it?

Problem 4—Demonstrate the answer to Problem 3

mathematically.

Contributed by David Tweed

Edited by David Tweed

Problem 1—A residential power meter contains two

coils that together produce a torque on the rotor disc

that is proportional to the instantaneous power flowing

in the load. The mechanical inertia of the disc aver-

ages this torque over several cycles.

Power factor correction (PFC) circuits come in two

flavors, one that corrects for reactive (inductive or

capacitive) loads, and one that corrects for nonsinu-

soidal current waveforms.

If the load is an inductive load, such as a lightly

loaded motor, what is the effect of adding a PFC of the

first type to it on the power meter reading? In other

words, does the meter run faster, favoring the power

company, or does it run slower, favoring the customer?

Problem 2—If the load is a nonlinear load—such as

a large capacitor-input power supply that draws cur-

rent in relatively narrow spikes at the peaks of the AC

voltage waveform—what is the effect of adding a PFC

of the second type to it on the power meter reading?

WW

W.G

iURUMELE

.Hi2

.RO

Page 14: GRAPHICS & VIDEO

mind. As a result, all of the modulesreside in separate files that are ready tobe ported to other applications by chang-ing only a few #define commands.

Now I’ll describe how I managed totransform a DVD player into an eye-catching video thermometer. Even if youaren’t interested in taking temperatures,you can adapt these basic techniques todisplay any sort of data. These techniquesare worth adding to your bag of tricks,just in case. Along the way, you can col-lect some valuable, reusable softwaremodules, like a versatile programmablepulse generator, an I2C bus driver, and aRECS80 remote control transmitter.

SYSTEM BASICSLet’s examine the building blocks of

the system (see Figure 1). A specializeddigital temperature sensor IC measuresambient temperature and converts itinto a digital word that can be read bythe microcontroller via the I2C bus.The microcontroller doesn’t have ahardware I2C, so the I2C driver is imple-mented in software. This driver worksas the foundation for the thermometerchip driver, which is, in turn, requiredby the main application firmware.

Another software module makes themicrocontroller’s internal 16-bit timerwork as a programmable pulse generator(PPG). The RECS-80 remote-controlencoder block assembles these pulses inorder to drive an infrared LED connectedto a port pin. The sleep manager moduleensures that all of the previous blocks

12 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

I built an innovative multimediathermometer that displays tempera-ture readings on an ordinary TV withcrisp, full-color graphics. To add a lit-tle magic to a reading, you can ani-mate pictures and program CD-qualityaudio announcements to accompanyeach temperature change. The picturescan vary according to your application.

The system is perfect for a wide rangeof settings. If you use it in a retail shopor mall, you can complement logos andproduct advertisements with tempera-ture information. On the domesticfront, photos of the kids playing at thebeach or, should the temperature drop,making a snowman are nice gifts forGrandma. The thermometer would alsowork well at hotels, airports, sportingvenues, and tourist sites (see Photo 1).

DVD-THERMOMETERDespite its rich feature set, my

DVD-Thermometer is an amazinglysimple design that requires few com-ponents. Another advantage is that it’shundreds of dollars cheaper than typi-cal PC-centric solutions. I made theDVD-Thermometer at home, just forthe fun it, without special tools. All Iused were a soldering iron, a multime-ter, a PC with ordinary CD-R burner,and the Motorola QT demo board.

The circuit, which is battery-operated,fits comfortably in a small plastic boxthat’s located in front of an ordinary DVDplayer. A switch and infrared LED peepout of the box. The DVD player is loaded

Adaptable MultimediaThermometer

Alberto’s 68HC908QT4-based multimedia thermometer displays temperature readings in fullcolor on a TV screen. What’s more, you can add animated pictures along with high-qualityaudio to announce each temperature change. If you don’t need a temperature-taking system,you can use the design techniques described here to display any other type of data.

with a disc that’s prerecorded with pic-tures that correspond to different temper-atures. Acting as an intelligent infraredremote control, the DVD-Thermometerdirects the player by selecting the scenethat matches ambient temperature.

The circuit diagram is embarrassinglysimple: it’s entirely built around an inex-pensive eight-pin microcontroller, a digi-tal temperature sensor, and an infraredLED. All of the hard work has to do withthe software, which is the most impor-tant ingredient of the project. I wrote theprogram in C language, implementinglow-power techniques with code reuse,portability, and data encapsulation in

FEATURE ARTICLE by Alberto Ricci Bitti

Photo 1—One of the great features of this project isthat you can customize the graphics. Here is Tux, theLinux penguin, commenting on the temperature.

WW

W.G

iURUMELE

.Hi2

.RO

Page 15: GRAPHICS & VIDEO

it receives from the circuit.The adjustment is repeated

until the temperature on theTV matches ambient temper-ature. There is no feedbackfrom the DVD player tellingthe microcontroller whichimage it’s playing, so themicrocontroller and playermust start from a well-knowntemperature/picture pair. Toensure the DVD player alwaysstarts from the first picture inthe sequence, the microcon-troller stops and restarts the

disc during start-up.

REMOTE CONTROL HACKINGI started the design process by

reverse-engineering the remote controlthat came with my DVD player.

picture on the TV. The DVD driver usesthe RECS-80 embedded remote controlto direct the DVD player to the appro-priate position. The DVD player cannottell the difference between a realremote control and the infrared stream

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 13

are called in a timely mannerand that power isn’t wasted.

The infrared LED is placedin front of an ordinary DVDplayer connected to a TV. TheDVD player is loaded with aspecial disc containing a prere-corded sequence of pictures,each of which shows a differ-ent temperature value. Whenplayed normally, the discshows all of the temperaturesin the thermometer range,from the lowest to the highest.Refer to the “Disc Production”sidebar for more information.

When the system runs, the mainprogram continuously evaluates ambi-ent temperature. If it differs from theon-screen temperature, the systeminstructs the DVD driver to change the

Temperaturesensor

Microcontroller

Main program

Thermometerdriver

I2C Busdriver

Sleep manager

DVD Driver

RECS-80Remotecontrol

Programablepulse

generator

SDA

SCL

InfraredLED

DVD Player

DVD Media(recorded with graphics

and sound)

TV

Figure 1—One of the building blocks is an entire DVD player that’s used as avideo generator. The remaining hardware consists of a digital temperature sen-sor, an infrared LED, and a microcontroller. The software is the most importantingredient because of the many levels of nested drivers.

DISC PRODUCTIONThe disc is an essential part of the system because the

images, videos, animations, and sounds are recorded on it.Skipping the artistic part of the process, let’s focus on thetechnical aspects of the procedure.

Of course, you can use your favorite recording and video-editing software to burn the disc. Strictly speaking, it willwork if it can burn a disc with a sequence of images that yourDVD can browse back and forth through by way of the Nextand Previous keys.

I searched for the easiest way to record a test disc. A DVDburner is unnecessary. If your thermometer doesn’t require theDVD player’s full 4.7-GBcapacity, an inexpensive CD-Rburner is sufficient. I used CD-RW media to perform differentexperiments recycling thesame disc. You must ensurethat your DVD player can readCD-R or CD-RW discs.

I prepared a set of 62 frames,each of which is stored in aseparate JPG file on the PChard drive, representingtemperatures between –10° and 50°C, plus one frame withthe message “battery low” (see Figure 1). Newer DVDplayers can automatically play JPG and MP3 files locatedin the root directory of a CD-R or CD-RW disc. This isdefinitely the easiest way to get started with the DVD-Thermometer. It’s worth a try.

Unfortunately, my DVD player refused to read such a disc,so I made a second attempt at recording the CD-RW disc inthe video-CD format. This method worked well.

I prepared my disc with Nero Burning ROM 5.5, a popular

software solution for burning CD-Rs. It features a CD-Rwizard that makes the process a piece of cake.

Click on the File/New menu, and the New Compilationwindow will appear. From the left banner, select the Video-CD format. Don’t touch the defaults (except deselectingthumbnail generation if it’s enabled. Confirm the new com-pilation by clicking on the New button. The program contin-ues with the familiar selection of the files to be included onthe disc, with an Explorer-like directory tree interface. Dragand drop all of your 62 JPG files on the new project. Payattention to the order: the first file you drop must be the first

file that appears in the finalsequence. Multiple selectionand cut and paste work well,provided that you select theoriginal files in the rightorder. I suggest you give thefiles new names so they canbe sorted alphabetically.Then, sort the folder by filename and do a multipleselect by dragging the mousefrom top to bottom.

That’s it. If you click on the Burn icon, the programwill format the disc according to the Video-CD specifica-tions and create all the necessary support files requiredby the DVD player. I recommend that you choose thelowest possible burn speed. When you’re finished, test iton the DVD player to verify that all of the images are inthe correct sequence, passing from one another, by press-ing the Next and Previous keys. This is also the besttime to read the user manual in order to discover the pro-cedure for disabling the on-screen display.

Figure 1—I implemented readings from –10° to 50°C in 1°C steps. Therefore, I setDVD_LAST_PICTURE to 61 (62 pictures in total). The last picture appears when themicrocontroller detects an insufficient battery level (approximately 4.3 V on my proto-type). You may download this sample picture set from the Circuit Cellar ftp site.W

WW

.GiU

RUMELE.H

i2.R

O

Page 16: GRAPHICS & VIDEO

14 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

weekend and wasn’t able get one untilthe following Monday. So, I used thePC sound card to analyze the signal.

I connected an infrared LED (the sameone I used in the final circuit) to the micinput in order to use it as a sort of photo-voltaic sensor. I placed the remote con-trol in front of it (as close as possible) andwatched the signal with a sound-editingprogram. The waveform suffered becauseof the rude measurement technique, butit was clearly discernible as one of thepopular codes described in Other’s article.

Fortunately, I didn’t need to open it.All I wanted to know was how itencodes its various keys. The marketis shared among a handful of differentinfrared modulation schemes, but Iwas lucky enough to find that theremote control conformed to one ofthe standards whose documentationwas readily available in A. N. Other’sarticle “IR Remote Control Codes”(Elektor Electronics, March/April 2001).

Although an oscilloscope is prefer-able, I started the design on a rainy

The good news is that the remote controlor my Irradio DVD player conforms tothe RECS80 format. The bad news is thatthe RECS80 waveform is difficult toencode because it involves synthesizingpulses whose duration spans many ordersof magnitude, from microseconds tohundreds of milliseconds.

A complete waveform anatomy is doc-umented in Philips’s “SAA3004 RemoteControl Transmitter” datasheet. In brief,a RECS80 code word is a sequence ofshort pulse bursts. The basic burstrequires six cycles of the 38-kHz carrierfrequency with a 33% duty cycle. Thisrequires asymmetrical, nail-shapedpulses just 8.77 µs wide.

Bits are encoded using PPM modula-tion. In PPM code, the time betweentwo consecutive bursts represents a sin-gle bit of a code word. In the case ofRECS80, an interval of 5.06 ms repre-sents a zero, whereas a 7.6-ms intervalmeans a one. An entire code wordcounts 12 pulses, encoding 11 bits ofinformation including a bit that toggleseach time a new key is pressed. Toensure that the code is received withouterrors, the same word is repeated manytimes, with a repetition period of 0.12 s.Note that because encoded PPM codewords differ in length, the duration ofthe pause between repetitions mustchange accordingly to compensate.

As you observe your remote controlwaveform, I suggest you take note ofthe key codes involved in the DVDscene selection process. I guess thereare standard tables somewhere, butbecause there are only four keys touse, I found it convenient to transcripttheir binary values watching the emit-ted waveform. After the start pulse,every short pause means a zero,whereas a longer one means a one.

Photo 2 highlights the keys of inter-est. The Next key, which allows youto skip to the next scene in the DVDsequence, is opposite the Previous key,which allows you to go back. TheNext/Previous pair is all you need tosearch for a specific picture.

A few other keys are useful duringstart-up because the software usesthem as a sort of reset, forcing theplayer to always start from the firstscene on DVD disc. In the case of myDVD player, these keys include Stop,

WW

W.G

iURUMELE

.Hi2

.RO

Page 17: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 15

which stops disc playing, and Play,which starts playing the disc from thebeginning after the disc has stopped.

HARDWARE SIMPLICITYWith just eight parts and a battery,

the hardware could not be simpler (seeFigure 2). Circuit optimization is acorollary coming straight from the levelof integration of its main components.

The temperature sensor IC is eithera DS1621 or DS1631. This eight-pin-ner includes a complete digital tem-perature sensor/thermostat with I2Coutput. With the appropriate com-mands, the temperature can be readfrom the serial interface with a guar-anteed accuracy of 0.5°C and a resolu-tion of up to 0.1°C. It does not requirecalibration, which is advantageousbecause you can trust your ther-mometer without messing with iceand boiling water. Pin 3 works as athermostat, but this feature is unusedin this application. Pins 5 through 7determine the low bits of the device’sI2C address. (Up to eight sensors can beconnected in parallel on the same I2Cbus.) Setting the connections as shownin Figure 2 configures the device torespond at address 0x90.

I used the MC68HC908QT4, a tinyeight-pin device with 4 KB of flashmemory and 128 bytes of RAM. Anice characteristic is that all of itspins (except power) can be used asI/O, because proper reset is guaran-teed by means of internal brownoutcircuitry and a flash-calibrated inter-nal oscillator provides a reasonably

stable clock source. Timing precisionis important to get correct remotecontrol waveforms. The 1% specifica-tion for the internal oscillator is notfar from the accuracy of ceramic res-onators, which are commonlyemployed in remote controls.

Two I/O pins serve as I2C bus dataand clock. All MC68HC908QT4 pinsfeature programmable pull-ups, so exter-nal resistors on the I2C bus are unneces-sary. Another I/O port drives the IRLED (ports can source up to 25 mA)through a current-limiting resistor. Peakcurrent is set to 8 mA—much lowerthan a real remote control—because thedevice is designed to operate in closeproximity to the DVD player. ExcessiveLED power may interfere with other IRdevices in the same location (e.g., airconditioners, TVs, VCRs, DVD play-ers, and devices commonly found inhomes, offices, and shops).

The circuit will not add anothercable to your AV tangle: it’s batterypowered. Four AA cells supply a totalof 6 V. A voltage regulator is unneces-sary; but, if you feel uncomfortablepowering chips close to their maximumtolerable voltage, you can always addone. I found that an electrolytic capac-itor and two filter capacitors areenough to provide clean power.

An extremely useful feature of theMC68HC908QT4 is hardware supportfor one-pin ICD (in-circuit debug),which makes an emulator unnecessaryfor most developers. An MC68HC908QT4chip programmed with a tiny usermonitor allows you to load applica-tion programs, place breakpoints, andwatch variables with almost no over-head for the program running. ICDmode requires just one pin (PTA0) fordata transfer, a push button to keepPTA2 grounded during reset, and a

trivial interface for the PC serial port.(Refer to the Motorola applicationnotes listed in the Resources sectionof this article for a circuit schematicthat’s compatible with the DVD-Thermometer and detailed program-ming explanations.)

If this is your first project with anHC908 microcontroller, it is simplerto start with a part with the user mon-itor already programmed and goodhardware (e.g., the inexpensiveM68DEMO908QT4 starter kit). Inthis case, I suggest you replace thesleep() routine with a classic“empty-for” delay loop, because thestop instruction should not be usedwith the demo board.

SOFTWARE ESSENTIALSBecause this project requires a mini-

mal amount of hardware, most of thehard work is done in software. I devel-oped the software with the freeMetrowerks Codewarrior integrateddevelopment environment. The IDEincludes an assembler, ANSI-C com-piler, simulator, chip programmer, in-circuit emulator/debugger, and evenProcessor Expert, which is an auto-matic C code generator.

You may download the code fromthe Circuit Cellar ftp site. I selected Clanguage to make the code reusableand more flexible. By the way, I hadsome I2C sources coming from a previ-ous application on a different micro-controller.

I have a quite formal program-ming style. When time allows, I domy best to write structured code,using #defines to name every con-stant, ban global variables, and par-tition the code in .c modules and .hheader files. Source file namesclosely reflect the elements in the

Photo 2—The microcontroller emulates four remotecontrol keys: Stop, Play, Next, and Previous. TheRECS80 routine can generate any key code given itsbinary value.

Figure 2—There are eight parts plus the battery. Most of the hard work has to do with the software. The only activeparts are a digital temperature sensor and an 8-bit microcontroller. As long as batteries are used, a power regulatoris unnecessary.

WW

W.G

iURUMELE

.Hi2

.RO

Page 18: GRAPHICS & VIDEO

To ensure that discplaying starts fromthe first scene,DVD_init() stopsand restarts theplayer, emulatingthe respectiveremote control keys.

The distinctremote.c file imple-ments the RECS80remote controlencoder. To makethe IR LED flash theplay command, callremote_control(KEY_PLAY).

I defined codes forthe Stop, Play, Next,and Previous keys.The routine can gen-erate any other codeif given its binaryvalue. It automatical-

ly swaps the toggle bit each time it iscalled. Each code is repeated five timesto ensure it is received correctly.

I’m extremely satisfiedby the RECS80 encoderimplementation (seeListing 1). The secret isusing a programmablepulse generator (PPG)that works in the back-ground under interruptcontrol; it does all themagic transparently andallows for a straightfor-ward definition of theencoding scheme. If yourDVD player uses aninfrared code other thanRECS80, implementingthe new scheme should-n’t be too difficult. Onthe contrary, the PPGpulse_gen.c file is rathercomplex, so I willdescribe it separately.

The DS1621.c file,which is the thermome-ter driver, is in chargeof initializing the chipregisters and the I2Cbus as well as takingtemperature readings. Itcarries out these opera-tions issuing short

16 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

block diagram (see Photo 3). The main application (main.c) includes

initialization code for port register set upand void interrupt routines. During thestart-up phase, it calls the initializationprocedures of the DVD driver and ther-mometer respectively. Each driver han-dles its initialization hierarchically (e.g.,after it’s initialized, the thermometerroutine DS1621_init() callsI2C_init() to initialize the I2C pins).

After the system is up, the main con-trol loop begins. First, check if the bat-tery has enough juice by reading theLVI register. If not, use the remainingenergy to select the “battery low” mes-sage from the DVD pictures. (I arbi-trarily placed it as the last image in thesequence.) Otherwise, obtain the ambi-ent temperature, subtract the lowesttemperature possible to get an indexthat starts from zero, and use theindex to select the image.

DVD.c provides the scene selec-tion facility. For instance, callDVD_select( 25 ) to show the twen-ty-fifth scene. Figure 3 illustrates theselection algorithm. The DVD modulekeeps track of which image is currentlydisplayed, starting from zero during ini-tialization. If the image that will beselected follows or precedes the currentone, the disc is advanced, emulating theNext or Previous remote control code.

sequences of I2C commands. I tried tomake them as easy as possible to read,but understanding the DS1621/DS1631datasheet, as well as familiarizingyourself with I2C bus concepts, is defi-nitely necessary. If you don’t have thetime to read the datasheet, just callDS1621_temperature() to get thecurrent temperature (°C). If you needhigher resolution, uncomment thelines in the code to get 0.1°C readings.Notably, the software doesn’t need toconvert Celsius to Fahrenheit for useof the thermometer outside Europe.All you need is a different DVD onwhich Celsius pictures are replaced byFahrenheit temperatures!

The software emulates an I2C bus tog-gling two I/O pins. When speed is not aconcern, software implementations likethis one are perfectly adequate. I portedthe I2C.c code from a bigger processor.All that was required was to providemethods to set and clear the SDA andSCL pins, to change data direction, andto activate the pull-ups. All of this wasdone with macros, so I accomplished

Select DVD picture

Picture greater thanlast picture?

Picture less than

first picture?

Same pictureas currentlyon screen?

Picture greater than

on-screen picture?

Picture less than

on-screen picture?

Function end

N

N

Y

N

N

N

Y Transmit “prev” remotecontrol key

picture = picture –1

Transmit “next” remotecontrol key

picture = picture + 1

Y Go in Stopmodefor 1 s

Picture = last picture

Picture = first picture

Y

Y

Figure 3—The DVD selection routine operates iteratively. It keeps track ofthe image currently on the screen and passes to a new one (one step at atime). This technique requires the DVD to respond only to two commands,next and previous.

Photo 3—The C file names in the Codewarrior project window reflect the blocksconstituting the application. Each module encapsulates a reusable driver for func-tions like DVD selection, I2C bus communication, temperature readout, andremote control generation. The code compiles in approximately 2 KB and runs inUser Monitor mode.

WW

W.G

iURUMELE

.Hi2

.RO

Page 19: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 20: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 21: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 19

the task in minutes. I didn’t need toadjust the waiting loop, although youmight have to if you port the code tofast (or slow!) processors. After it wasrecompiled, the driver worked likemagic, providing the I2C primitivesfor communicating with two-wireperipherals: I2C_start, I2C_stop,I2C_tx_byte, and I2C_rx_byte.

The last file, sleep.c, provides a func-tion to put the processor in Stop mode fora given number of seconds. The sleepfunction is called from different modules;therefore, I placed it in a separate file.Because the delays are based on the wake-up timer, the times are approximate. Tohave the processor take a 1-min., low-power nap, just call sleep(60);.

PULSE GENERATORThe usual way of generating remote-

control pulses with small controllersis by bit banging (i.e., flipping pinsdirectly in a carefully timed softwareloop). This solution is far from perfect.The main defects are its poor resolu-tion and inherent dependency on code.Even touching a single line of codeinside the loop can completely ruinthe output waveform.

The excellent 16-bit timer module ofthe MC68HC908QT4 processor calledfor a more elegant solution than crude

bit banging. The result is the versatileprogrammable pulse generator (PPG)contained in the pulse_gen.c source file.It can generate pulse bursts whose carri-er frequency and duty cycle are set witha simple command. The number of puls-es in a burst can be set as well. This isideal for handling the 8.77-µs LED flash-es. You can disable the output but keepthe timing in order to generate pauseswith the same resolution to handle the5.06-ms, 7.6-ms, and 0.12-s gaps requiredby the RECS80 code.

The PPG is easy to set up and use(see Listing 2). It is interrupt-basedand synchronizes itself for pendingrequests, so it frees the main programfor other tasks while working in thebackground. This feature is beneficialwhen writing the infrared encoding

routine because it leaves plenty oftime for the processor to compute thepulses that come next.

I started from a working examplethat I created with Processor Expert,using its PPG component (“bean” inProcessor Expert jargon). I studied thecomputer-generated code along withthe datasheets in an effort to getfamiliar with the timer module detailsbefore I started writing my own code.

My incarnation of the PPG isextremely different from the PE code.First, you must set up the desired fre-quency and duty cycle with a call toppg_set(frequency, duty);. Thepurpose of this function is to set thePWM registers; it does not modify thePPG output. A call to ppg_set can beissued at any time because it automati-

Listing 1—The PPG works in the background under interrupt control. Calls to ppg_pulses() synchronize automatically and return almost immediately to thecaller. As you can see, the implementation of a RECS80 remote control encoder is straightforward.

static void recs80( unsigned int code, unsigned char toggle )

unsigned int mask;unsigned int pause = 4598;ppg_set( 38000, 33 ); //Prepare PPG for 38 kHz, 33% duty cycleif (toggle)

code |= (1 << 10); //Add toggle bit to data wordfor( mask= 1<<11; mask!=0; mask>>= 1 ) //Scan all bits in the code word

if (mask & code) //Is data bit = 1?

ppg_pulses( 6, PPG_ENABLE_OUT ); //Yes, transmit burst ppg_pulses( 288,PPG_DISABLE_OUT ); //and a longer silencepause = pause - 6 - 288; //adjust repetition rate pause to compensate

//for the time spent else //No, data bit is 0

ppg_pulses( 6, PPG_ENABLE_OUT ); //transmit burst ppg_pulses( 192,PPG_DISABLE_OUT ); //and a short silencepause = pause - 6 - 192; //adjust repetition rate pause to compensate

; //for the time spent ;ppg_pulses( pause, PPG_DISABLE_OUT ); //Add the pause to get the 121-ms repetition rate

Listing 2—The programmable pulse generator defined in PPG.C is easy to set up and use. It providesfunctionalities for generating square waves of an arbitrary duty cycle with specified duration as well aspauses. Therefore, the code can be adapted to generate encoding schemes other than RECS80.

//Set up PPG for 38-kHz square waves, 33% duty cycleppg_set( 38000, 33 );

//Generate six pulses with the current frequency and duty cycle.ppg_pulses( 6, PPG_ENABLE_OUT );

//Generate a 100-cycle long pauseppg_pulses( 100, PPG_DISABLE_OUT );

WW

W.G

iURUMELE

.Hi2

.RO

Page 22: GRAPHICS & VIDEO

20 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

cally waits for the completion of a pre-vious cycle if the PPG is running. ThePPG is running whenever TSC_TSTOPis zero.

Starting pulse generation requires acall to ppg_pulses(count, mode);.This function triggers the PPG to gener-ate count pulses (up to 65535). The sec-ond parameter tells the PPG to togglethe output if set to one and to leave theoutput unchanged if set to zero. Settingthe mode to zero is an effective way togenerate pauses synchronized to themain PPG frequency. It that case, countspecifies the pause length expressed ascycles of the PPG frequency.

It is remarkable that, if no previousrequests are pending, ppg_pulsesreturns to the main application almostimmediately. The purpose of thisfunction is to load a cache buffer withthe pulse parameters, and to start thetimer if it was not already running. Itthen returns to the calling application,which gets plenty of time to preparethe next pulse burst. Successive callsto ppg_pulses join and synchronizeseamlessly. This feature allows for thestraightforward coding of the remotecontrol encoding routine in Listing 1.

After the timer runs, waveform gen-eration is handled by the timer over-flow interrupt service routine. It’s morecomplex than it looks. Timing is crucialbecause a 38-kHz pulse takes only 26.3µs, which leaves little time for countingpulses and flipping bits. The situationgets even worse when working in UserMonitor mode because of the overheadinvolved with the vector’s redirection.

At every interrupt, the handler checksthe pulse ticks counter to determine if

it is the last pulse. If not, it decrementsthe counter and returns. Otherwise, itchecks the cache buffer to see whetheror not more pulses are scheduled. In theformer case, it reloads the tick counterand sets the mode of operation for theoutput pin. In the latter case, it waits forthe current pulse to end, testing the sta-tus of the output port pin, and resets theoutput mode to no-pulse generation. Itfinally stops the timer, which stopsoverflow interrupts as well. Fortunately,you don’t have to know all of thesecomplex details to benefit from thePPG, which is encapsulated in a C mod-ule and can be called transparently.

IT’S SHOWTIMEThe circuit, which is quick and easy

to assemble on a piece of perf board,doesn’t require calibration. My proto-type is shown in Photo 4. The systembegins working immediately after plac-ing the disc in the player and switchingon the player and the thermometer.

The DVD-Thermometer has superbmultimedia capabilities unparalleledby current thermometers. It’s inexpen-sive too. With DVD players starting at$59.99, using a DVD player as a sortof graphic front-end is reasonable. Analternative PC-based solution costsmore, consumes more power, is muchmore complex to set up and upgrade,and is immensely less fun to design!

The basic idea can be adapted to avariety of practical situations. Clearly,it’s a great idea for hotels, malls, show-rooms, stations, airports, and touristsites. Thermometers, per se, are unques-tionably useful, but the multimedia useand low cost of the DVD-Thermometerprospects new uses, especially when thepossibility of adding advertisements isconsidered. Potential applicationsinclude talking please-take-a-numberdisplays, interactive product selectors(e.g., select a certain paint or see how anew drill works), and colorful, dramaticdisplays for any sort of measurement.

You shouldn’t have a problem usingthe circuit as a building block forother projects. The C software isstructured and modular, and the PPGmodule performances in particular areexcellent. Its cache-based algorithmallows for an unusually straightfor-ward implementation of the remote

Photo 4—I assembled the DVD-Thermometer prototypeon perf board. The circuit fits a small plastic box, with thepower switch and infrared LED peeping out one side. Tomeasure the external temperature, separate the LED to bea few meters apart and connect it with twisted-pair wire.

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

SOURCESNero Burning ROM Ahead Softwarewww.ahead.de

68HC908QT4 MicrocontrollerMotorola, Inc.www.motorola.com

DS1621/DS1631 Digital temp sensorMaxim Integrated Products, Inc.www.maxim-ic.com

Alberto Ricci Bitti holds a degree inComputer Science from the Universityof Milan. He has more than 10 years ofexperience designing and writing soft-ware for embedded systems. Albertocurrently designs industrial controllersand instrumentation for Eptar. In hisfree time, Alberto enjoys competing indesign contests. He has been awardedseveral prizes. You may visit Alberto’sweb site, www.riccibitti.com, or writehim at [email protected].

RESOURCESPhilips Semiconductors, “SAA3004Remote Control Transmitter,” 1982.

J. Sibigtroth, “User Mode MonitorAccess for MC68HC908QY/QT SeriesMCUs,” AN2305, 2002.

J. Suchyta, “Reprogramming theM68DEMO908QT4,” AN2322/D, 2002.

control encoder routine, which youcan adapt to most of the encodingschemes currently on the market. Ifyou write a driver for a different DVDplayer brand, please contact me so I canshare it with other interested readers.

This design is also a great candidatefor classroom experiments. It’s instruc-tive for teaching students about micro-controllers, programming languages,serial (I2C) busses, sensors, remote con-trols, waveform generation, and theprocess of creating and preparing multi-media content. Young, open-minded stu-dents working on simple everyday tech-nologies can generate wonderfulresults. I look forward to seeing whatthey can get out of a bit of silicon! I

WW

W.G

iURUMELE

.Hi2

.RO

Page 23: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 24: GRAPHICS & VIDEO

cameras, digital picture frames, andphotofinish freeze-frame cameras).

More importantly, my goal is todemonstrate the techniques by whichthis is accomplished. This article isalso intended to serve as a startingpoint for further exploration.

ANALOG VIDEO BASICSSince the early 1950s, the National

Television System Committee (NTSC)color analog video standard has been ineffect for all North American TV broad-casts. Similar flavors of the standard (i.e.,PAL and SECAM) also have been devel-oped in various other parts of the world.

Figure 2 shows the structure of a typi-cal baseband analog composite video sig-nal. Essentially, there are four regions ofinterest: the sync pulse, which is thelowest level of the signal; the back porch(black level) with color burst, which isused as a synchronization referenceduring the color decoding process; theactive video region; and the front porch(black level).

The luma (Y), or intensity informa-tion, is encoded as theaverage amplitude of thesignal within the activevideo portion. In addi-tion, note that two chro-ma (Cb/Cr), or colorcomponents, are quadra-ture-modulated andadded to the luma sig-nal. In simpler terms,the two modulated chro-ma components arecharacterized by a super-imposed sinusoidal sig-nal, whose phase withrespect to the referencecolor burst signal (in theback porch) represents

22 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

My old cell phone had finallypacked it in! That wonder of moderntechnology wouldn’t even allow me todial out. Instead of having it fixed, Idecided to go shopping for a replace-ment. I was surprised to find out that alarge number of the newer cell phoneshave built-in cameras. Not only can youtalk to your friends, but you can nowsee them too. Hmmm.

On the way into the store I also noticedseveral closed-circuit TV cameras remind-ing customers that they should be ontheir best behavior. In another corner ofthe store, satellite TV products were ondisplay featuring a personal video recorder(PVR), which you can use to time-shiftand record whatever TV shows keep youglued to your seat. Freedom at last!

Essentially, over the past few years,there has been an explosion in the num-ber of video-related embedded productson the market. This has been possible inlarge part because of the availability ofinexpensive CMOS imagers, specializedvideo compression ICs, and FPGA cores.

Over the years, I’ve designed a numberof embedded productsinvolving digital video.These products range incomplexity from a full-fledged, stand-alone,FPGA-based multichanneldigital video recorder(DVR) to a much simplervideo freeze-frame device.For all of these designs, oneof the key requirementsalways has been ultralowcost. Surprised? In myexperience, “ultralow cost”is usually a synonym for“8-bit microcontroller.”

Unfortunately, digitiz-ing video can be a daunt-

Full-Field Color Video Frame Grabber

ing task because of the volume of datacollected and the rate at which it isgenerated (more than enough to chokethe fastest 8-bit microcontrollers on themarket). In this article, I will presentyou with a relatively simple and inex-pensive circuit that allows for the sin-gle-shot digitization of a full field (720 ×240) of color video (PAL/NTSC) into afield buffer. This buffer is accessible byan Atmel AVR 8-bit microcontroller,and its contents are sent to a host PCthrough the UART (see Figure 1).

Of course, the circuit probably won’twin any frame-rate contests! Even thoughthe video acquisition rate supports60 fields per second, downloading a frozenfull-resolution (720 × 240) color imageover the serial port takes about 30 s at115.2 kbps. (A download 10 times fastercould be realized over the SPI bus.) Ifyou sub-sample the image at a fractionof the resolution during downloading,expect proportionally better results. Inmany applications, acquiring a singlefield of video following a trigger is allthat’s required (e.g., motion-triggered

FEATURE ARTICLE by Eric Gagnon

Eric’s frame grabber enables the single-shot digitization of a full field of color video. Use thiscircuit for digital, freeze-frame, and motion-triggered camera design projects.

Video 1

Video 2

Video 3

Video 4

SAA7113Video

decoder

Video out

Powerregulator5 to 9 VDC

3.3 V

AL422BFieldbuffer ATmega8535L

8-bit MCU

4:2:2

(CLK, VS)

W

E

HS

4:2:2

(RCK, RE, RRST)

VS

ACQUIRE

(RXD, TXD)

RS-232Levelshifter

RS-232 Port(to PC)

I2C (SCL, SDA)

Figure 1—The SAA7113 video decoder digitizes one of the analog input video signals and stores thesamples in a field buffer. The ATmega8535L coordinates the acquisition and download processes.

WW

W.G

iURUMELE

.Hi2

.RO

Page 25: GRAPHICS & VIDEO

solid dark lines inFigure 3) and one ofall the 262.5 even-numbered lines(the lighter dashedlines in Figure 3) inrapid succession.

Half images, orfields, are displayedwith a slight verti-cal offset in rela-tion to each otherin such a way thatthe eye’s retinalpersistence super-imposes them andis fooled into see-

ing a 525-line image. Each field is sentat 60 Hz. This trick is still in use today,although most PC monitors and TVsnow have video deflection circuits fastenough to display noninterlaced images

at full video rates. A field of video is defined as the half

image composed of either the odd or even262.5 lines of a frame. A frame of video isdefined as a full 525-line image with both

the odd and even fields super-imposed (interleaved).

One of the problems thatarises when digitizing video ofmoving objects is that the oddand even fields are acquired atone-sixtieth of a second apart.When played back on a TVscreen, this is not apparentbecause the eye is fooled.However, if you freeze bothodd and even fields in a framebuffer and overlay them,

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 23

you’ll notice motion artifacts as shownin Figure 4. Because the images aren’ttaken at the same point in time, anymoving object in the scene will resultin this slight spatiotemporal mismatch.

There are some deinterlacing tech-niques aimed at isolating the changesbetween both images and applying inter-polation to infer details in regions of largemotion. However, the most commonapproach to the problem is simply to dis-card one of the fields and use the other(albeit at half the vertical resolution). Ifabsolutely necessary, it’s always possibleto interpolate the acquired field verticallyto bring the image back to the originalsize. (Although this is artificially inferredinformation, it is often adequate.)

Another approach is to copy the dataas-is to the other field. In this article Isimply explain how to acquire one of thevideo fields and discard the other.

DIGITIZING VIDEO SIGNALSThe digital revolution has taken the

world by storm, and video is no excep-tion. With the creation of two standards,ITU-R BT601 and ITU-R BT656, a newdigital video format has been estab-lished. The former describes the essen-tials of the video digitization processsuch as minimum/maximum, reservedvalues, sample rates, etc. The latterspecifies both a parallel and a serial elec-trical interface for digital video transfer.The parallel interface supports an 8-bit-wide datastream (10-bit is also support-ed) with embedded codes representingtiming and ancillary information.

Both standards apply to component4:2:2 digital video. The 4:2:2 ratio ter-

the hue, and whose amplitude repre-sents the saturation of the color.

FRAMES VERSUS FIELDSEncoding the information contained

in an entire image requires the con-catenation in time of a series of sin-gle-line video signals. In fact, there isone for every active video line andalso some for additional timing infor-mation (the first 21 lines per field).Figure 3 illustrates the scanning pat-tern used to encode the informationcontained in a typical image.

The NTSC composite video standardcalls for 525 total lines of video perframe at 30 frames per second. In orderto reduce image flicker and increase therefresh rate without changing the overallvideo signal bandwidth or needing fasterdeflection circuitry in TV receivers,engineers came up with the interlacedvideo technique. This technique doublesthe image refresh rate to 60 Hz (whilemaintaining the perceived vertical reso-lution of 525 lines) by quickly alternat-ing between a half image composed ofall the 262.5 odd-numbered lines (the

Y component (luma) = average signal offset

1 V

Back porch

Active video

Cb, Cr components(chroma)

= superimposedquadrature-modulatedsinusoids

63.555 µs

Color burst(reference)

Front porchSync pulse

Figure 2—Study the structure of an analog composite NTSC video signal. The mainsections include the sync pulse, the back porch, the active video, and the frontporch. The average signal offset represents the luma (Y) and the superimposedquadrature-modulated sinusoid, the chroma (Cb and Cr) components.

Even field (lines 264–525)

Line 285

Line 286

Line 287

Line 288

Line 524

Line 525

Odd field(Lines 1–263)

Line 22

The first 21 video linesof each field

contain no activevideo information

(not shown)

Vertical spatialoffset between

odd and even fields

Typical scan line consists of a

single-line video signal

Line 263

Line 23

Line 262

Line 261

Figure 3—The NTSC image scanning pattern is for full video frame. The odd field scan lines are shown in soliddark, and the even field scan lines in the light dashed pattern. Both fields are scanned in rapid succession from topto bottom, left to right with a slight vertical offset to each other.

Figure 4—The motion artifacts are obtained when simultaneouslydisplaying both the odd and even fields captured from a movingobject. Because the fields were acquired one-sixtieth a second apartby the camera, the image of the moving van appears jaggedbecause of the spatiotemporal mismatch.

Vehicle at time T2Vehicle at time T1

Even field lines sampled

at time T2

Odd field linessampled

at time T1Direction of

vehicle motion

WW

W.G

iURUMELE

.Hi2

.RO

Page 26: GRAPHICS & VIDEO

much more familiar with the R, G, Bcolor space where a pixel has three sam-ples corresponding to its red, green, andblue color components. Fortunately,converting between the two involves asimple matrix operation. To transform aYCbCr triplet to a corresponding RGBtriplet, use the following YCbCr-to-RGB transformation equations:[1,2]

R, G, and B are gamma-corrected val-ues ranging between zero and 255.

SAA7113 VIDEO DECODER ICConverting an analog video signal

into the digital domain requires anADC. About 5 to 10 years ago, manysemiconductor manufacturers offereddigital video decoder integrated cir-cuits. A video decoder is essentially aspecialized ADC with a front-end usedto condition and synchronize to ananalog video signal. In recent years,however, only a few of the dominantplayers have remained and continuedto offer a good selection of parts.Among these is Philips Semiconductor,whose SAA7113 is truly a lean-and-mean video decoder IC. Its ancestor isthe venerable SAA7111 known bymany in the field.

The SAA7113 is housed in a com-pact 44-pin TQFP package and oper-ates at 3.3 V. It accepts up to fourvideo input channels that are internal-ly multiplexed to a single video ADC.A convenient analog video output pinbuffers the currently selected analogvideo channel for viewing. The videoADC outputs data in 8-bit, multi-plexed, 27-MHz (BT656) format on itsdata bus pins. It also provides addi-tional signal outputs such as verticalsync, horizontal sync, and odd/evenfield detect on two programmable pins.This makes it convenient to interfaceto external circuitry without needingto recover the synchronization infor-mation from the datastream itself.

The SAA7113 has a built-in phase-locked loop (PLL) circuit, which enablesit to lock its on-board oscillator clockto the incoming video signal. This pro-vides an accurate pixel clock (27 MHz

R

G

= 1.164 Y 16 + 1.596 Cr 128

= 1.164 Y 1

× −( ) × −( )× − 66 0.392 Cb 128

0.813 Cr 128 = 1.164

( ) − × −( )− × −( )

×B YY 16 + 2.017 Cb 128−( ) × −( )

24 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

Y sample (see Figure 5). The (Cb,Y,Cr)triplets are cosited in space, and eachsecond Y sample is alone because of thedropped Cb and Cr samples. The result-ing aggregate sample rate, 27 MHz, iscalculated by adding the 13.5-MHz Ycomponent as well as both the 6.75-MHzCb and Cr components.

COLOR SPACESThe 8-bit Y, Cb, and Cr sample values

are used to represent a pixel in colorspace. In the computer world, we are

minology simply means that duringthe video sampling, the luma informa-tion (Y) is sampled at every pixel posi-tion (13.5-MHz sample rate), and thechroma (Cb, Cr) components are sub-sampled by a factor of two (6.75 MHzeach). This decimation is possiblebecause the eye is less sensitive to spa-tial color resolution than spatial intensi-ty resolution. In a BT656 4:2:2 digitalvideo stream, one 8-bit sample of Cb isfollowed by a Y sample and then a Crsample, which is followed by the next

WW

W.G

iURUMELE

.Hi2

.RO

Page 27: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 25

nominal) with respect to the video sig-nal timing and tracks any signal jitter.

I should also mention that besidesvideo decoders used to digitize legacyanalog video signals, there are also newvideo imagers based on CMOS technol-ogy that directly output BT656. (Thevideo ADC is internal to the IC.)Therefore, in theory, you could directlyreplace the video ADC front end of thiscircuit and substitute a CMOS imagerif you want to build a small camera.

KEEPING PACE As I mentioned earlier, the funda-

mental problem in capturing digitalvideo is the rate at which it is generat-ed and the volume of the generateddata. A typical 8-bit MCU would nothave the SRAM resources required todirectly store a single color field ofvideo (300 KB) or even the processingspeed to read the data at 27 MHz. Thesolution to this problem lies in buffer-ing the video field into a field buffer.This can be implemented in a numberof different ways. Figure 6 shows afew possible system architectures.

For optimal performance, an FPGA-based (or CPLD-based) external mem-ory buffer is the architecture ofchoice, especially when the FPGA isotherwise needed in the circuit (seeFigure 6a). As such, its incrementalduties as the field buffer can be rela-tively inexpensive. The circuitryinside the FPGA typically includes a

counter that cycles the external mem-ory in sync with the incoming videodata samples and writes the values ateach memory location. The verticaland horizontal sync pulses are used togate (enable/disable) the clocking ofthe SRAM addresses to ensure thatdata is only written to memory duringvalid video data sampling (and not

720 sampled pixels per video line (at 13.5 MHz)

720

Pixel 720Y720

Cb720Cr720

Pixel1

Chroma componentsare sampled at 8 bits afterquadrature demodulation

1

Each sampled pixel has a [Y, Cb, Cr] triplet

4:2:2 Digital video stream (at 27 MHz)from video decoder

Every second, Cb/Cr chroma samples(shaded) are dropped

Y720Cb1 Y1 Cr1 Y2 Cb3 Y3 Cr3 Y4

Y1 Y2 Y3 Y4Cb1Cr1

Cb2 Cb3 Cb4Cr2 Cr3 Cr4

Pixel2

Pixel3

Pixel4

8-bit Sampling range

(for luma)

0

255

Figure 5—Here you see the ITU-R BT656 4:2:2 digital video stream. The 27-MHz digital datastream is mainlycomposed of a succession of Cb, Y, and Cr samples. Each component sample value of the (Cb, Y, Cr) triplets arecosited in space. Because of the 4:2:2 decimation, each second Y value has no associated chroma information(shown shaded). Embedded sync codes are also added throughout the digital stream.

WW

W.G

iURUMELE

.Hi2

.RO

Page 28: GRAPHICS & VIDEO

26 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

needs to be transferred to the mainprocessor for processing, communica-tion, or storage. This operation can beaccomplished by implementing a DMAcontroller inside the FPGA or simply byhaving the FPGA switch over all the

control and data lines of the memoryto the MCU during the entire transfer.(This is done to the detriment of theoverall system frame rate because nonew fields of video can be acquiredwhile the SRAM is under MCU control.)

Another way to accomplish the datatransfer is to use dual-ported memory(see Figure 6b). The video frame grab-ber writes to the memory on one port,and the system can read the data fromthe other port. However, full-field,dual-ported SRAM memories areextremely expensive. It is often moreeconomical to use smaller dual-portedSRAM as single-line buffers.

If you have the luxury of a DSP orextremely fast processor with anexternal memory bus, you can simplyuse DMA transfers. Assuming theprocessor can read out one line ofstored video data at a faster averagerate than it’s generated, all you need isa single-line video FIFO or dual-portedSRAM (see Figure 6c). The videodecoder simply fills the FIFO withdata at the video rate, and it interruptsthe main processor when the buffer is

outside these bounds). At the sametime, the circuit can separate the Y,Cb, and Cr components into differentmemory destinations if desired.

After the digital video field data iscollected in the field buffer, it usually

SRAM or SDRAM(full frame/field)

ADDR, CTRL

FPGAor

CPLD

DATA

4:2:2

HS, VS, CLK

ADDR

DATAMCU

FPGAor CPLD

Dual-portedmemory

MCU(external

memory bus)

ADDR4:2:2

DATA

ADDR

DATA

Single-line FIFO

4:2:2

HS, VS, CLK DATA

CTRL

Fast MCUor DSP

ADDR

DATA

Mai

n m

emor

y

Full-fieldFIFO

MCUDATA

CTRL4:2:2

HS, VS, CLK

HS, VS, CLK

Figure 6—There are a few possible field buffer architectures: an FPGA managing memory buffer (a), a dual-portedmemory (b), a single-line FIFO (c), and a full-field FIFO (d).

a) b)

c) d)

WW

W.G

iURUMELE

.Hi2

.RO

Page 29: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 30: GRAPHICS & VIDEO

28 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

half full or at the end of each line. Theprocessor then immediately bursts outthe data from the buffer in less timethen it took to fill it, preferably muchfaster. The data is transferred to theprocessor’s main memory space,which has to be large enough to holda complete field.

In this project, you don’t have accessto an FPGA or DSP, or even enoughinternal memory to buffer a field.Therefore, you need a full-field FIFOwith an interface simple enough forthe MCU (see Figure 6d). The videodecoder will fill the FIFO using thewrite port. Then, the MCU will inde-pendently read out the data from theread port after it detects that a com-plete field has been stored.

AL422B FIELD BUFFER FIFOAverlogic’s AL422B is a popular

full-field FIFO. This IC is implement-ed internally as dynamic RAM, so itcosts less than a comparable SRAM-based product. It has a convenient andsimple FIFO interface with one inputwrite port and one output read port.

On the input port, the write enablesignal is used to gate the main clock,which must be present for the DRAMcells to get refreshed internally. Thewrite reset pin resets the internal writeaddress generator counter to zero. Atevery write clock pulse, the addressgenerator is automatically incremented.On the read side, the same ideaapplies, but from the read perspective.

PUTTING IT TOGETHERThe circuit is shown in Figures 7

and 8. The SAA7113 is used to digitizeone of four possible analog video inputchannels. The buffered analog video out-

put allows for the live viewing of theselected video channel. The BT656-for-mat digital output of the video decoderis wired to the input port of the FIFO.

The SAA7113 is programmed tooutput an odd/even field signalswitching after line 21 (start of activevideo lines) on its RTS1 pin. This signalgoes high for the duration of an oddfield, and then goes low for the evenfield. It is tied directly to the writereset pin (*WRST) and holds the writecounter in its reset state, except whenan odd video field is present.Remember, you only want to sampleone field to eliminate motion artifacts.

Furthermore, the SAA7113’s other pin(RTS0) is programmed to output a hori-zontal reference (HREF) signal, whichgoes high and stays high for the durationof the active video data portion of everyvideo line. Connected to the *WE pin

Figure 7—U1 digitizes one of the four video input signals from BNC connectors J2–J6. The digitized samples are stored in U4, a full-field FIFO memory. All of the operationsof the frame grabber, as well as download functions, are coordinated by U5, an 8-bit Atmel AVR MCU.

WW

W.G

iURUMELE

.Hi2

.RO

Page 31: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 29

through an inversion, it is usedto gate the main pixel clock,which is connected to WCK. Itsimply enables the writing ofvalid video data values to theFIFO at the appropriate times.

The microcontroller also hasaccess to the write enable linethrough a NAND gate. Thisallows for the acquisition of asingle field and then the abilityto stop under MCU control.(Otherwise, the video fields willbe continuously overwrittenbefore you have the chance toread out the data.) The MCUhas full access to the FIFO’soutput port. After detecting thata frame grab is complete, the MCUwaits for the appropriate serial portcommand before reading out the videodata from the FIFO for transmission.

The fully assembled circuit board isshown in Photo 1. Note that the designwas separated into two modular parts:a stand-alone daughter card, whichcontains the entire frame grabber cir-cuit, and a larger motherboard thatholds the various connectors as well asthe RS-232 level shifter circuitry.

FIRMWARE AND SOFTWAREThe firmware for this project was

developed in C using ImageCraft’sICCAVR compiler. The MCU’s mainroles involve running a serial commandserver, initializing the SAA7113 throughthe I2C bus, and managing the fieldacquisition process. The serial com-mands are sent in plain ASCII format.

The basic ASCII frame grabbercommand set includes the following:VER returns firmware version number;GRAB grabs a field into the field buffer;CHAN n selects video channel n; RRSTresets the FIFO read pointer; and SENDsends the next n bytes of video datafrom the FIFO in binary format.

A variation of the SEND com-mand could allow decimation ofthe image to speed up the transfer(Thumbnail mode). Additionalcommands allow for board config-uration and extra features.

The SAA7113 is a highly config-urable part that contains a largenumber of registers. At power-up,each register must be set up cor-rectly through I2C before the partcan be used. Just remember to pro-gram the unused registers to zeroas indicated in the datasheets; oth-erwise, it won’t work. After ini-tialization, the desired channel isselected and the digital videocomes spewing out!

At this point, the frame grabber iscapable of digitizing a full-color videofield and transmitting the data over astandard RS-232 serial port inresponse to simple ASCII commands.This offers great flexibility for use ingeneric embedded systems. In orderto allow for simple user experimenta-tion, a Windows-based command andviewing utility was developed usingVisual C++ 6.0. This utility commu-nicates with the frame grabberthrough the PC’s serial port. It cansend all the commands used to con-trol the frame grabber as well as

Figure 8—The live video output BNC connector J7 allows for a live preview of the currently selected video input. An RS-232 level shifter (U2) provides the required signal lev-els for interfacing to a PC. U3 is a 3.3-V LDO regulator providing local regulation of the input voltage.

Photo 1—This is the microcontroller frame grabber (uCFG) prototype.The small daughter card on top contains the entire frame grabber cir-cuitry, and the larger motherboard on the bottom contains the variousconnectors as well as the RS-232 level shifter circuitry.

WW

W.G

iURUMELE

.Hi2

.RO

Page 32: GRAPHICS & VIDEO

30 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

download the image data for viewing. The downloaded YCbCr data has to

be reconstructed into an RGB arrayfor display on the computer screen.To perform this reconstruction, thedecimated Cb and Cr samples are firstregenerated through interpolation.The YCbCr-to-RGB matrix transformis then applied to convert image datato the RGB color space. Because thecaptured video field is 720 × 240,merely displaying it 1:1 on a PC mon-itor results in a vertically squashedimage. In order to compensate, verti-cal interpolation of the missing fieldis performed before displaying theimage. A high-resolution mode couldbe implemented that would capturethe odd field, the even field of a staticscene (eliminates motion artifacts), andprovide an actual 720 × 480 resolutionimage. The software can also save theuploaded image in the .bmp format.

FIRST LIGHTWell, enough theory. It’s time to get

your hands dirty! After building theframe grabber circuit, I used my cam-corder as a color video source. I sentthe command to acquire the videofield from the Windows-based GUIapplication and downloaded the image.Photo 2 shows the PC control softwarein action. You can see the downloadedimage of the frame grabber taking apicture of the frame grabber, taking a

PROJECT FILESTo download the viewing software andprogramming files, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

REFERENCES[1] K. Jack, Video Demystified, LLH

Publications, 2001, www.video-demystified.com.

[2] C. A. Poynton, A TechnicalIntroduction to Digital Video, JohnWiley & Sons, Hoboken, NJ, 1996.

RESOURCESInternational TelecommunicationUnion, ITU-R series standards,www.itu.int/home/index.html.

NTSC standard information, www.ntsc-tv.com.

SOURCESATmega8535L MicrocontrollerAtmel Corp.www.atmel.com

AL422B Full-field FIFOAverlogic Technologies, Inc.www.averlogic.com

Stand-alone OEM frame grabberboards, evaluation kitDigital Creation Labs, Inc.(905) 793-3603www.digitalcreationlabs.com

C Compiler ImageCraft www.imagecraft.com

CMOS ImagersOmniVision www.ovt.com

SAA7113 Video decoderPhilips Semiconductor www.semiconductors.philips.com

Eric Gagnon, M.A.Sc., P.E., has morethan 10 years of embedded designexperience. He currently runs DigitalCreation Labs, Inc. (www.digitalcreationlabs.com). Eric has worked on projectspertaining to the International SpaceStation, industrial robotics, 3-Dmachine vision, and embedded videoproducts. You can contact him [email protected].

picture of the framegrabber… Well, youget the picture (no punintended)!

LOOKING AHEADI’m sure you are

already thinking ahead.How can you integratethis simple frame grab-ber into a product?What about adding anSPI-based secure digital(SD) flash card on theSPI interface of theAtmel MCU and turn-ing this into a simpledigital camera? Youcould save a large num-ber of images in rawformat to the flash card(or with a file system).

How about implementing a simplevideo compression algorithm insidethe microcontroller and sending theimage to a remote observation hostusing a wireless RS-232 module? Maybeyou could implement a photo finishfreeze-frame module to take a singlepicture of athletes crossing the finishline. Or what about a motion-triggeredcamera taking a snapshot of the lastperson entering the premises? Using theCypress wireless USB chipset (wirelessSPI), you can build an all-digital wire-less camera. Let your imagination runwild! If you come up with some neatideas, I would love to hear from you.

Hopefully this article has providedyou with some useful background ondigital video as well as some hints onhow to implement a basic video framegrabber. By extending this basic sys-tem, it’s possible to implement high-er-performance video capture circuits,and perhaps combine them with somesimple image-processing algorithms. Ifyou’re interested in hands-on experi-mentation, take a look at my fullevaluation kit and individual OEMframe grabber modules (www.digital-creationlabs.com).

Anyhow, back to my story. Afterwaiting in line at the store (for longerthan I should have), I ended up purchas-ing a replacement cell phone, but notone with a video camera. I guess I’mcheap. Some things never change! I

Photo 2—The frame grabber circuit acquired this image. Also shown is ascreen capture of the Windows-based PC control and viewing software. Allcommunications occur over a standard RS-232 serial port.

WW

W.G

iURUMELE

.Hi2

.RO

Page 33: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 34: GRAPHICS & VIDEO

REFLOW OVENThe key to good reflow is a precise

multistep thermal profile, as illustrat-ed in Figure 1. The preheating profileallows you to slowly bring the PCB toa temperature high enough to dry thesolder paste (approximately 100°C)while minimizing the risk of thermalstress on the components in the reflowphase. After thermal stabilization, theboard is heated as quickly as possible tothe reflow temperature (approximately250°C). The board stays above thereflow temperature for a set period oftime (usually around 30 s) before it’scooled down in a controlled fashion.

What are the key characteristics ofan industrial reflow oven? Quick heat-ing and cooling is important (thequicker the better) in order to reducethe thermal stress on the components.(The pads and solder paste have alower thermal latency than the com-

32 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

For years surface-mount technology(SMT) has been the manufacturingtechnology of choice, particularlybecause it’s less expensive than classicthrough-hole processes and because ofthe reduction in board size. I’m sureyou have noticed that SMT is nowmandatory for prototypes, even if aproject isn’t space-constrained. Manynew and exciting components are onlyavailable in SMT packages. High-speed designs (using high-speed digitalor radio frequencies) won’t work usinglarge through-hole packages.

It’s possible to solder the majority ofSMT components by hand, but it’spainful and time-consuming. Thecomponents must be soldered individ-ually with either a small solderingiron or a hot-air pencil. But small

Easy Reflow

When designing high-speed applications, working with SMT components and soldering byhand can be tedious. Robert’s H8/3687-based SMT Reflow Oven Controller transforms aconventional infrared toaster oven into an effective reflow oven that ensures thermal control.

packages like 0603 resistors are likelyto fly away when soldered with hot airand stick to the soldering iron at theworst time.

A solution to this problem is to usereflow oven technology just like themanufacturers do. A reflow oven is awell-controlled oven that allows toyou cook a PCB with its componentsand solder all of the pads simultane-ously with solder paste. Great! Theonly issue is that reflow ovens cost afortune, ranging from $2,000 to $1million. The ovens cost so muchbecause they need strictly controlledthermal profiles to ensure good solder-ing and also to limit the thermalstress on the components.

In this article I’ll show you how ahomemade controller built around a

Renesas evaluationboard can transforman inexpensive toasteroven into a reflowoven. First, I’ll coverhow reflow ovenswork and explainwhich toasters on themarket are best suitedto mimic them. Then,I’ll describe my con-troller’s hardware andsoftware. I’ll finish upwith some tips onhow to assemble yourown SMT boardsusing the reflow oven.Let’s get hot.

FEATURE ARTICLE by Robert Lacoste

Preheating,1° to 4°C/s

Heating, 2° to 4°C/s

Maximum temperature =reflow temperature + 20°C,or around 250°C, dependingon the solder paste.

Drying, 100° to 150°C,1 min., 30 s to 3 min.

Cooling,–2° to –4°C/s

Reflow

Figure 1—In order to achieve reliable solders and to minimize thermal stress oncomponents, a precise thermal profile must be used with four successive steps.

Build an SMT Reflow Oven ControllerGRAND PRIZE WINNER

Photo 1—You must choose an appropriate toasteroven. For the best results, find one with infraredheaters on top that allow for a quick temperature rise.This one, which was made in France, costs less than$150. The thermocouple wire is on the left.

WW

W.G

iURUMELE

.Hi2

.RO

Page 35: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 33

you to select either Configurationmode or Run mode.

In Configuration mode, the LCDsuccessively displays each of the ninekey profile parameters (preheating slope,drying temperature, drying duration,heating slope, reflow temperature,reflow duration, cooling slope, thermalhysteresis, and differential coefficient).It also allows you to modify the profileparameters with the plus and minusbuttons. (It’s easy to store these valuesin EEPROM, but it isn’t done in the cur-rent version of the firmware.) In Runmode, the LCD shows the current actu-al and preset temperature, as well as thecurrent state and the remaining time tobe spent in the state (see Photo 3).

Seven steps are managed by thestate machine in order to achieve athermal profile that’s as close as possi-ble to the theoretical one. The firststep involves preheating. The presettemperature is linearly increased fromthe ambient temperature up to thedrying temperature. Next, the con-troller waits for the actual tempera-

ponents themselves.) Maintaining ahomogeneous temperature inside theoven is also important, especially whenyou’re working with large PCBs. And,last but not least, regulation is a mustin order to guarantee that successivereflows follow the exact same profile.As you can imagine, I will handle theregulation with a microcontroller-based solution, so let’s focus on thelow-cost oven you’ll use to replace areal reflow oven.

In order to have a quick heatingtime, some industrial reflow ovensuse infrared heaters. Why not just buyan infrared-based toaster oven like theone shown in Photo 1? I bought mineon the ’Net for less than $150. It hastwo quartz heating elements on thetop and a classic resistor on the bot-tom (a total of 1,100 W).

I used a thermocouple affixed on asmall PCB to take the first measure-ments. The temperature got up to250°C in less than 4 min., which isdefinitely enough for this application.The only real drawback was the lackof a cooling system. I decided to use amanual cooling method: I open thedoor when the controller asks.

HOME-BUILT CONTROLLERAs for building the controller, I used

the Basic Micro EVB87 Renesas evalu-ation board, which is fitted with anH8/3687 microcontroller (see Figure 2).This inexpensive microcontroller isexactly what I needed for this project.It has a low pin count, high RAM andprogram memory for using a simplehigh-level language like BASIC, andon-chip ADC. The evaluation boardalready provides an LCD and push but-

tons, so all I had to do was add two smallcircuits using the prototyping area. Thefirst was a thermocouple interface. I useda K-type thermocouple and an AnalogDevices AD595 monolithic thermocou-ple amplifier with on-board cold-junctioncompensation directly connected to theH8/3687’s ADC. More than simple, isn’tit? Lastly, I needed a way to drive anexternal relay to switch the oven on andoff. It took nothing more than a BD235transistor and a free-running diode. Ofcourse, you could use your favoritemicrocontroller (e.g., Basic Stamp’s) forthis design, but this evaluation kitspeeds up the process (see Photo 2).

On the firmware side, I decided totry to the BasicATOM programminglanguage because this application isn’tmanaging microseconds. This waseasy thanks to the user-friendly devel-opment environment provided by theboard in addition to the resident boot-loader. It took only 4 h to write anddebug the full software, even though Iwasn’t able to use the debugger forsome reason.

The application, for which thesource code is available on the CircuitCellar ftp site, is extremely easy toread. It is structured into two inde-pendent sections: a configuration sec-tion and a state machine section. Theformer allows you to manually modifyall profile parameters with the LCDand a couple of push buttons. The lat-ter manages all of the successive stepsof the thermal profile and reads theactual oven temperature in real time.Let’s look at the details.

First, a welcome screen is displayed.Then, a static screen displays the cur-rent temperature in real time and allows

Figure 2—The reflow oven controller is simple. There are only six components in addition to the Renesas EVM87evaluation board.

Photo 2—The oven controller includes a Renesasevaluation board with thermocouple and relay inter-faces in the breadboard area.

Photo 3—When it’s running, the controller shows thecurrent phase (“UpDry,” meaning “up to drying tempera-ture”), and the preset and actual temperatures, as wellas the remaining time to spend in this phase.

WW

W.G

iURUMELE

.Hi2

.RO

Page 36: GRAPHICS & VIDEO

34 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

ture to be equal to the drying tempera-ture. The third step involves drying.The preset temperature stays constantduring the drying time.

Heating follows this. Basically, thepreset temperature is linearlyincreased from the drying to thereflow temperature. Then, the con-troller waits for the actual tempera-ture to be equal to the reflow tempera-ture. Next, the preset temperaturestays constant during the reflow time.Finally, the preset temperature moveslinearly down to the initial ambienttemperature, and you open the ovendoor to help the process.

In addition to statemachine management, athermal control loop isimplemented in the soft-ware using a PD-like algo-rithm. An estimated future temperatureis calculated using the actual tempera-ture plus a multiple of the differential ofthe temperature. The estimated futuretemperature is compared to the presettemperature in order to switch theheater elements on or off. This allowsyou to account for the thermal latencyof the captors and heaters and to get amore stable temperature. A small hys-teresis factor is also used in the compar-isons in order to extend the life of theheater. Figure 3 shows the actual ther-mal profile compared to the preset val-ues generated by the controller.

OVEN IN USENow that you know why you need a

reflow oven and how to build one,how will you use it? First, you need toget some additional equipment. You’llneed a good magnifier (a video magni-fier would be best) and a syringe ofsolder paste. It’s easier if you have a

pneumatic fluid dispenser(which is easy to find onthe ’Net, but you willalso need shop air)because using the syringecan be difficult. You willalso need a flux cleaningspray, a small classic iron(15 W or less), and, ideal-ly, a hot-air iron forrepairs. Don’t worry, theInternet is a good sourcefor low-cost equipment.

Even if you don’t have a video magni-fier, you can be successful if you havea good optical lens and good eyes!

A clean blank PCB is extremelyimportant. I know from experiencethat it’s nearly impossible to achievegood reflow results with home-etchedPCBs. Solder masks are really helpfulin keeping the solder paste on thepads. I don’t know how to get soldermasks on home-etched PCBs, so finda good PCB manufacturer and orderyour PCB with solder masks.

You have to put solder paste on thepads with the syringe either manuallyor with the fluid dispenser. Then, you

must place each component on thePCB on the solder paste spots. Thesetwo steps are time-consuming, butthings speed up with experience!Remember that it is far quicker to usesolder paste than to try to solder byhand. After all of components areplaced, you can put the board in yourreflow oven and press the Start but-ton. After 10 min. or so, your PCBwill be cooked. Beware, it can still bequite hot. Use flux removal fluid anda toothbrush to clean the board (seePhoto 4). Refer to the Circuit Cellarftp site for a detailed illustration ofthe process.

By the way, you can use this processfor boards with components on bothsides if you put light components onone side. Reflow only that side first,and then flip the board and repeat theprocess: apply solder paste, place thecomponents, and then reflow. Thecomponents on the bottom side will

300

250

200

150

100

50

00 100 200 300 400 500 600

Thermal profile

Tem

pera

ture

(°C

)

Time (s)

tSETtACTUAL

Figure 3—The red curve is the set point defined by the software, where-as the yellow curve shows the actual temperature as measured insidethe oven. The full cycle takes around 10 min.

With a $150 toaster oven and alow-cost controller, you canachieve reflows with good results.

WW

W.G

iURUMELE

.Hi2

.RO

Page 37: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 35

usually stay soldered thanks to thesurface tension of the solder.

Finally, you should check the elec-trical connections and make the neces-sary repairs. If you follow the processclosely, you shouldn’t have too muchtrouble. My last 160 mm × 100 mmboard had more than 300 fine-pitchcomponents on both sides, but I hadonly a couple of bad joints and onesolder bridge on a 0.65-mm pitch IC.

THREE-DAY SOLUTIONThis project proves that SMT tech-

nology is neither boring nor too expen-sive for the occasional prototype circuitmaker. With a $150 toaster oven and alow-cost controller, you can achievereflows with good results. The onlyother things you need are a good lensand some basic equipment that’s readilyavailable on the used market. And, yes,you’ll need some patience too.

This project also shows that BASICis efficient language for low-speed,real-time applications, especially thosethat are associated with microcon-trollers with plenty of RAM and pro-gram memory in order to fully use thepower of such languages (e.g., theRenesas H8/3687).

Last but not least, this projectdemonstrates that embedded develop-ment doesn’t necessarily have to be ahuge undertaking to give good results.It took me only three days to finishthis project. I spent one day drawingthe concept and algorithms on paper.The last two days were spent buildingthe prototype, writing the software,and optimizing it.

The next step will be to experimentwith BGA packages, but that shouldwork too. Happy reflowing! I

RESOURCESAnalog Devices, Inc., “MonolithicThermocouple Amplifiers with ColdJunction Compensation: AS594/AD595,” rev. C, 1999.

Basic Micro, “Renesas 3687 TinySeries Starter Kit User Manual,” ver. 2.1,2003, www.basicmicro.com/downloads/Renesas/3687/3687RSKUsersManual.pdf.

———“3687 Starter Kit: Quick StartGuide,” 2003, www.basicmicro.com/downloads/Renesas/3687/QStart.pdf.

D. Kubin, 3687 Evaluation boardschematic, 2003, www.basicmicro.com/downloads/Renesas/3687/Schematics.pdf.

Research International, “ReflowTechnology Handbook,” www.research-intl.com/reflowtechbook.htm.

SOURCESAD594/AD595 Thermocouple ampli-fiersAnalog Devices, Inc.(800) 262-5643www.analog.com

EVB87 Renesas evaluation boardBasic Micro, Inc.(248) 427-0400ww.basicmicro.com

H8/3687 MicrocontrollerRenesas Technology Corp.(408) 382-7500www.renesas.com

PROJECT FILESTo download the code and additionalphotos, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

Photo 4—Here’s an example of a cooked PCB afterreflow and cleaning. Not too bad, huh?

Robert Lacoste lives near Paris,France. He has 15 years of experienceworking on innovative real-time soft-ware and embedded systems.Specialized in cost-optimized mixedsignal designs, he has won more thana dozen international design con-tests. Robert currently manages hisown design and consulting company.You can reach him at [email protected] and visit his web site atwww.alciom.com.

WW

W.G

iURUMELE

.Hi2

.RO

Page 38: GRAPHICS & VIDEO

and detailed in Figure 2. Its purpose isto limit the system’s maximum veloci-ty. The velocity is calculated and thensubtracted from the error signal. Whenthe error signal is at its 2047-countlimit, the motion speeds up until thevelocity reaches a large enough valueto limit additional speed increases.

If you recall, velocity is change inposition divided by change in time. Thevelocity feedback design has P0 to latchthe present position and P1 to latch theprevious position. The latching is per-formed by counting 4,096 clock ticks(4,096 × 50 ns = 0.203450 ms). A littlestate machine transfers the position datainto the appropriate registers and theproper times using states S0, S1, and S3.Note that S2 is not used, so don’t look too

36 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

Last month I started describing atwo-axis motion control system featur-ing an Altera Nios embedded CPU. Infact, I put the entire system inside oneof Altera’s FPGA devices. I left off withV00-00. I had the CPU and one axisdesigned. Also, I did an initial placementand achieved my design goal of 20-MHzoperation. This month I’ll explain howto enhance the axis component byadding velocity feedback and building atwo-axis system. I’ll also detail thesoftware you’ll need to run the design.

Well, I was extremely pleased withthe V00-00 version of this project.Typically, you would review this withall the interested parties in your organ-ization (a design review). And out ofthat hypothetical meeting, supposeservice said that you need to monitorthe temperatures of motors and othercircuitry, and that marketing is reallyclose to having an answer about thenetwork requirements. What to do?

I found Analog Device’s AD7476/7/6serial A/D converters, which have 8, 10,or 12 bits, respectively, of resolution at a1-msps rate. So, I added a four-device SPIserial interface to the Nios processor. Andfor the network requirements, I added aninterface to the LAN91C111 on an Alteradevelopment board. So, now I have aschematic and software, if marketing isever able to firm up their requirements.

Photo 1 shows the new SOPC builder.Note that the SPI interface requiresseven pins, three of which are sharedfor data in, data out, and clock, andfour of which are chip selects, one foreach device. The LAN91C11 interfacerequires just three additional pinsbecause there is already a bus for off-

Designing with the Nios (Part 2)

Last month, George laid the groundwork for a Nios-based two-axis motion control system.Now he discusses velocity feedback and preps you on the software you’ll need to drive it.

chip memory. The pin count can be alimiting factor in any FPGA design.Having too many pins pushes you intoa larger, more expensive package.

The place and route achieved 31.02MHz in the selected device. The maxi-mum clock frequency times got bettereven though I added more logic ele-ments. Don’t count on this to be thenorm. By looking at the timing reportsI see that the longest path is in theaxis-error calculation, which isn’t sur-prising. I could speed up this path andincrease the maximum clock frequen-cy by adding registers in the path. But,as it stands, I’ve met the design goal.

I also added a velocity feedback ele-ment to the design. The velocity feed-back block diagram is shown in Figure 1

FEATURE ARTICLE by George Martin

System Enhancement

Photo 1—This screen shot of the SOPC builder shows the CPU configuration details. Screen peripherals areadded to the CPU from this. The implementation details of the peripherals are also defined.

WW

W.G

iURUMELE

.Hi2

.RO

Page 39: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 37

quencies. If the resonant point in yourmechanical system is below the high-fre-quency cut off defined by the output driv-ers, then the mechanics will oscillatewhenever the offending frequency is out-put. And because the step output containsall frequencies, your system will oscillate.

After you know the resonant fre-quency, you could define a digital fil-ter to remove it from the output sig-nal. The great part about this solutionis that each system probably has aslightly different resonant point, andyou can tune the digital filters for eachsystem. Production will love that.

SOFTWAREI built a set of software routines to

help you understand the Nios design.

long for that reference. I was planning toadd registers for settling time on the cal-culations, and S2 provides another 50 nsof delay for the calculations to complete.

So, I have ∆P over ∆T, and that’savailable on the output pins. This num-ber needs to be scaled. I could scale it bychanging the 4096 clock divider in thevelocity feedback count block. I couldincrease or decrease the time period forthe measurement. If that’s not suffi-cient, I could change the type of counterto a count down and achieve any timeperiod. If that still isn’t enough, I couldadd a multiplier to the VEL[31..0] sig-nal to scale it to the appropriate value.

Figure 1 shows an optional filterblock just before the output signal. Ididn’t include this as part of my design.

This would be a great place to add a digi-tal filter to attenuate any unwanted fre-quencies in the output signal. Most sys-tems have resonant frequencies. Themechanical designers try to eliminatethem, but you usually will be faced withworking around them. If you need a visu-al example, imagine a fly fishing rod. Asyou slowly move your arm and the rod,the tip of the rod exhibits no lag in itspositioning. But, as you start acceleratingyou arm and the rod, the rod’s tip startsto lag. If you move your arm back andforth at just the correct frequency, the tipof the rod will be moving in the oppositedirection of your arm.

You’ve just found the system’s resonantfrequency. The controller’s output can bethought of as a step, containing all the fre-

Figure 1—Aiming for single-axis control with velocity feedback? The A and B inputs derive the current position. The CPU sets the target position register. The errout output isused to drive the servo motors.

Figure 2—For the velocity feedback circuit, the positions are captured in latches P0 and P1. The difference is latched and represents the velocity. The up-counter determinesthe rate of position sampling.

WW

W.G

iURUMELE

.Hi2

.RO

Page 40: GRAPHICS & VIDEO

38 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

I know I’ve got some explaining to do.First, let’s take a look at the constants__TURBOC__ and RUNNING_IN_NIOS.When the Turbo C compiler isinvoked, __TURBOC__ is defined andRUNNING_IN_NIOS is not defined. If__TURBOC__ is not defined, thenRUNNING_IN_NIOS is defined.

Look at the beginning ofCCCONST.h, which you may down-load from the Circuit Cellar ftp site.This file enables code to run in TurboC or any other compiler, without writ-ing to an address that will cause prob-lems on the PC. uart0 is defined atsome constant address in excalibur.h,so accessing it in Turbo C will probablycrash the PC’s operating system. I knowthis because I’ve done it by accident.

Next, the BYTE keyword is definedin CCCONST.h. When different com-pilers and CPUs are used, the value ofdefinitions such as int can change.So, I created keywords including BYTE,

These routines create a test bed for codedevelopment and will actually run thehardware. I used Turbo C++ V. 3.0 in aDOS window to write, compile, anddebug code. I know this is an oldmethod, but it’s great for getting start-ed, especially when the hardwaredoesn’t exist yet. Eventually, you willuse the GNU tool chain to build thesoftware for the Nios CPU.

UARTThe interface to each of the periph-

erals selected for the design is generat-ed as a set of registers. Take the UARTfor example. The register set for theUART is defined as a structure in theexcalibur.h file (see Listing 1).

The structure np_uart (“np” standsfor Nios peripheral) has six 32-bit registersthat interface to the hardware. These reg-isters are memory-mapped I/O. The firstregister is np_uartrxdata, which con-tains the data received in the UART. Theactual data is only 8 bits, but 32 bits arereserved for this and every register. Othersymbols are defined too: na_uart_0 is apointer to an np_uart located at the0x00040000 address; na_uart_0_base isthe base address value for the UART 0register set; and na_uart_0_irq isthe interrupt request number.

The excalibur.h file also contains bitdefinitions for the UART and all periph-eral control purposes. So, the softwarecan be completely written using theexcalibur.h file. To make hardwaredesign changes, all you need is the latestcopy of excalibur.h. If you’ve ever boughta C compiler dedicated to a microproces-sor, it probably came with a header filethat described the CPU; those headerfiles look a lot like excalibur.h.

In the ARMCOM.c file posted on theCircuit Cellar ftp site, you will find theroutines that directly touch the Nioshardware as opposed to transferringdata in and out of the serial buffers inmemory (CCCOM.c and CCCOM1.c).The PutCom0(BYTE c) routine puts aBYTE (8-bit entity) in the UART’stransmit buffer (see Listing 2). First, apointer to the UART register structureis declared (np_uart *uart), and thenthe pointer is set to point to theuart_0 register set in memory-mappedI/O. And finally, the data is placed inthe Tx register (see Listing 2).

INT16, INT32, and UINT8 to definewhat I intend to do.

If I use a different CPU or compiler,I will redefine these values for eachnew implementation. Take a look atthe INT16 for the Turbo C (16-bit) com-piler versus the Nios (32-bit) compiler.Lastly, note that if you are compilingfor Turbo C and running in a DOS win-dow, the output for Com0 goes to thestdout, which is the console on the PC.

The serial communications routinesare in the ARMCOM1.c, CCCOM.c,and CCCOM1.c files. The incomingcharacters generate an interrupt inwhich characters are read from thehardware and placed in a buffer. Inputline-feed characters are ignored. I’vehad trouble when systems send a car-riage return and then line feed whileothers send a line-feed followed by acarriage return. So, I just started ignor-ing line feeds and life became simpler.

Also, I processed complete lines of

Listing 1—The NIOS UART data structure is defined by np_uart. The hardware mapping of the UART isdefined by the (np_uart *) construct.

// UART Registerstypedef volatile struct

int np_uartrxdata; // Read-only, 8 bitsint np_uarttxdata; // Write-only, 8 bitsint np_uartstatus; // Read-only, 8 bitsint np_uartcontrol; // Read/Write, 9 bitsint np_uartdivisor; // Read/Write, 16 bits, optionalint np_uartendofpacket; // Read/Write, end-of-packet character

np_uart

#define na_uart_0 ((np_uart *) 0x00040000) // altera_avalon_uart#define na_uart_0_base 0x00040000#define na_uart_0_irq 16

Listing 2—This Put_Com example will run a PC and Nios. If compiled with __TURBOC__ defined, thenthe character goes to the PC’s console device. If compiled with RUNNINGIN_NIOS defined, then thecharacter is placed in the UART buffer at location 0x40000 (see Listing 1).

// This routine puts a character into Nios Com0: portvoid PutCom0(BYTE c) np_uart *uart; // Create a ptr to a Nios UART

// data structure

uart = (np_uart *)na_uart_0; // Set that pointer to Com0 hardware// Output the data#ifdef RUNNING_IN_NIOSuart->np_uarttxdata = c;#endif

#ifdef __TURBOC__// put_com(c);#endif

/* end of void PutCom0(BYTE) */

WW

W.G

iURUMELE

.Hi2

.RO

Page 41: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 39

could just write to a memo-ry-mapped register offsetfrom some base address. Myapproach takes a couple ofextra instructions for eachoperation, but it workswithout any hassle.

In the CCPOS.C file, Idefined the bit functions forthe Read_Status[15..0] inputsand the CTRL[15..0] outputs.On the input side, I have LoopStatus (OK/fault), Home,

Limit, and Fault indicators for each axis.On the output side, I have LatchPosition, Clear Position, Set Position,Clear Target, Latch Target, and CloseLoop for each axis. I don’t use every oneof these bits because several are redun-dant. I included all of them to show youwhat’s possible in this type of design.

The SetTarget, GetPosition,and SetPosition routines are fairlyself-explanatory. These are used toclear control bits, output/input thedata, and then set any control bits(see Figure 3). The control bits arepositive-edge active.

data as they were received. Idefine an end-of-line charac-ter for each serial port. Whenthat character is received, aline counter is incremented.All the main routine looks atis that line counter. Whenthe input line counter doesnot match the output linecounter, I know a completeline has been received and Istart to process that line.

I selected a Nios UARTwith a fixed data rate and other param-eters. If you look through these serialroutines, you’ll see how to interface tothe Nios UART hardware. You canthen extrapolate to other variationsyou might add to the CPU. Altera alsoprovides documents and code examplesfor the peripherals.

TIMERThe CCTIM1.c file contains the

timer routines. You can set the timerperiod and install the timer interrupt.The timer variables are incremented foreach interrupt. If you have a timer inter-

rupt period of 1 ms, every 1,000 inter-rupts are equal to 1 s in the real world.

I created a timer test option in themain program loop. With this option,you can install and remove the timerinterrupt, and set the interrupt period.

PIO INPUT AND OUTPUTI used a parallel I/O scheme to inter-

face to each axis. Basically, I set a valuefor the Nios PIO and that worked itsway down through the hardware. Thisis the safest approach I could think of.It’s slower than designing each axis as adevice, like the UART, for which you

Figure 3—This circuit is looking for a change from zero to one. After the changeoccurs, the circuit’s output goes to a one for one clock period.

WW

W.G

iURUMELE

.Hi2

.RO

Page 42: GRAPHICS & VIDEO

George Martin began his career in theaerospace industry in 1969. After fiveyears at a real job, he set out on his ownand cofounded a design and manufactur-ing firm (www.embedded-designer.com).George’s typical designs include servo-motion control, graphical input andoutput, data acquisition, and remotecontrol systems. He’s a charter memberof the Ciarcia Design Works Team. He’scurrently working on a mobile commu-nications system for the military. In hisspare time, George has become a nation-ally ranked revolver shooter. Contacthim at [email protected].

RESOURCESAltera Corp., “Nios UART,” DS-NIO-SUART-3.0, 2003.

Nios peripheral library, www.altera.com/products/devices/nios/features/nio-peripherals.html.

SOURCESNios embedded processor, SOPCBuilder, QuartusII design softwareAltera Corp.www.altera.com

40 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

an int, which is a 32-bit entity. Youneed to test this assumption whenyou’re debugging the hardware.

You now have an axis and a step size.The motion system should be resting,and the position and target registersshould be equal values. However, notethat the target register is constant, andthe position register varies slightlybecause outside disturbances cause themechanism to move.

I have defined target registers for eachaxis. You need to add the step to the tar-get register and set that new value in thehardware. This causes the hardware togenerate an error signal that drives theaxis motor in a direction to reduce theerror. You can monitor the position untilthe motor stops and its close enoughto the target. If all is well, you’re done.

A word of caution here: Lots of thingscan go wrong. The mechanism couldrun into something and never get to thetarget position. The step size could beinacurate and you might move too farpast your limit. The move could be soslow that you timeout before reachingyour goal. The motor could overheatand shut down. Furthermore, you couldreach your goal but be unstable, oscillat-ing back and forth across the target. Ididn’t consider this when I wrote thecode. I just looked for a way to reach thetarget. This gets you started on the rightfoot. You also might want to modify thedesign to address the potential problems.

You’ll notice that the RunMotion rou-tine assumed the axis was at some sortof acceptable, stable position. How didyou get there? Well, you went through azeroing process, which moved the axis tothe home position, which was zeroedalong with the target registers. Actually,each axis has a home, zero, and limitposition defined by its construction.

Home is a position that you can moveto rapidly. Some overshooting is permit-ted. Zero is a position found under stable,repeatable conditions. For example, mov-ing to zero occurs at a rate until an opti-cal sensor is tripped. Limit is a fault-typecondition that indicates you’ve gone toofar. Sometimes software reacts to thelimit condition, and sometimes the hard-ware takes over and shorts the motor,causing the axis to stop abruptly. You canrecover from a limit condition by movingthe axis by hand. If you try to move

quickly, the motor will act as a generatorand the short will act like a brake.

A ZeroAxis() routine takes care ofthis homing operation. Its implementa-tion requires information from outsidesensors. Keep in mind that I used hypo-thetical data for this article rather thangathering data from sensors. Therefore,you’ll want to pay more attention tothe comments than the actual code. Isuggest adding a GoHome(INT16 Axis)routine that would close the loop andstart stepping relatively small amountstoward the home direction until thehome sensor is activated.

NEXT Next month I’d like to show you a

complete system with... Wait a minute.Why don’t you take over? It doesn’thave to be a Nios; any FPGA vendor’ssystem would be good. Come on, showus where you’re going today. I

The InitAxis routine opens thecontrol loop for the axis. Then, it setsboth the position and target registersto zero and closes the loop.

I left out looking for errors in thecontrol loop. Potential errors include ahigh motor temperature reading, detec-tion of limit input, or a timeout on amove command. Each system is so dif-ferent that showing one implementa-tion is a waste of ink.

Another feature of the Nios PIO inputregisters is that an interrupt can be gen-erated for an event on any input bit. If asafety interlock is activated, you mightwant to open the loop immediately.

MOTION CONTROLYou have two options for motion test-

ing in the main control loop. The first isto zero both axes. The second is to moveone of them a predetermined distance.

Let’s start with the second command.The format is as follows: G n dddd<CR>.“G” is the unique command prefix,“n” is the axis, “dddd” is the commandamount, and “<CR>” is the end-of-com-mand character. This data is enteredinto the serial port and processed usingthe call count = ReadLineCom1(buf).The return value is the number ofcharacters returned in buf. If there areany, the main loop attempts to processthe returned characters. The first char-acter is the test option selected. If thatfirst character is “G” or “g,” then con-trol is transferred to RunMotion andthat routine is passed a pointer to therest of the command line.

The RunMotion routine takes thepointer and extracts the axis numberand the size of the step. It does so byfirst ignoring (skipping over) spaces inthe command string. Then, a call goesto the C atoi() routine, which returnsthe integer value of the characters start-ing at the pointer value passed to it.That return value is the axis number.

Skipping over the axis number andany subsequent spaces places the point-er at the start of the step size. Theatol() function is used to extract thevalue. Be careful here. You need to rep-resent position and step sizes in 32-bitentities. In Turbo C, atol is used toget a 32-bit return value. In Nios, Iselected a 32-bit CPU, so I expect thecompiler to interpret atoi() to return

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

WW

W.G

iURUMELE

.Hi2

.RO

Page 43: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 44: GRAPHICS & VIDEO

DS requires only approximately60 words of program memory. It wasdesigned for this kind of interface, butmy only debugging tool is awkward touse, and I was more interested in see-ing waveforms than writing anotherdebugging tool. If one or more of theprocessors had been tied up in a time-intensive task while needing to attendto the firmware-only communicationschannel, I would have used this one.

The serial peripheral interface (SPI)does not require any critical timing. Itonly needs a small amount of code, andwould have been a good candidate,except that it would have required athird wire, which is undesirable for theinterface between the graphic displayunit and the capture and control unitbecause of the cable between them.

When it came time to actually writethe code, I settled on asynchronousserial ASCII for all the communica-tions channels, including the one thatwas to be implemented in firmware.The second serial channel in thewaveform capture controller is easy toimplement using the compact code Ifound on the ’Net. As for a debuggingtool, I realized that if I would stick to

printable ASCII codes, I could usethe terminal program on my PCand directly interact with the con-trollers. And that’s what I did.

DISPLAY MODULEThe graphic display unit’s inputs

are power and asynchronous serialdata. Its output is handshake datato its host, and it displays informa-tion by writing black dots on a

42 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

After building the minimum masswaveform capture circuit that Idescribed last October (“Minimum MassWaveform Capture,” Circuit Cellar,issue 159, 2003), I couldn’t resist theurge to build an oscilloscope-like instru-ment with it. The waveform captureengine was already designed, so all Ineeded were a little analog processing, asimple graphic display, a user interface,and some interchip communications totie it all together.

My waveform capture and display sys-tem is composed of two circuit assembliesincorporating a total of three AtmelAT90S2313 microcontrollers (see Figure 1).One assembly is the graphic displayunit, which includes a Seiko-EpsonG1216B1N000 64 × 128 graphic LCD, anadjustable negative bias supply for thedisplay, and a microcontroller-based seri-al interface. I put the graphic display unitin a separate clear plastic box so I couldposition it for easy viewing; it’s inde-pendent of the rest of the electronics.Because the unit is in its own box, I canuse it with other projects. The displayand control panel are shown in Photo 1.

The other assembly is the captureand control unit, which includes thewaveform capture electronics thatsupply the waveform and triggersignals to the waveform capturecontroller. It also has all of the usercontrols, including those for signalgain and offset, triggering, timebaseadjustments, a four-digit LED time-base display, and a trigger indicatorLED, all of which are minded by theuser I/O controller. All the commu-nication between the capture con-

Triple AVR Waveform Capture and Display

Dick built a simple waveform capture and display system around three AT90S2313 micro-controllers. Although it’s not a replacement for a real-time oscilloscope, he relies on the sys-tem for a variety of tasks such as monitoring the I/O on a microcontroller.

trol unit and the other two controllersis 0- to 5-V asynchronous serial.

WHY ASYNC SERIAL? Each of the three controllers has a

hardware UART on it, but the wave-form capture controller has to supporttwo bidirectional communications chan-nels (one to the graphic display unit andthe other to the user I/O controller), andthat means one or more of the commu-nications channels must be imple-mented in firmware only. I looked atPhilips’s I2C protocol a couple of times.It’s certainly well proven and designedfor exactly this kind of interchip com-munication. But, I was concerned aboutthe amount of code space a firmwareimplementation would take and thesevere demands on the slave controller’sresponse time. Most of all, I dreaded thehassle of debugging something I hadlittle experience with and no tools for.

The DS protocol turned out to be abetter choice for this project than I2C.It’s a two-wire serial protocol that Iwrote for some earlier projects inwhich I2C wasn’t suitable because ofits demands on the slave controller’sresponse time.

FEATURE ARTICLE by Dick Cappels

Photo 1—It works! I removed the display from its plastic box forthis picture. The controls are arranged in a manner similar tothat found on old Tektronix analog oscilloscopes. The red lightbelow the timebase display is the trigger signal indicator.

Three Controllers Make a Waveform Monitor

WW

W.G

iURUMELE

.Hi2

.RO

Page 45: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 43

ASCII Input mode. $82 switches toBinary Input mode, and $83 restartsthe firmware and controller.

The controller’s main loop watchesfor data coming into the UART. Whentwo successive address bytes arereceived, they are used as x,y coordi-nates and a dot is written at thatpoint. Then, it sends an ASCII asteriskcharacter back to the host to indicatethat the operation has completed. Anybyte received with a value higher than127 is interpreted as a command, andthen the execution jumps back to thestart of the main loop. If an unsupport-ed command is received, it sends anASCII exclamation point before return-ing to the main loop. The acknowledge(ACK, $06) and negative-acknowledge(NAK, $15) are traditionally used ashandshakes, but I used the asterisk andexclamation points to make sure theywould print on all ASCII terminals.

CAPTURE AND CONTROLTwo circuit boards are inside the cap-

ture and control unit’s plastic enclosure.The main board holds two microcon-trollers: the waveform capture controllerthat digitizes the analog waveforms andthe user interface controller that attendsto the user input buttons and the LEDtimebase display. Analog circuitry pro-vides minimal signal processing for theanalog waveform and triggering. Theother board is the control panel boardon which the user controls are mount-

ed. The circuitry forboth boards is shownin Figure 3.

Early in the project,I decided to use twoseparate controllersfor the waveform cap-ture and user I/Ofunctions so I couldput them at oppositeends of the circuitboard to minimize thenoise pickup by theanalog circuits (seePhoto 2). As it turnedout, using two sepa-rate controllers alsohelped simplify thedevelopment process;it forced me to usesmall modular pro-

light background at locations speci-fied by the host.

The power for the graphic displayunit comes through a 7805 regulatorin a TO-220 package. The 7805 supplies5 V to the Seiko module, the microcon-troller, and a voltage multiplier andadjustable regulator that provides thenegative bias for the display. To makethe negative supply, the buffered outputof an NE555 oscillator is passed througha five-stage, capacitor-diode, half-wavevoltage multiplier to provide a negativepower supply for the op-amp, whichprovides a regulated bias supply that isadjusted with a contrast potentiometer.

As for the original breadboard, I wasdisappointed to see that the NE555’soutput dropped to less than 3 VPP

under load. The datasheet confirmedthat this is expected, so I added a two-transistor saturating buffer so I couldget the necessary negative voltagewith the minimum of multiplier stages.The transistors in the buffer saturate,causing the voltage multiplier to bedriven within a couple hundred milli-volts of ground and the 5-V line.

The inverting serial interface is aclever circuit that I first saw inAtmel’s AVR910 application note. Ittakes its negative power supply fromits host, which makes it well suitedfor projects like this. The interface’soutput swings negative if it’s connect-ed to my PC’s EIA-232 port for debug-ging with the terminal program. Itsafely swings down toonly a little aboveground if it’s connect-ed to the 0- to 5-VCOMS input on thewaveform capture con-troller. There are noswitches, jumpers, orfancy sensing circuits;it just works that way!

The interface firm-ware for Seiko’s 64 ×128 LCD was compli-cated because the dis-play appears as two 64 ×64 displays side by side,while the interface wasto make it appear as asingle continuous dis-play. There are separatechip-select pins for the

two halves, and the AT90S2313 con-troller was a pin short, so an inverterwas added to make two chip-select linesout of one (see Q3 in Figure 2).

When power is first applied, theAT90S2313 LCD interface controllerresets the LCD, erases the screen, anddraws a line from the upper-left cornerto the middle of the bottom edge andthen another to the upper-right corner,which looks similar to a large V span-ning the display. This is a visual indica-tion that the power supply, displaymodule, and serial controller are up andrunning. At that point, the graphicinterface controller enters its main loopwhere it waits for data from its host.

Data from the host is either com-mands or parts of the x,y screenaddress at which a dot is written. Aninternal flag tells the UART characterreceive routine whether to receivedata in 2-byte ASCII hex format,which is useful for debugging, or insingle-byte binary format, whichneeds only 2 bytes for a dot addressinstead of 4 and doubles throughputwhen writing to the screen.

Because the highest dot address is127, I was able to reserve those valueswith the most significant bit set (cor-responding to decimal values of 128 orhigher) as commands, while values of127 or lower were treated as x,yaddress data. As for the commandcodes, $80 erases the display andsends an asterisk, and $81 switches to

8 to 14 VDC

Power return

5-VRegulator

AT90S

2313M

icrocontroller

Signal Attenuator

AT90S

2313M

icrocontroller

Serial ASCII

Serial A

SC

II

Amplifier

SignalGround

External trigger

Triggercircuit

Waveform capturecontroller

User interface controller

4 × 7LED display

8 8 8 8

User input buttons

Capture and control unit

AT90S2313Microcontroller

Adjustablenegativesupply

64 × 128LCD Module

LCD Interfacecontroller

Graphic display unit

5-VRegulator

Figure 1—The waveform capture and control system is composed of a capture and control unit and agraphic display unit connected to each other with a 50-cm, five-conductor flat cable.

WW

W.G

iURUMELE

.Hi2

.RO

Page 46: GRAPHICS & VIDEO

44 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

small capacitor should be selected andplaced in position C1 or C2 to compen-sate for the differences in capacitance,which include wiring capacitances andthe input capacitance of the FET bufferfollowing it. With my layout, I needed5 pf for C2 and C1 was not used.

Source follower Q1 provides high-input impedance to the attenuator andshifts the signal to positive so that sig-nals below ground are within the

grams rather than one large,complex one.

The unregulated 8 to 14 VDCcoming into the assembly isshunted by a 14-V varistor toprotect against line transients.After passing through an on/offswitch, the unregulated voltagedirectly powers the op-amps andthe 78L05 voltage regulator.Then, it’s sent off the boardthrough the display connector tothe graphic display unit.

The input waveform is capaci-tively coupled to the top of a10:1 attenuator. The waveformcapture controller’s full-scale input is1 V, so the 10: attenuator raised thefull screen sensitivity to 10 V, whichis more than enough for most of myneeds. Closing the switch across thecoupling capacitors makes the inputdirect coupled. The ratio of the capaci-tive reactance across each of the atten-uator resistors should be the sameratio as the resistance values in orderto make square waves look square. A

input range of the waveformcapture CPU. Either the indi-vidual FET used for Q1, thevalue of R1, or both may haveto be selected to obtain the nec-essary 1.5- to 3.5-V gate tosource voltage. A gain stagemade with A1A and A1B allowsfor the selection of a bandwidth-limited version of the signal togive 10× gain for the full-screensensitivity of 100 mV. The fineand coarse offset potentiometersare adjusted so that the 0-VDCpoint on the displayed waveformdoesn’t shift when the gain

stage is switched in or out. The2N2907 on the output of A1A protectsthe comparator input of the waveformcapture CPU from excessive voltage.

Trigger signals, whether they’re fromthe separate trigger input or the incom-ing waveform, can be either AC or DCcoupled; they are compared in compara-tor A2A with the trigger level set by thetrigger-level potentiometer. The result-ing pulses are applied to the trigger input

Photo 2—The main board is at the top. The control board is at the bot-tom. The waveform capture controller is on the right-hand end of themain board, and the user I/O controller and the LED timebase display areat the left-hand end. The analog circuitry is in the middle.

Figure 2—The op-amp regulates the contrast voltage at –2.2 times the voltage set on the wiper of the contrast potentiometer. The NPN and PNP transistors can be 2N2222and 2N2907 (or similar devices), respectively.

WW

W.G

iURUMELE

.Hi2

.RO

Page 47: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 45

of the waveform capture controller andto a simple one-shot made with com-parator A2B, which drives the triggersignal indicator LED with voltage fol-lower A1C. As a result, the LED is illu-minated whenever triggering signals aresent to the waveform capture controller.

The waveform is digitized by suc-cessively comparing the input wave-form at specific time intervals relativeto the trigger signal with a referencevoltage that is stepped from 1 V tonearly ground. Vertical centering ofthe waveform in the display is accom-plished by changing the reference volt-age by adding current from Q1 (whichis set by the vertical centering poten-tiometer) to the resistor divider on thecontroller’s PWM output. The PWMoutput divides the PWM signal downto 1-V full-scale.

WAVEFORM CAPTURE CONTROLLERThe firmware for the waveform cap-

ture controller is a modified version ofthe firmware posted on the CircuitCellar ftp site for my October 2003article (ftp.circuitcellar.com/pub/Circuit_Cellar/2003/159.). Duringpower-up initialization, the waveformcapture controller’s firmware waitsuntil the serial data line from thegraphic display unit goes high, whichindicates that the LCD interface con-troller is ready to receive data. Thiskeeps the system start-up synchro-nized when the graphic display unit hasa separate power supply. After that, itsends an erase command to the dis-play and waits for an acknowledgmentbefore sending a “Switch to ASCIIdata” command to the graphic displayunit. It then sends a character to the

user interface controller to display thedefault timebase setting.

Having set up the system, it goesinto its main loop where it continu-ously cycles through the process ofcollecting a waveform, sending thewaveform data to the graphic displayunit, and checking to see if a characterfrom the user I/O controller wasreceived by the UART. In each meas-urement cycle, 100 waveform samplesare collected at 6-bit resolution to cor-respond to the 64 × 128 display for-mat. Some of the extra columns areused as vertical scale markers, whichare written to the display each meas-urement cycle.

Captured waveforms are sent to thegraphic control unit. The handshakesare received at 19,200 bps, 0 to 5 V withEIA-232 polarity on regular I/O pins, by

Figure 3—Take a look at the circuitry on the front panel board and the main circuit board. CPDNG is a special ground bus on the front panel board. The 39-kΩ resistor on thebase of Q2 was added to stop RF oscillations.

WW

W.G

iURUMELE

.Hi2

.RO

Page 48: GRAPHICS & VIDEO

46 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

firmware asynchronous serial commu-nications routines. Communicationwith the user interface controlleroccurs at 9,600 bps, 0 to 5 V with thesignal polarity inverted from EIA-232and uses the hardware UART. Thehardware UART is used for user I/Oto make sure user input is not missed,even during the time-intensive tasksof capturing waveforms and sendingthem to the graphic control unit.

When the waveform capture con-troller receives a button code from theuser interface controller, it performsthe indicated internal functions, suchas adjusting the timebase, and returnsone or two characters depending on thebutton code. If the timebase changes, itsends a symbol corresponding to thecurrent timebase setting. If the buttoncode is a toggle, such as the one to tog-gle trigger polarity between positiveand negative edges, it also sends backthe four status flags that show thestates of the four toggle controls.

Although the status flags weren’tused by the current version of theuser interface controller, they were

handy when debugging with the termi-nal program. I can use them to update

status LEDs if I update the user inter-face controller code in the future. The

ASCII Character Waveform capture unit Internal action taken when Action taken when received response received by waveform by user I/O controller

capture unitFunction code0 Timebase value Set sampling to 1 µs Display “1–6”1 Timebase value Set sampling to 2 µs Display “2–6”2 Timebase value Set sampling to 5 µs Display “5–6”3 Timebase value Set sampling to 10 µs Display “10–6”4 Timebase value Set sampling to 20 µs Display “20–6”5 Timebase value Set sampling to 50 µs Display “50–6”6 Timebase value Set sampling to 100 µs Display “1–4”7 Timebase value Set sampling to 200 µs Display “2–4”8 Timebase value Set sampling to 500 µs Display “5–4”9 Timebase value Set sampling to 1,000 µs Display “1–3”: Timebase value Set sampling to 2,000 µs Display “2–3”; Timebase value Set sampling to 5,000 µs Display “5–3”< Timebase value Set sampling to 10,000 µs Display “10–3”

Button codeA,a Status flags Toggle triggered/free run NoneC,c Status flags Toggle capture enable on/off None D,d Status flags, Timebase value Decrement timebase NoneE,e Status flags Toggle auto erase NoneF,f Status flags Toggle trigger polarity NoneI,i Status flags, Timebase value Increment timebase None

Table 1—These ASCII codes can be received by either the waveform capture controller to set capture parametersor by the user interface controller to set the timebase display. The user interface controller can only generate the A,C, D, E, I, and F characters. It does not use the status flags, but characters “0” through “<” and the status flags arehelpful for debugging the waveform capture controller using a serial terminal.

WW

W.G

iURUMELE

.Hi2

.RO

Page 49: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 47

functions and button codes are shownin Table 1.

The status flags returned by thewaveform capture controller are gen-erated by masking off the irrelevantbits in the register that the flags arestored in and adding the $50 hexvalue to it. None of the button or func-tion codes have values higher thanthe $50 hex value, so any byte with ahex value of $50 or higher can be inter-preted either on an ASCII terminal orby the user interface controller (if Iadd features) as containing flags.

The flags have significance whenthey are set: flag 0 indicates that eras-ing the display before rewriting isenabled; flag 1 indicates that trigger-ing is enabled; flag 2 indicates thattriggering occurs on the positive edge;and flag 3 indicates that the timebaseis in free-run mode.

USER INTERFACE CONTROLLERThe last and easiest part to design

was the user interface controller.Having thoroughly worked out andtested the interface to the waveformcapture controller using a terminal,designing the user I/O controller andcircuitry, as well as writing anddebugging the firmware, was a pieceof cake.

Inside the user interface controller,a round-robin multitasker, triggeredby Timer0 interrupts, refreshes one ofthe four LED characters or checks theinput buttons at each interrupt sothat all four characters are displayedand the buttons are checked everyfive interrupts. The controller’s mainloop continuously checks for a char-acter arriving in the UART’s receivebuffer. After a character is received, itchecks the character against charac-ters corresponding to the 13 possibletimebase settings. When a matchoccurs, the appropriate bit patternsare loaded into registers that holdrefresh data for the LED display.

Using this technique, everythingother than the characters relating tothe timebase settings are ignored.Thus, the status flags are ignoredwhen they are sent from the wave-form capture controller. The timebasedisplay shows the selected waveformsample rate in a 1-2-5 sequence from

1–6 to 10–3, which represent 1 µs and10 ms per sample, respectively. Thedisplay codes are shown in Table 1.

Updating the timebase display inresponse to data returned from thewaveform capture controller insteadof directly from the user-control but-tons causes a perceptible lag betweenpressing a timebase button and seeingthe display change. That’s becausethe waveform capture controller does-n’t send the updated timebase valueuntil after the completion of thewaveform capture cycle in which thecharacter has been received. I had todo it this way. When I tried settingthe display according to the buttoncodes sent to the waveform captureunit, the display was hopelessly outof sync as soon as the waveform cap-ture controller missed a button code.

The LED is a common cathode.The anodes are driven by the userinput controller’s I/O port B through1-kΩ current-setting resistors. Whenthe multitasker gets to the time slotassigned to sensing the input buttons,port B changes to inputs, the buttons’states are read, and then the port pinsturn back to outputs. An additional1-kΩ resistor between the buttonsand ground protects port B fromover-current when a button ispressed while its corresponding I/Opin is driven high.

The user input buttons include thefollowing: Triggered/Free-Run Toggle,which enables you to vertically centerand measure DC voltages, even if notrigger signal is available; PositiveTransition/Negative TransitionTriggering Toggle; Capture Enable/Disable Toggle, which stops samplingand freezes the display; and EraseBefore Write Toggle, which keeps thedisplay from erasing a captured wave-form before writing the new one. Thislast feature makes the display lookmore solid because the display doesn’tdisappear before it’s rewritten in eachwaveform capture cycle.

BUTTONING UPThe graphic display unit resides in

a clear plastic box with one 50-cmflat cable that carries serial data andpower to connect it to the outsideworld. The waveform capture unit is

WW

W.G

iURUMELE

.Hi2

.RO

Page 50: GRAPHICS & VIDEO

48 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

mounted in a clear plastic pencil boxthat’s the same color as the LEDs,which can be seen through the top ofthe box. Note that the user controlsare mounted on the top of the box.

Along with a ground lead, the trig-ger and signal inputs exit the side ofthe case close to where the flat cableto the graphic display unit and thepower cable to the 12-V wall warttransformer exit the case. Captivemicrograbbers and a subminiaturealligator clip enable you to attach thesignal, trigger, and ground leads. Allof the cables plug into the mainboard. Note that when the top of thepencil box is closed, all of the cablesare captive.

Since building this little waveformmonitor, I have come to rely on it fora variety of indication and measure-ment tasks. Although it isn’t a sub-stitute for a real-time oscilloscope,it’s just fine for things like seeingwhat the I/O on a microcontroller isreally doing, and even sorting througha bag of mystery inductors from thesurplus store. I

National Semiconductor Corp., “LM124/LM224/LM324/LM2902 Low PowerQuad Operational Amplifiers,”SA009299, 2000.

———“LM193/LM293/LM393/LM2903Low Power Low Offset Voltage DualComparators,” DS005709, 2000.

Philips, “I2C Bus Specification Version2.1,” 9398 393 40011, 2000.

Seiko Instruments, “Liquid CrystalDisplay Module G1216B100N,”MG1216B1N000-002, 1993.

Dick Cappels enjoys tinkering withand writing about analog circuits andmicrocontrollers. He has publishedseveral papers on the topic of elec-tronic displays in computer systemsand is currently active in the Societyfor Information Display. Dick holds18 U.S. patents in areas including dis-play technology, color management,and capacitive proximity sensing. Youmay reach him at [email protected].

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

RESOURCESAtmel Corp., “AVR910: In-SystemProgramming,” rev. 0943C, 2000.

———“8-bit AVR Microcontrollerwith 2K Bytes of In-System Program-mable Flash: AT90S2313,” 0839I, 2002.

D. Cappels, “DS Two-Wire Protocol,”users.cableaz.com/~cappels/dproj/dspage/ds.htm.

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

LM324 Op-amp, LM3939 ComparatorNational Semiconductor Corp.www.national.com

G1216B1N000 LCDSeiko Instruments, Inc. (310) 517-7771www.siielectroniccomponents.com

WW

W.G

iURUMELE

.Hi2

.RO

Page 51: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 52: GRAPHICS & VIDEO

50 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

I speak regularly with the electricaland application engineers that supportthe ICs and modules that I talk aboutin my columns. The reason for this issimple: I get into their heads. As aresult, I have a better understandingas to how to work the ICs and elec-tronic modules into applications thatmay interest and help you. Gettingfreaky with an application doesn’talways make sense for you, the reader.So, I always try to use a device for itsintended purpose. I’ll do that this timearound, but with a slight twist.

dsPICDEM (BEFORE)As you can see in Photo 1, I have a

Microchip dsPICDEM 28-pin demoboard loaded with a dsPIC30F2010 engi-neering sample. Engineering samples arelike rental cars: you get one, run theheck out of it, and buy your own if theexperience is positive. I tend to work onthe bleeding edge of most demo boards,so I took this one for a test drive. Now

troller communications channel, I con-nected the dsPIC30F2010 and thePIC18F452 coprocessor serially, usingthe dsPIC30F2010’s UART interface andthe PIC18F452’s USART interface. Bydirectly connecting the USARTs, I pro-duced a simple and relatively high-speedcommunications link with a minimumof hardware and firmware effort.

Next, I added a NICholas 10/100microcontroller NIC, which is solelysupported by the PIC18F452. The ideahere is to provide a fast Ethernetinterface to the motor control func-tionality of the dsPIC30F2010 onthe dsPICDEM demo board. After theEthernet interface is established, youcan get at the dsPIC30F2010 and itsinternal organs in all sorts of ways.

dsPICDEM (AFTER)Photo 2 is a view of the modified

dsPICDEM 28-pin demo board. TheNICholas Ethernet NIC stacked onthe dsPICDEM is based on the ASIXAX88796L 10/100 Ethernet engine IC,which does all of the work that makesEthernet things go.

Uncomplicated dsPICImplementation

APPLIED PCs by Fred Eady

I’ll let you know how it felt becauseyou’ll probably get the real thing onyour dsPICDEM 28-pin demo board.

At first glance, the dsPIC30F2010datasheet gave me the impression thatthe dsPIC30F2010 was designed to bean integral part of a motor control orpower control system. The six PWMoutput channels can go either way,while the quadrature encoder interfacesupports the motor control side of mydatasheet interpretation. Although thedsPIC30F2010 sports an internal DSPengine, its pins are heavily multiplexedto incorporate all of the motor control-oriented functionality. That’s a goodthing if all you want to do is dictate theactions of a motor or supply numerousPWM signals to a power controller/voltage regulator subsystem.

No matter what, you still have to beable to talk to the dsPIC30F2010 to con-trol it dynamically. The dsPIC30F2010is capable of communicating with itsthree-wire SPI module, I2C, or seriallyusing its internal UART module. Thedownside of taking the dsPIC30F2010out of solitary confinement is thatyou’ll either have to give up somemotor control pins to the communi-cations interface of your choice orbring in some help.

There isn’t much on the dsPICDEM,but considering all of the stuff insidethe dsPIC30F2010, not much else isrequired if motor control is your goal.Just add an H-Bridge, tie in yourencoder, and write some PWM drivercode. That’s nice, but I had somethingelse in mind (see Figure 1). First, Iadded a coprocessor to the dsPICDEMin the form of a PIC18F452. To facili-tate a microcontroller-to-microcon-

As soon as Fred got his hands on a Microchip dsPICDEM 28-pin demo board, he modified it.This month he proves that you don’t have to be a DSP wiz to get started with the dsPIC.

Photo 1—This is one unassuming development board,but don’t let the lack of componentry fool you. There’s alot of bang in this little package.

Photo 2—Check out my dsPICDEM 28-pin demo boardafter a trip to the Florida room chop shop.

WW

W.G

iURUMELE

.Hi2

.RO

Page 53: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 51

The AX88796L is an NE2000 regis-ter-compatible, local CPU busEthernet controller with an embedded10/100-Mbps PHY transceiver. Usingthe IEEE802.3 and IEEE802.3u stan-dards, the AX88796L provides 10- and100-Mbps Ethernet functionality infull- or half-duplex operation.

Note that 8 KB of 16-bit SRAM isincluded on the AX88796L, as is an 8-or 16-bit local CPU interface that canaccommodate a wide range of micro-controllers. The AX88796L can beconfigured to run in either 8- or 16-bitmode by simply setting a bit in itsdata configuration register (DCR).Specifying the CPU interface is just aseasy. The AX88796L can be config-ured to run in one of four local busCPU modes by jumpering pins CPU[0]and CPU[1] to logic levels thatinstruct it to interface to one of thefollowing environments: an ISA, an80186, a 68000, or an 805X. TheNICholas loaded on the dsPICDEM

demo board is jumpered for ISA opera-tion, which equates to both CPU[0]and CPU[1] being pulled low.

The AX88796L, which is housed ina 128-pin LQFP low-profile package,typically consumes less than 100 mAfrom a 3.3-V power source. In additionto smashing packets through a wire,the AX88796L’s I/O is 5-V tolerant,which means you really don’t have toconvert the dsPICDEM’s 5-VDCpower supply to 3.3 VDC to accom-modate the Ethernet controller. TheAX88796 L’s clock lines are the onlyI/O lines that are not 5-V tolerant. A25-MHz crystal or oscillator can beused as the AX88796L’s clock source.

To keep the part count down andmaintain the smallest footprint possi-ble, the AX88796L development board’sEthernet magnetics are contained with-in a single LAN Mate unit. The LANMate NU1S041C-434 complies withthe IEEE 802.3u standards. The moduleused on the NICholas is a 1:1 center-

tapped configuration that contains allof the necessary electronics needed tointerface to standard Cat 5 twisted-pairmedia. Three-link activity and speedstatus LEDs are also incorporated inthe LAN Mate module.

The NICholas’s dual-row headerpins out five of the AX88796L’s addresslines that I used to gain access to theAX88796L’s internal NE2000 (MAC)register set (SA0–SA4). The remainingaddress lines are hard-wired at thedsPICDEM’s dual-row female NIC sock-et to select a base address of 0x200,which is the default base address forthe AX88796L. By using the defaultaddress, the three base address pins—I/O_BASE[0], I/O_BASE[1], andI/O_BASE[2]—can be left in a disconnect-ed state. This allows the AX88796L’sbase address pins to follow their internalpull-up and pull-down circuitry andselect the base addresses of 0x200(I/O_BASE[0]=0, I/O_BASE[1]=1 andI/O_BASE[2]=1). I hand-wired this

Figure 1—No surprises here. Imagine what you can do with six remotely controlled PWM outputs.

WW

W.G

iURUMELE

.Hi2

.RO

Page 54: GRAPHICS & VIDEO

52 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

baby in, so every extra pin I don’thave to connect a wire to is goodness.

In terms of raw processing power,the dsPIC30F2010’s MIP rate fallswith the voltage, which gave me onemore reason not to rip up thedsPICDEM and modify the on-board,5-V power supply just to accommo-date the NICholas. So, to keep theAX88796L 3.3-VDC power supply cir-cuitry as simple as possible, and tokeep the dsPIC30F2010’s performancepotential high, I powered theNICholas using a Zetex ZSR330 volt-age regulator, which is fed by thedsPICDEM’s 5-VDC power supply.The ZSR330 doesn’t require any exter-nal components for stability.

The DPDT switch you see mountedon the dsPICDEM in Photo 2 is therein place of the jumpers and shortingblocks you see there in Photo 1. Iused the MPLAB ICD 2 as thedsPIC30F2010 debugging tool. Aftersome initial serial routine failureswith BASIC code that executed in thedebugger correctly, I finally figuredout that the UART transmit andreceive lines are doing double-duty asthe MPLAB ICD 2 debugger commu-nication lines. To circumvent this sit-uation, I used a dsPIC30F2010 config-uration fuse setting that shifted theMPLAB ICD 2 debugger lines to analternate set of MPLAB ICD 2 com-munication pins.

The dsPIC30F2010 has four sets ofalternate MPLAB ICD 2 interfacepins. The primary set of pins, EMUCand EMUD, is multiplexed with theprimary UART transmit and receivepin pair. The EMUC1 and EMUD1pins are positioned on the alternateUART transmit and receive pair locat-ed on port C. The third pair of pins,EMUC2 and EMUD2, is found on portD, and the final pair of pins, EMUC3and EMUD3, resides on port B.

Having a MPLAB ICD 2 interfaceson different ports gives you the flexi-bility to hang an MPLAB ICD 2debugger on pins that you aren’t try-ing to use in the debugging process. Inthis case, the jumpers and the configu-ration fuse setting switched theMPLAB ICD 2 from EMUD andEMUC to EMUD1 and EMUC1 toallow the serial port pins originally

assigned to the MPLAB ICD 2 to beused as transmit and receive lines inthe debug process. I added the DPDTswitch because the MPLAB ICD 2must use the EMUD and EMUC inter-face to initially load the compiledcode and debug executive with thealternate MPLAB ICD 2 interface fusesetting into the dsPIC30F2010.

After the debugger load is complete,the jumpers have to be moved to con-nect the MPLAB ICD 2 to theEMUD1 and EMUC1 interface pairand free the EMUD and EMUC pinsto be used as the UART transmit andreceive pins. I moved the jumpersback and forth once before deciding tomount the DPDT switch in theirplace. Another way to avoid movingjumpers or adding switches is to codethe dsPIC30F2010 to use the alternateUART transmit and receive pins. Todo that with the dsPICDEM requirescustom trace cutting and rewiring.Adding the DPDT switch is the easi-est way out.

dsPIC30F2010 CODINGI always like to start out with a new

microcontroller by conquering theserial interface. After I get the serialport of that microcontroller working,other things just seem to fall intoplace. My first experiences with thedsPIC30F2010 UART were unhappy

ones because I didn’t realize that theMPLAB ICD 2 was messing up theoutgoing data. However, after I finallycaught on to what was transpiring,using the dsPIC30F2010’s UART wasas simple as Listing 1 shows it to be.

Although simple, the code inListing 1 is instrumental in that thisis the way the dsPIC30F2010 and thePIC18F452 communicate. Taking thecode line by line, the dsPIC30F2010’sUART is enabled by setting the mostsignificant bit of the U1MODE register.The dsPIC30F2010’s UART data rate iscalculated with the following formula:

FCY is the instruction clock rate. BRGis the value to load into U1BRG fordata rate clock generation.

The U1BRG statement in Listing 1solves for BRG and loads the data rategenerator value in the U1BRG register.The last action performed before turn-ing the UART loose involves enablingthe UART transmitter by setting theUTXEN bit in the U1STA register.The code between the while(1)braces is a simple serial echo mecha-nism. The dsPIC30F2010 UART hasits own 4-byte receive-and-transmitbuffer. When a character enters thereceive buffer, the URXDA bit is set.If there is no transmission in progress,

DataFCY rate =

BRG + 116 × ( )

Listing 1—After I got this little piece of code working, I was on my way to bigger and better things.

main(void)

U1MODE |= 0x8000;U1BRG = (((7372800/9600) /16) - 1);U1STA |= 0x0400;while(1)while(!U1STAbits.URXDA);while(!U1STAbits.TRMT);U1TXREG = U1RXREG;

Listing 2—I really had to dig to get enough information to make this little code snippet work correctly.

main(void)

int x;PTPER = 0x1FFF;PDC1 = 0x1FFF;PTCON = 0x8000;while(1)++x;

WW

W.G

iURUMELE

.Hi2

.RO

Page 55: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 53

the TRMT bit is clear. The code waitsfor a character to enter the receivebuffer, and when all is clear on thetransmit side, it moves the incomingcharacter from the receive buffer intothe transmit buffer for transmission.

The dsPIC30F2010 has an extensivePWM module. The dsPIC30F2010datasheet provides information abouthow to set up the PWM registers, so Iturned to Microchip’s “dsPIC30F FamilyReference Manual” for the scoop onthe bits inside the dsPIC30F2010’s PWMregister set. As you can see in Listing 2,the PWM module is just as easy to setup and use as the UART.

The PWM operation is based on a15-bit up/down counter, or PWM timebase, implemented by the PTMR spe-cial function register. The most signif-icant bit of the PTMR is read-only andindicates the direction of the timebasecount (up or down). Using the PWMtimebase to count up and down allowsfor the generation of center-alignedPWM signals. To set the PWM period,a 15-bit value is written to the PTPERspecial function register. When thecount in the PTMR reaches the countestablished by the PTPER, the PWMtimebase either resets to zero or startscounting in the reverse direction.

In Listing 2, PWM1 is set to runin Free-Running mode. ThedsPIC30F2010’s PWM running in Free-Running mode produces an edge-aligned PWM signal, which means thePTMR value counts up to the PTPERvalue and resets the timebase to zero.The time it takes for the PTMR valueto reach the PTPER value is the periodof the PWM signal. It’s computed asfollows:

where TPWM is the PWM period, and TCY

is the dsPIC30F2010 clock cycle time.TCY in Listing 2 is the reciprocal of

the crystal, or clock frequency, multi-plied by four:

With a value of 0x1FFF (8191 decimal)and a PTMR prescale value of one, thePWM period is 4.44 ms, which resultsin a PWM frequency of 225 Hz.

17.37 MHz

TPTPERPWM =

T PTPER + 1

prescale valueCY × ( )

produce PWM signals, the rest of thecode for the dsPIC30F2010 calls onthe serial routine to receive a PWMperiod or duty cycle value from thePIC18F452 coprocessor, as well assome auxiliary code to apply thereceived data to the appropriate PWMspecial function register. Listing 3 is away of routing the data to the correctspecial function register to implementthe change in the requested PWM sig-nal. As you can see, the ASCII charac-ter P or D, followed by 2 bytes of spe-

The PDC1 special function registerdetermines the duty cycle of thedsPIC30F2010’s PWM1 signal. Thevalue in the PDC1 special functionregister determines how long the PWMsignal will remain high during eachcycle. The value of PDC1 in Listing 2sets a 50% duty cycle. Figure 2 is agraphical interpretation of howPTPER, PTMR, and PDC1 interplay toform a PWM signal.

With some dsPIC30F2010 code tocommunicate with the PIC18F452 and

WW

W.G

iURUMELE

.Hi2

.RO

Page 56: GRAPHICS & VIDEO

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

Fred Eady has more than 20 years ofexperience as a systems engineer. Hehas worked with computers and com-munication systems large and small,simple and complex. His forte isembedded-systems design and com-munications. Fred may be reached [email protected].

SOURCESNICholasEDTP Electronicswww.edtp.com

dsPICDEM 28-pin demo board,dsPIC30F2010, and PIC18F452MicrocontrollerMicrochip Technology, Inc.(480) 792-7200www.microchip.com

ZSR330 Voltage regulatorZetex(+44) 161 622 4444www.zetex.com

54 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

cial function register datareceived from the PIC18F452coprocessor via the asynchro-nous serial link, can be usedto modify the dsPIC30F2010’sPWM output signal.

CODING THE PIC18F452The PIC18F452’s job is to

initialize the AX88796L andperform the interface func-tion between thedsPIC30F2010 and theEthernet link. If thePIC18F452’s code is writtenin a modular fashion, it reallydoesn’t matter how youdecide to encode the messagesthat ultimately will be delivered to thedsPIC30F2010. For instance, Visual Basicallows you to put together a quick andnasty UDP engine. The UDP code mod-ule contained within the PIC18F452picks up the UDP data, performs thenecessary data conversions, and passesthe message to the dsPIC30F2010 viathe serial link established between thetwo microcontrollers.

If Visual Basic isn’t your thing, youcan code a Telnet module for thePIC18F452 that essentially does thesame thing as the UDP module. Thebasic idea is to capture the data usingthe AX88796L Ethernet interface,process it, and pass it to the

dsPIC30F2010 via the PIC18F452’s seri-al port. Doing so simply entails gather-ing data from one code module insidethe PIC18F452 and passing it to anoth-er code module that either prepares thedata for output or sends it on its way.

MELDING MODULESThe AX88796L is NE2000-compati-

ble, which means you can reuse (withminor modifications) code written forother NE2000-compatible Ethernetcontrollers such as the RealtekRTL8019AS. Visual Basic, which pro-vides plenty of space when it comesto Internet protocols, is a fast andeasy way to build a useful user inter-

RESOURCESMicrochip Technology, Inc.,“dsPIC30F Family Reference Manual,”DS80169C, 2004.

face. Even though I didn’t doany deep DSP stuff, I’veshown you just how easy itis to get started with thedsPIC using the dsPICDEM28-pin demo board.

I want you to have asmuch fun as I did. So, I bun-dled up all of the dsPICDEMEthernet, Visual Basic, anddsPIC30F2010 code that Iwrote so you can download itfrom the Circuit Cellar ftpsite and use it in a project ofyour own. The dsPIC ismuch like the PICs you’reused to, but some of thenewer features will have you

digging into the datasheets. After youget familiar with the differences,you’ll find that dsPIC stuff isn’t com-plicated, it’s embedded. I

Listing 3—You can build on this to include changing just about any special function register-relateddsPIC30F2010 function.

#define make16(varhigh,varlow) ((varhigh & 0xFF)* 0x100) + (varlow & 0xFF)

switch (recvchar)case P: //Change PWM period

while(!U1STAbits.URXDA);low_byte = U1RXREG;while(!U1STAbits.URXDA);high_byte = U1RXREG;PTPER = make16(high_byte,low_byte);break;

case D: //Change PWM duty cyclewhile(!U1STAbits.URXDA);low_byte = U1RXREG;while(!U1STAbits.URXDA);high_byte = U1RXREG;PDC1 = make16(high_byte,low_byte);break;

default:break;

PTPER

PDC1

PDC2

0

PWM1H

PWM2H

Duty cycle

Period

PTMR value

New duty cycle loaded from PDCX

Figure 2—After all that reading, I see this. Bing!

WW

W.G

iURUMELE

.Hi2

.RO

Page 57: GRAPHICS & VIDEO

Schematic and PCB Layout

• Powerful and flexible schematic capture.• Auto-component placement.• Rip/entry PCB routing.• Polygonal gridless ground planes.• Library of over 8000 schematic and 1000 PCB foot prints.• Bill of materials, DRC reports and more.

Mixed Mode SPICE Circuit Simulation

• Berkeley SPICE3F5 simulator with custom extensions fortrue mixed mode and interactive simulation.

• Six virtual instruments and 14 graph based analysis types.• 6,000 models including TTL, CMOS and PLD digital parts.• Fully compatible with manufacturers’ SPICE models.

Proteus VSM - Co-simulation and debugging forpopular Micro-Controllers

• Supports PIC16 & PIC12, AVR, 8051, HC11 and ARM micro-controllers.

• Co-simulate target firmware with your hardware design.• Includes interactive peripheral models for LED and LCD

displays, switches, keypads, virtual terminal and much,much more.

• Provides source level debugging for popular compilersand assemblers from HiTech PICC, Crownhill, IAR, Keiland others.

R4 www.labcenter-electronics.com

EASY TO USE CAD TOOLS AT FANTASTIC PRICESMicroChip PIC 18

• Supported models of the PIC 18 includes PIC18F242,PIC18F252, PIC18F442, PIC18F452, PIC18F248, PIC18F258,PIC18F448 and PIC18F458.

Basic Stamp BS1 and BS2

• Proteus VSM for BASIC Stamp contains everything youneed to develop and simulate designs based around theBASIC Stamp.

• See examples in downloadable Demo atwww.labcenter-electronics.com

“I finished my first design, schematic and PCB in one day.”“What a great tool! I love it.” DAN GILL

“For the cost of the software compared to the productivity gains,I consider Proteus to be pivotal in the commercial viability

of my company and by far represents the best value for moneyof anything Tempus possesses.” ROB YOUNGS, Tempus Consulting

“PROTEUS stands out as the best all-round program in this review.Other programs reviewed have strengths in the pcb design process,Proteus maintains a constant high level of capability throughout.Whether a schematic, user-friendly interactive routing, config-urable autoplacing, competent autorouteing, or a combinationof the above, PROTEUS handles everything very well.”

Electronic & Wireless World CAD Review Roundup

FREEDOWNLOADABLEDEMO

Save Time. Save Money.Proteus Starter Kit – $199 • Complete Systems from $449

“This is clearly superior in every respect.”

Virtual System Modelling

SYSTEMSINC. Tel: 905•898•0665 [email protected]

WW

W.G

iURUMELE

.Hi2

.RO

Page 58: GRAPHICS & VIDEO

As the design concept evolved, Irealized that I could actually designthe entire UI right on a PCB with thee-field circuitry. There are no unwant-ed or flimsy connections (e.g., a touch-screen flex connector), and the PCBtraces are my electrodes. This keepsthe manufacturing simple and itenhances reliability.

The design uses two e-field sensorsto form an XY grid on both sides of theboard. A custom user interface template(or overlay) is placed on the back of theboard and exposed through the enclo-sure for interaction. When you touchthe overlay, the capacitance changeson various e-field electrode XY pointsunderneath, which are then decipheredby the Nitron. The final result is mySmart-E-Touch, which is a simple, com-pact design that has many possibilities.Now I’ll cover the technical details.

SYSTEM OVERVIEWThe Smart-E-Touch is an intelligent,

touchscreen-based UI design that usesa Nitron microcontroller to controland monitor a pair of e-field sensors.The sensors, in turn, monitor an XYgrid on the PCB for the actual capaci-tive sensing of the touchscreenthrough a custom UI overlay. Afterthe Nitron has translated a touch fromthe e-field sensor data, it then outputsan XY coordinate to its RS-232 serialport. A main system controller, PC,PLC, or microboard then receives thecoordinates and can act upon them.

The unique thing about this touch-screen is that it’s built right on theactual circuit board where the touch-

56 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

User interface (UI) designs are acritical part of a system’s design.Having worked on a variety of UIdesigns, I’ve seen the simplest LCDand keypad overlay combo all the wayup to the extreme of a full-blownWebPAD that harvested more process-ing power than my last desktop PC.The front end of the system is whatyou use to interact with your productor device. For this reason, it must becarefully tailored toward the applica-tion for which the device will be used.If you make it too simple or too com-plex, your device may not get used toits fullest potential.

As technology improves, UIs willevolve. For example, an LCD with atouchscreen bolted on top is a com-mon alternative for custom keypadswitch overlays and LEDs, which cangive your product more pizzazz andflexibility but bring inherent complex-ity and cost. Once again, it comesdown to the level of complexity need-ed to interface with your product, andwhether you can take the inherentcost burden.

E-FIELD FOR UI DESIGNTechnological improvements can

provide the catalyst for new designideas. It was definitely the case when Iwas introduced to the new MotorolaMC33794 e-field sensor. Since then,the sensor has garnered a lot of public-ity. It also has appeared in severalCircuit Cellar articles, so I won’t gointo too much depth about how itworks. Let’s focus on the basics. Youcan connect up to nine electrodes (e.g.,

Smart-E-Touch

wire and PCB trace) to one chip andsense a change in capacitance on eachindividual line. Touching one elec-trode with your finger drasticallyaffects the capacitance measurement,and the chip easily senses it.

At the time of the Motorola FlashInnovation 2003 Design Contest, Iknew that hooking up an e-field sen-sor to a Nitron microcontroller wouldresult in a really cool project, especial-ly if it had something to do with sens-ing human touch. So, how does all ofthis tie into UI design? Well, given mylove (or lack thereof) for UI designs, Ithought it would be interesting todesign a simple, low-cost UI based one-field technology. I decided that thedesign’s main focus would be on thesimplicity of interfacing and placinglow burden on the system controllermonitoring the UI.

FEATURE ARTICLE by Bruce M. Pride

Bruce’s Smart-E-Touch is an intelligent, touchscreen-based UI design in which a68HC908QY4 microcontroller controls a pair of Motorola e-field sensors. This inexpen-sive system is the perfect alternative to the pricier touchscreen UIs on the market.

Photo 1—The Smart-E-Touch design is entirely inte-grated on the PCB, so you can easily bolt it into anenclosure. Use custom PCB form factors to accommo-date the enclosure for a perfect fit.

An Intelligent User Interface

WW

W.G

iURUMELE

.Hi2

.RO

Page 59: GRAPHICS & VIDEO

Photo 2b, a 9 × 9 XY electrode grid wascreated on the back of the circuit boardto provide the UI sensing. The grid wasalso brought through to the front of theboard with vias so as to increase theamount of copper for each electrode. Asyou can see in Photo 2c, I shined a lightthrough the board to show you the UIand the XY grid together. This shouldgive you an idea of the UI’s resolution.

Although the grid resolution iscoarse and only provides 81 total sens-ing points, it was just fine for this UIdesign. Most of the buttons on my UIoverlay have at least four XY intersec-tion points on or near them that pro-vide ample sensing capabilities for thebuttons. These 18 PCB trace elec-trodes are then hooked up to the twoMC33794 e-field sensors. Nine elec-trodes go to the X e-field sensor andnine go to the Y e-field sensor.

The e-field sensors require littleexternal circuitry to operate. All youneed is power and a few discrete resis-tors and capacitors (see Figure 2). Byconnecting your microcontroller to thee-field’s 4-bit logic input, you can selectwhich of the nine e-field channels youwant to measure. After a selection is

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 57

made, the electrode voltage is outputon the e-field sensor’s LEVEL pin foreasy reading by an A/D converter.

The e-field sensor provides otherfeatures that I didn’t use for this proj-ect. The internal lamp driver and ISOcommunications interface could provehandy for some designs.

Now that I’ve covered the UI, elec-trodes, and e-field sensors, let’s take alook at the processing power behind thedesign. I used a Nitron 68HC908QY48-bit flash memory microcontroller ina 16-pin TSSOP SMT package.Although a TSSOP is tricky to solder,I needed a small device package giventhe size constraints. The Nitron pro-vides the 100-ms sample interrupt viaits internal timer, the selection inter-face for selecting which electrode tomeasure, and uses its A/D converterto measure the current selected elec-trode. The Nitron then converts theanalog electrode voltage data to acoordinate representing a specific loca-tion on the UI. After X and Y coordi-nates have been put together, it out-puts them to its bit-banged RS-232 portat 19.2 kbps via a MAX232 transceiver.This gives the Smart-E-Touch a fairlyhigh-speed serial port from a low-costmicrocontroller.

The Nitron provides 4 KB of flashmemory and 128 bytes of RAM, whichwas more than enough for the Smart-E-Touch code. The Nitron doesn’trequire an external crystal because ithas a built-in digitally controlledoscillator. I used it for this project andprogrammed it to 10 MHz.

The Nitron is programmed via the16-pin MONO8 port, which allows fora direct connection to a P&EMicrocomputer Systems Cyclone pro-grammer. Reset is provided via the

control circuitry is located. An interest-ing option for this concept is that ratherthan integrating a separate touch-screen assembly into a design, you candesign the touchscreen on the mainsystem controller board. This makesfor a more cost-effective, reliable, andadaptable user interface design.

So, given the Smart-E-Touch’s capa-bilities, how can it be used in systemdevelopment? Depending on the appli-cation, the Smart-E-Touch is a naturalreplacement for touchscreens and cus-tom-made switch overlays. A simple UI,like the one shown in Photo 1, could beused with or without an LCD and pro-vide a great deal of functionality. Nowlet’s look at the various pieces of thedesign so you can see just how simpleand elegant the Smart-E-Touch really is.

SYSTEM BLOCKSTo keep things simple and the cost

down, the Smart-E-Touch is made upof a minimal number of components(see Figure 1). Starting with the userinterface, note that you interface withthe Smart-E-Touch via an overlayplaced on the back of its board. Idesigned a simple UI in Excel, printedit on paper, and then cut it to fit.Although this wasn’t a production solu-tion, it was the simplest way to comeup with a nonconductive overlay with-out breaking the bank. I’m sure thereare many more durable materials outthere that can be placed over an e-fieldelectrode that would allow a change ofcapacitance to occur when touched.

Next, the overlay is placed over theXY electrode matrix (see Photo 2a).Underneath the overlay is the key tothe entire system. As you can see in

Y Electrodes

Motorola MC33794

e-fieldsensor

E-field interface

X Electrodes

STOPGO

Smart-E-Touch

Motorola MC33794e-field sensor

E-fieldinterface

MotorolaNitron

microcontroller

ASCIISerial data

MaximRS-232

transceiver

RS-232 ASCIISerial data

PCBPC or

XY PCBtouch panel

RS-232-enabledmonitoring device

Figure 1—The Nitron microcontroller lies at the heart of the design, controlling the e-field sensors and sendingASCII “touch” data out through the RS-232 transceiver.

Photo 2a—The user overlay on the back of the board forced the requirement of having no circuitry on the back,and it mandated that I use surface-mount components. b—The XY electrodes were designed right on the PCB asrectangular strips of copper. Each electrode is isolated from the others because only one electrode is read at a timeand the others are grounded. c—With the overlay on the back of the board, you can see the XY points by shininglight through the board. There are 81 possible data points, or coordinates, on the board.

a) b) c)W

WW

.GiU

RUMELE.H

i2.R

O

Page 60: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 61: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 59

CodeWarrior IDE for the 68HC08 withProcessor Expert using the C program-ming language.

There are several benefits to usingthis IDE. Because it supports C lan-guage, learning the processor’s nativeassembly language isn’t required. Thissaved time and made developing theSmart-E-Touch easier because I wasable to use various C modules fromprevious projects. The built-inProcessor Expert program saved anenormous amount of time given thatthis point-and-click GUI automatical-ly implemented all of the Nitron’speripheral drivers in C language! Italso provides boot-up code for thechip, which lets you concentrate moreon your application than on manuallysetting up the microcontroller.

LT1117CM-5 voltage regulator, furtherreducing the Smart-E-Touch’s cost!

The PCB, which is a single-sided,mixed-technology (surface-mount andthrough-hole) circuit board, was devel-oped using the ExpressPCB softwarepackage. The board was designed sothat no components are located on theback because the user interface overlaymust be attached to the back of theboard, which then sticks out throughthe enclosure or machine panel open-ing. The board routing is dense, giventhe surface-mount components, but isrequired because of size constraints.

FIRMWARE Before covering the Smart-E-Touch’s

software design, I’ll describe how thesoftware was developed in the

Nitron’s internal power-on-reset circuit.This eliminates the need for an externalreset circuit. The debug LED, which isattached to a Nitron port bit, provedextremely useful during debugging forwatching the scan interrupt occur.

Powering the system is straightfor-ward. You must supply 12 VDC to thepower input connector, which is usedby the e-field sensors and also convert-ed to 5 VDC by the LT1117CM-5 low-dropout voltage regulator. The Nitronand the MAX232 require the 5 VDC.The e-field sensors also convert the12 VDC input to 5 VDC internally,and output it to one of their pins. Iaccounted for this and added a few 0-Ωresistors to the board to provide foraccess to this feature in the future.This eliminates the need for the

Figure 2—As you can see, the circuitry is straightforward. The Nitron has just enough I/O pins to hook to both e-field four-input selects, both e-field analog level pins, theMAX232, and the infamous debug LED!

WW

W.G

iURUMELE

.Hi2

.RO

Page 62: GRAPHICS & VIDEO

60 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

The overall goal of the firmware isto control the e-field sensors, scanthem at a timed interval, translate thesensor data into XY coordinates, andthen send the ASCII XY coordinatedata out the serial port. As you cansee in Figure 3, after the Nitron bootsup and is initialized, the 100-ms peri-odic interrupt timer is enabled, whichthen gives the firmware a timed inter-val, or heartbeat, to perform therequired operations. Inside this heart-beat interrupt, the Nitron scans thetwo XY matrix e-field sensors via itsA/D converter inside every heartbeatinterrupt and figures out the XY coor-dinate of any touch sensed by an X orY electrode (see Listing 1).

A valid touch is defined by anyvalue below the analog-to-digitalMaxTouchLevel threshold, which is110 for this setup. When an electrodeisn’t touched, the 8-bit analog-to-digi-tal value sits at approximately 255, ora high. When a PCB metal electrode isdirectly touched, the value goes downclose to zero. This value is muchhigher, around 100, when touchingthrough the user interface overlay.

When no electrode has been sensedon either the X or Y matrix, the coordi-nate is marked with an asterisk. Thistells the host connected to the Smart-E-Touch serial port that no valid coor-dinate has been sensed. After the scan-ning is done, the Nitron converts thecoordinates to ASCII and sends themout the serial port at 19.2 kbps (e.g.,X3, Y4 or X*,Y7 or X*,Y*). Refer toPhoto 3 for a real data set sample takenfrom HyperTerminal. This entireprocess happens every 100 ms. TheSmart-E-Touch software frameworkallows for plenty of future expansionand features.

SYSTEM TEST AND RESULTSI compiled the code, downloaded it

to the board, and verified the e-fieldsensor’s functionality. Valid X and Ycoordinates were successfully sensedwhen I touched the PCB electrodes.When X or Y electrodes weren’ttouched, the Smart-E-Touch correctlyinterpreted these as “no touches,”which were then assigned an asterisk.

The X and Y coordinates were suc-cessfully sent out of the serial port to

Listing 1—The Nitron C code selects an e-field electrode, reads the analog value of it, and then compares itto the maximum touch threshold. This straightforward code comprises the bulk of the Nitron code, showingjust how easy it is to interface to an e-field sensor.

//Check each E-field sensor electrode, 18 total electrodes**********************************************************************PTB = ELECTRODE_1; //Select e-field electrodeDelay1mS(); //Wait 1 ms after selecting new electrodeReadAdcValue (&Xsensor, &Ysensor); //Read electrode analog valueElectrodeX1 = Xsensor; //Save A to D value of electrode X-1ElectrodeY1 = Ysensor; //Save A to D value of electrode X-1.. //Duplicate code for electrodes 2. //through 8PTB = ELECTRODE_9;Delay1mS(); //Wait 1 ms after selecting new electrodeReadAdcValue (&Xsensor, &Ysensor); //Read electrode analog valueElectrodeX9 = Xsensor; //Save A to D value of electrode Y-9ElectrodeY9 = Ysensor; //Save A to D value of electrode Y-9**********************************************************************//Find the X position********************************************************************** if (ElectrodeX1 < MaxTouchLevel) //Electrode X-1 AtoD value <

//touch max value?Xcoordinate = 1; //Yes, X-coordinate 1 has sensed a touch

else //No, look at next X-coordinate electrodeif (ElectrodeX2 < MaxTouchLevel) //Electrode X-1 AtoD value <

//touch setpoint?Xcoordinate = 2; //Yes, X-coordinate 2 has sensed a touch

. //Duplicate code for Electrodes 3

. //through 8

.else //No, look at next X-coordinate electrodeif (ElectrodeX9 < MaxTouchLevel) //Electrode X-9 AtoD value <

//touch setpoint?Xcoordinate = 9; //Yes, X-coordinate 9 has sensed a touch

else //No valid touch has been sensedXcoordinate = *; //X-coordinate set to none

**********************************************************************// Find the Y position**********************************************************************if (ElectrodeY1 < MaxTouchLevel) //Electrode Y-1 AtoD value

//touch max value?Ycoordinate = 1; //Yes, Y-coordinate 1 has sensed a touch

else //No, look at next Y-coordinate electrodeif (ElectrodeY2 < MaxTouchLevel) //Electrode Y-1 AtoD value <

//touch setpoint?Ycoordinate = 2; //Yes, Y-coordinate 2 has sensed a touch

. //Duplicate code for Electrodes 3

. //through 8

.else //No, look at next Y-coordinate electrodeif (ElectrodeY9 < MaxTouchLevel) //Electrode Y-9 AtoD value <

//touch setpoint?Ycoordinate = 9; //Yes, Y-coordinate 9 has sensed a touch

else // No valid touch has been sensedYcoordinate = *; //Y-coordinate set to none

**********************************************************************//Output X,Y coordinates to host via 19.2-kbps RS-232 port connection.//9 × 9 electrode matrix gives a total of 81 possible points.**********************************************************************DebugPortTxData(X); //Send an X out the serial portDebugPortTxData(Xcoordinate);

//Send the X-coordinate DebugPortTxData(,); //Send a ,DebugPortTxData(Y); //Send a YDebugPortTxData(Ycoordinate);

//Send the Y-coordinate

WW

W.G

iURUMELE

.Hi2

.RO

Page 63: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 61

as the user interface. This wouldallow the Smart-E-Touch to be used asa real system user interface.

Another option is to refine the e-field sensor’s scanning algorithm toachieve better sensitivity. You alsomight need to modify the e-field’sminimum and maximum referencecapacitors to get better sensitivity.

Adding a wireless transmitter to theSmart-E-Touch would remove the needfor a serial port. You’ll find this valuableif you design a remote user interface.

You also could provide more detaileddata out of the serial port. The newdata can be the actual analog-to-digitalreading and the values of the e-field ref-erence capacitors, which are the mini-mum and maximum e-field values.

Finally, consider writing a VisualBasic application (or something equiv-alent) that you can use instead of aterminal emulator. This would makethe user interface more flexible. Theprogram would actually do somethingon the screen when a Smart-E-Touchbutton is pressed.

SMART ALTERNATIVEThe Smart-E-Touch is an intelligent,

touchscreen-based UI design that’s agreat alternative to current UI optionscurrently on the market. In addition

HyperTerminal at 19.2 kbps (seePhoto 3). When you look at the dataset, start at the top of the Hyper-Terminal screen shot. Note that thefirst XY coordinate is X1,Y1. Thiscoordinate is followed by others, fromX2,Y2 all the way down to X9,Y9. I gotthis pattern by placing my finger on thebottom corner of the XY matrix andthen slowly moving it diagonally up tothe top corner of the screen. This iswhy both coordinates incrementtogether. It proves just how well theSmart-E-Touch tracks a moving finger!

You’ll also notice the asteriskmixed in with the Y coordinates. Thishappened when my finger crossedover to the next Y electrode; therewas a point where no electrode wasbeing touched. When this occurs, it’sdetected as a “no touch,” which isexactly how the system should work.This proves that the sampling rate forthe system is sampling more thanenough data points. The Smart-E-Touch concept is now a proven success!

SYSTEM ENHANCEMENTSThe Smart-E-Touch has a lot of

potential. You could change the cir-cuit board form factor to fit nicelyinside an off-the-shelf enclosure simi-lar to Photo 1 with a durable overlay

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

Editor’s note: Bruce’s Smart-E-Touchproject won Grand Prize in the 2003Motorola E-Field Sensor Contest andFirst Prize in the Motorola FlashInnovation 2003 Design Contest.

Bruce M. Pride holds an A.S. and B.S.in electronics and currently works asa Senior Electrical Engineer. He enjoysall aspects of embedded system hard-ware and software design, particular-ly designs with 32-bit microproces-sors, FPGAs, and various microcon-trollers. In his spare time, he enjoysspending time with his family, playingacoustic guitar, competing in CircuitCellar design contests, and consultingvia his side business, Pride EmbeddedLLC. You may reach him [email protected].

Start

Reset and initialization

Enable the 100-ms touchscan interrupt timer

100-ms touchscan timerinterrupt?

Scan X e-field sensor,scan Y e-field sensor

Translate data into XYcoordinates if less than

threshold voltage set point, or else coordinate equal “*”.

Convert XY coordinates to ASCII data

Send data out serial portat 19.2 kbps

N

Y

Figure 3—As you study the system’s firmware flow dia-gram, keep in mind that the code doesn’t execute untila timer interrupt or heartbeat has occurred.

SOURCESPCB Design toolExpressPCBwww.expresspcb.com

LT1117CM-5 RegulatorLinear Technology(408) 432-1900www.linear-tech.com

MC33794 E-field sensor,68HC908QY4 Nitron microcontrollerMotorola, Inc.(847) 576-5000www.motorola.com

Cyclone programmerP&E Microcomputer Systems, Inc.(617) 353-9206www.pemicro.com

Photo 3—Take a look at the HyperTerminal snapshotshowing the XY coordinate data from the serial port. Ifyou notice the incrementing coordinates, you’ll realizethat the data is a result of dragging a finger diagonallyacross one side of the board to the other.

to its reliability, the Smart-E-Touch isinexpensive to build and easy to use.

Given the design’s adaptability, youcan use it in applications to replacemechanical switches, touchscreens,membrane keypads, and entire switchpanels. To my knowledge, there aren’tany touchscreen designs currently onthe market similar to the Smart-E-Touch. This truly proves that theNitron-controlled, e-field sensor-enabledSmart-E-Touch is a unique design. I

WW

W.G

iURUMELE

.Hi2

.RO

Page 64: GRAPHICS & VIDEO

For a 128 × 240 screen with a font sizeof 6, the RAM needed is 40 columns by16 rows, or 640 bytes. The third regionis the user-defined character font. Eachuser-defined character requires 8 bytes.A maximum of 128 characters can bedefined for a total of 1024 bytes.Unless you use custom-defined char-acters, this buffer space is not needed,of course. The sum of the three afore-mentioned values is 6784 bytes,which is less than the 8 KB mountedon the LCD panels.

Initializing the T6963 controllerrequires you to first define the startingRAM locations for each bitmap areabeing used. Thus, if you are usingboth text and graphics, you mustdefine starting addresses in RAM foreach of those areas. Further initializa-tion chores consist of setting up agraphics-size parameter as well as thenumber of text columns on the screen.

Although I mentioned that the textand graphics bitmaps are independent,there can be some interaction betweenthem, if desired. You do this by select-ing various values with the mode setcommand. The different modes areshown in Table 1.

If you use either the XOR or theAND modes, then pixels placed onthe screen by text fonts will interact

62 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

I recently spent a considerable amountof time becoming familiar with Zilog’snew Z8 Encore! family. I was impressedwith several unique features of thechip’s hardware, and the developmentkit that I received worked right out ofthe box, with an extremely short learn-ing curve. I decided to port some of theBASCOM/assembly language peripheraldriver routines, which I routinely usewith Atmel’s AVR family, over to Z8Encore! C libraries. I often use graphicLCDs in my projects, so these driversseemed like a good place to start.

With the proliferation of Palm Pilotsand fancy cell phones, there is certainlyno shortage of small graphic LCD pan-els available, many of them in color.Although quite nice, they tend to besomewhat small and require tiny inter-face connectors. The panels themselvesare often sub-VGA resolution, requiringa relatively complex controller ASIC todrive them and involving strict timingissues that must be carefully addressed.

In the past, considering the above com-plications, I’ve settled on LCD panels thatincorporate at least a low-level controller.I normally choose those incorporating thecommon Toshiba T6963 controller,because it has a good architecture and isfound in reasonably priced LCD panelshaving screen resolutions up to 128 × 240.

In this article I’ll briefly describe thecapabilities of LCD panels containing thiscontroller. I’ll also show you a text/graph-ics library, which I wrote in C language,that gives Z8 Encore! programs access tothe full functionality of the graphic LCDpanels. Photo 1 shows my prototype con-troller along with its LCD panel.

T6963 LCD PANEL The T6963 LCD controller’s most

Graphics LCD Library for the Z8 Encore!Brian has created a graphics library you can use for your future projects. It provides accessfor Encore! programs to graphics LCD panels driven by the T6963 LCD driver chip.

important feature, in my opinion, is thatit implements text and bitmap graphicsfunctions concurrently and independent-ly. Text mode contains a complete ready-to-use, ROM-based character set. (Youdon’t have to download your own bitmapimages for each of the ASCII characters.)Text characters placed on the screenreside on their own bit plane. This meansthey can coexist on the screen with anygraphics images, without any interferencebetween them). To put it another way,you perform separate “text clear screen”and “graphics clear screen” operations toselectively erase text and graphics contentindependently. This greatly simplifiesoperations such as plotting dynamicgraphs with fixed, labeled axes.

The T6963 controller can handle upto 64 KB of static RAM, but the LCDpanels that I’ve used have only 8 KBmounted, which is sufficient for ascreen resolution up to 128 × 240. Youmust partition this RAM memory spaceas needed into three distinct regions.

The first region is the graphics bitplane. When using the 6 × 8 font size,the maximum RAM space needed tohandle a 128 × 240 screen is:

The second region is the text bit plane.

128 240 = 5,120 bytes

×6

FEATURE ARTICLE by Brian Millier

1 0 0 0 CG MD2 MD1 MD0 Mode description

1 0 0 0 X 0 0 0 OR text and graphics pixels1 0 0 0 X 0 0 1 XOR text and graphics pixels1 0 0 0 X 0 1 1 AND text and graphics pixels1 0 0 0 X 1 0 0 Text Attribute mode1 0 0 0 0 X X X Internal ROM character generator1 0 0 0 1 X X X RAM character generator

Table 1—The way in which the text and graphics bit planes interact is defined by three bits in the Mode Set com-mand: MD0–MD2. As well, the choice of the internal character generator ROM, or a RAM-based character genera-tor, is determined by the CG bit.

WW

W.G

iURUMELE

.Hi2

.RO

Page 65: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 63

cellaneous characters consisting ofvowels with various accents and a fewcurrency symbols.

Although it’s possible to replace theentire ROM-based font with user-defined characters, it makes sense formost users to use the ROM-based fontfor the standard ASCII characters andto define only the extra charactersneeded. These get mapped to charac-ters represented by byte values of0x80 and higher.

Each custom character is represent-ed by 8 bytes, 1 byte per row of pixelsin the font, starting at the top. Themost significant bit of the byte repre-sents the leftmost pixel. My utilityapplication also contains a routine toassist in generating the 8 bytes neededto represent any given bit pattern. Itallows you to download this patterninto the T6963 CGRam for testing.

To define a custom character from aZ8 Encore! user program and load itinto the T6963 CGRam area, call theLoadCGRam library routine. This pass-es it the byte value that will subse-quently represent that character (theseuser-defined characters start at 0x80),followed by a pointer to a characterstring containing the 8 bytes needed torepresent the desired pattern. To displaya custom character on the LCD panel,simply place the byte plus 32 into anystring that you send to the display.

Why “plus 32”? It turns out that theT6963 defines all of its ROM-basedcharacters as their normal ASCII valueminus 32. Basically, this removes the32 ASCII control characters normallyresiding in characters 0 through 31.This allows room for those 32 miscel-laneous characters to reside in charac-ter positions 96 through 127. As aresult of this anomaly, the PrintCharroutine in the library must subtract 32from the ASCII values passed to it,before displaying them, if you are to

with graphics pixels located in thesame position. For example, if you useAND mode, only those pixels lit byboth a text operation and a graphicsoperation will show up on the screen. Iwanted completely independent text andgraphics, so I used the OR mode in myinitialization routine. I won’t describeText Attribute mode because it pre-cludes the use of the graphics functionsand instead uses the graphics bit plane toset text attributes on a character-by-character basis. The next operation ininitializing the controller is to issue aDisplay Mode command with thedesired parameters, as shown in Table 2.

Finally, you can set up the shape ofthe text cursor, if you want to use it,by issuing the Cursor Pattern Selectcommand. This command is made upof an upper nibble (1010) and thelower nibble containing a value denot-ing the number of lines needed in thecursor pattern (from one to eight).

All of the required T6963 initializa-tion is performed by the InitScreenlibrary routine. It’s well commented,and you can make changes to thedisplay configuration by changingthe parameters.

In general, all commands sent to theT6963 follow the following format:LSB of parameter, MSB of parameter,and the actual command itself. Thefirst 2 bytes must be sent to theT6963’s data register and the last to itscommand register. The only differencebetween these two operations is in thelevel set on the T6963’s C/*D line.

All such operations are performed bythe C library routines T6963dat andT6963cmd respectively. A third rou-tine, T6963WaitReady, which is calledby both of the aforementioned routines,is needed to monitor the busy status ofthe T6863 (i.e., waiting until it’s readybefore sending data/commands). Anadditional routine, T6963adt, also sendsdata to the T6963’s data register; it han-dles the special case in which largeblocks of data must be sent sequentially,without intervening commands.

Only these four routines and theinit_port routine contain referencesto the actual port pins used on the Z8Encore!. If you were to use differentports, or even a different microcontroller,these routines would be the only ones

associated with the T6963 that you’dneed to modify to match your hardware.The PWM routine that generates thedrive signal for the VEE generator wouldneed to be modified too, but that’s notstrictly a T6963-related routine.

TEXT FUNCTIONSThe library’s text functions are fairly

basic. ClrText() clears all text fromthe LCD screen (without disturbing anygraphics) and locates the character point-er position to row one, column one.Locate (Row,column) places the text

position pointer to the row and columnpassed. These parameters are “1” based(i.e., the “home” position is row one, col-umn one). PrintChar(char) places thecharacter passed to it on the screen atthe current text pointer position.WriteStr(*str) writes an ASCIIZstring on the display, starting at the cur-rent text pointer position. The pointerto that string is passed to this routine.

TEXT FONT CHARACTERSLike many LCD panel controllers,

the T6963 allows you to define yourown character font to supplement its128-character, ROM-based font. TheROM-based font contains the standardASCII 96 characters as well as 32 mis-

Photo 1—I built my unit on a vector board. There’splenty of free space for circuitry beyond what’s neededfor the LCD controller itself. I left Zilog’s smart cablehooked up so you can see how the Z8 Encore! is pro-grammed/debugged.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Description

1 0 0 1 0 0 0 0 Display off1 0 0 1 X X 1 0 Cursor on, no blink1 0 0 1 X X 1 1 Cursor on, blink on1 0 0 1 0 1 X X Text on, graphics off1 0 0 1 1 0 X X Text off, graphics on1 0 0 1 1 1 X X Text on, graphics on

Table 2—Text, graphics, or both bit planes can be enabled by setting the proper bits in the Display Mode com-mand. Also, the cursor can be turned on and off, and the blink attribute set here as well.

WW

W.G

iURUMELE

.Hi2

.RO

Page 66: GRAPHICS & VIDEO

64 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

the display without disturbing the textthat’s being displayed. Pset(X,Y,color)places a dark pixel on the screen at x, yif the color parameter is one; otherwise,it erases that pixel. DrawLine(X0,Y0,X1,Y1,color)draws the line (X0,Y0 ) – (X1,Y1)if color is one; otherwise, it erases thepixels between the two coordinates.DrawRectangle(X0,Y0,X1,Y1,color)draws a rectangle with opposing cornersat (X0,Y0 ,X1,Y1 ) if the color parameter isone; otherwise, it erases such a rectan-gle. DrawCircle(XC,YC,rad)draws acircle centered at (XC, YC ) with aradius of rad.

There are more specialized graphicsroutines. I’ll describe them in the fol-lowing sections.

BITMAP IMAGESWorking with instrumentation in the

Chemistry Department at DalhousieUniversity, I primarily need for agraphics display to show plots of databeing collected. However, I know thatmany people need to be able to displaypictures in the form of bitmap images,so I’ve written routines to handle this.

see what’s expected. However, in thecase of the user-defined characters,you must add 32 to the character youpass the PrintChar routine in order toend up displaying the character withthe code you’ve already predefined witha given character value.

I think Toshiba screwed up by organ-izing things this way. It would havemade more sense to place the miscella-neous accented vowels and currencysymbols in ASCII codes 0 through 31and leave the normal ASCII 96 charac-ters alone with their standard values.

BASIC GRAPHICS FUNCTIONSThe basic graphics functions include

the point, line, and circle drawing rou-tines as well as a screen clear func-tion. My earlier AVR assembly lan-guage T6963 graphics routines usedmy own custom line-drawing algo-rithm, but it seemed more sensiblehere to use Bresenham’s line and circlealgorithms, which are readily availableas C routines.

There are four basic functions.ClrGraph() clears all graphics from

The first thing to consider is whereto store the bitmap images. Zilog’sZ8F6401 contains 64 KB of flash memo-ry, much more than the microcontrollersI’ve used in the past. The assembly lan-guage graphics library, which I had writ-ten for the ’8515 AVR device, takes upless than half of the 8-KB flash memo-ry in that device. However, this graph-ics library, written in C for the Z8Encore!, is approximately 28 KB long.Allowing additional space for a reason-ably sophisticated program meant plac-ing the bitmap images somewhere else.

The obvious choice is to use someform of serial flash memory, becauseit can be connected to the Z8 Encore!using only a few lines. This is impor-tant, given that the T6963 displayinterface already consumes 12 I/Olines. Earlier, I had used Atmel 32-KBSPI flash memory devices for this pur-pose, but this time around I went withMicrochip’s 24LC256 I2C flash memo-ry device (also 32K × 8). Althoughaccessing this I2C memory device isslower than a comparable SPI memorychip, there are advantages. It requiresonly two I/O lines, and you can easilyconnect other I2C peripherals with thesame lines. Additionally, the Z8Encore! C compiler library containsI2C routines, and the 24LC256 is inex-pensive and readily available.

To compensate for the limited spaceavailable in the 24LC256 I2C flashmemory device, as well as its less-than-stellar access speed, I decided touse data compression prior to storingthe bitmap images. Because the dis-play is only monochrome, it’s possibleto achieve a high data compressionratio (from two to 10 times) of theimage using only a simple run-lengthencoding scheme. You can easily store30 full-screen images (on a 128 × 240display) in the 24LC256, and theseimages are painted on the screen in afraction of a second.

The images are stored in the I2Cflash memory by way of a simple fileorganization scheme. A number refer-ences each image, and there is a smalldirectory maintained in the I2C flashmemory that points to the startingaddress of each image, as well as itssize. In addition, this directory con-tains an eight-character name to iden-

WW

W.G

iURUMELE

.Hi2

.RO

Page 67: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 65

rows starting from the bottomand going toward the top of thescreen (i.e., they follow thestandard Cartesian coordinateconvention). The T6963 startsat the top of the LCD paneland works down.

Bitmap images generallyhave a white backgroundwith a black image. Zeros rep-

resent black areas. LCD panels are usu-ally viewed with the background unlitand the image itself lit. A lit pixel isblack (or blue, etc.) and, in terms of theT6963 controller, is represented by aone. Therefore, bitmap pixel data mustbe inverted before being sent to theT6963 controller.

Given the need for the aforemen-tioned data manipulation, as well asthe decision to run-length encode thedata, I wrote a PC utility applicationthat performs the data conversion. Itthen downloads the compressedimage data to the Z8 Encore! via anRS-232 serial data link. A routine inthe Z8 Encore! graphics libraryreceives this serial datastream and

tify that particular I2C flashmemory chip. The bitmapimage file utility program usesit to identify which memorychip is currently being pro-grammed with image data.

How do you generate thesebitmap images in the firstplace? I decided that the easiestmethod was to use standard PCdrawing programs that can outputWindows bitmap (.BMP) files. TheWindows bitmap format contains a sig-nificant amount of information in itsheader, most of which is unnecessary inthis context and can be ignored.However, the parameters that areimportant here are shown in Table 3.

There are a number of differences inthe way in which bitmap files areorganized in comparison to the way inwhich the data must be presented tothe T6963 controller. Bitmap images arestored as groups of 4 bytes (long inte-gers) representing image pixels horizon-tally from left to right. For images thatare not a multiple of 32 pixels horizon-tally, this long integer is zero-padded to

allow for the smaller number of pixelsin the source image.

Depending on the font size selectedin the T6963 controller, you have tobreak up the packets into either 8- or6-bit groups before sending them tothe controller. You also have to padyour own pixel data when the hori-zontal pixel size of the image is not amultiple of either eight or six pixels.

Because of the significant differencesin handling the bitmap image functionfor the 6 × 8 font size mode versus the8 × 8 font size, I chose to implementonly the bitmap function for the 6 × 8font size. I decided this presented themost useful display option.

Bitmap images store the pixels in

Offset Size Type Description of the variable

1 2 Character “BM” to indicate that the file is a bitmap11 4 Long integers Pointer to start of bitmap data19 4 Long integers Width of the image in pixels23 4 Long integers Height of the image in pixels

Table 3—Although most of the header information contained in a Windowsbitmap file is not needed in order to convert it to a file format that the T6963 canuse, the locations of the few necessary parameters are shown in this table.

WW

W.G

iURUMELE

.Hi2

.RO

Page 68: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 69: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 67

library that performs this function. Inoperation, you first fill the ScopeCurrentarray with up to 240 data points. Youthen call the ScopeDraw procedure withthe following parameters: horizontal off-set (in pixels), vertical offset (in pixels),horizontal size (number of data points),vertical clipping size (in pixels), anderase flag (set to one if you want toerase the previously plotted data set).

This routine allows you to present adynamic data plot positioned any-where on the screen with a defined ver-tical and horizontal size. Although thetiming is dependent on the actual databeing plotted, the routine takes lessthan 1 s to plot a full screen. The rou-tine requires 480 bytes of RAM for afull 240-pixel display, but it can bereduced if a narrower display is allthat’s needed (by defining smallerarrays for ScopeCurrent and ScopeLast).

This procedure is fairly straightfor-ward. For each data point (n), the line-draw routine is called using n,Y(n) andn + 1,Y(n + 1) for the endpoints (plushorizontal and vertical offsets speci-fied). If necessary, the Y values areclipped at the vertical clipping sizebefore plotting. If the erase flag is setto one, on a sample-to-sample basis,the line-draw routine is first calledwith a color of zero to erase the oldline (using the data from the previous-ly plotted screen and stored in theScopeLast array). Then, the line-drawroutine is called with a color of one toplot the line segment corresponding tothe new sample. After each new linesegment is plotted, the current sam-ple’s Y value is transferred, in prepara-tion for the next plot, into the corre-sponding index position in theScopeLast array. This provides a dis-play that remains on the screen, with

the erasure of the olddata occurring only inthe small area of thescreen where the data isactively being plotted. Inuse, it is extremelysmooth, like that of anoscilloscope display.

Some of my earlierprojects involving theT6963-based LCD panelused the AT90S8515microcontroller, which

has only 512 bytes of RAM, much lessthan the 4 KB present in the Z8F6401.To achieve this function without eatingup virtually all of the ’8515’s RAM, Iused a more efficient raster-based algo-rithm, which is coded in assembly lan-guage, rather than the sequential lineerase/draw routines that I chose forthis library. However, given thegreater RAM resources and Z8 Encore!execution speed, and wishing to use C,the more straightforward algorithmseemed appropriate.

WIRE IT UPT6963-based LCD panels interface

to their host via an 8-bit, bidirectionaldata bus using the Intel standard *RD,*WR, and CS control signals. This isgenerally implemented using a dual10-pin connection, which allows theuse of standard ribbon-cable and IDCheader connectors.

Although the T6963 LCD controllercan control up to 64 KB of static RAMfor the text and graphics displaybuffers, this memory is not randomlyaccessible by the host, because theinterface does not include an addressbus per se. Instead, there is a singleC/*D line which steers the data fromthe host into either a control registeror a data register. In terms of hard-ware, the eight data lines and a fewcontrol lines are all that the hostmicrocontroller has to actively han-dle. There are a few additional config-uration control lines that I generallychoose to handle with jumpers.

The T6963 controller chip’s bidirec-tional data bus is meant for a micro-processor featuring a full bus for exter-nal memory, peripherals, and so on. Inearlier T6963-based LCD projects, Iused an AT90S8515 microcontroller,

stores it in the I2C flashmemory. Other routinesread/maintain the imagefile directory, which is alsocontained in the I2C flashmemory.

Although the text/graph-ics routines reside in astand-alone library(T6963.c), the sample pro-gram that I’ve includedwith this article containscode in the main section,which interfaces directly with the PCutility program via the COMM port.This allows you to initially downloadbitmap images into the flash memory,as well as a few other useful functions.After the images are stored in the non-volatile flash memory, the PC utilityprogram is no longer needed.StoreBitmap() and DrawBitmap(

image#,Xoffset,Yoffset) are thetwo library routines used for thebitmap functions. The former is specif-ically meant to work in conjunctionwith the PC utility program I wrote.It’s used to initially store compressedbitmap images in the 24LC256 I2Cflash memory device. The routine iscalled from the main section in thesample program after receiving a 0xFEcommand from the serial port (issuedby the PC utility program). TheDrawBitmap(image#,Xoffset,Yoffset) routine draws a bitmap imagespecified by an image number at thespecified screen offset. Don’t call thiswith a nonexistent image number orthe results will be unpredictable!

Photo 2 is a screen shot of the utilityprogram. Note that the program canalso act as an exerciser to test the opera-tion of the various library routines.

OSCILLOSCOPE DISPLAY For my purposes, it’s essential to be

able to quickly plot a set of datapoints on the screen. For data thatchanges quickly, the ideal solution isthe left-to-right painting of data pointson the screen without an interveningfull-screen erasure. (CRT-based oscillo-scopes do this.) Intelligent graphicscontroller assemblies with serial datalinks are available commercially, but Ihave not seen any with this capability.

I included a routine in this graphics

Photo 2—I wrote the PC utility program so you can download bitmap images to the flashmemory.

WW

W.G

iURUMELE

.Hi2

.RO

Page 70: GRAPHICS & VIDEO

68 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

which contains a full bus. I wasn’t ableto get the LCD panel to work properlywith the ’8515 using Bus mode, evenafter calling for the insertion of waitstates. It appears that the T6963’saccess time is too slow to use withmost current microprocessor buses.

In my experience, it seems that thebest way to control the T6963 is witha simple port access. You allocate oneof the microcontroller’s 8-bit ports forthe data lines and connect lines of asecond port up to the T6963’s controllines. The latter lines are toggled upand down in software to read andwrite to the T6963 controller. Thisworks fine, although it takes a bit morecode to implement. Because the T6963controller is a low-speed CMOS device,the time it takes to perform the variousgraphics commands is much greaterthan the time spent doing either port orbus access, so this is moot. Assumingthat the microcontroller port pins thatconnect to the LCD panel’s *RD and*WR lines are not shared by otherdevices, the *CS line on the LCD panelcan be permanently tied low, therebysaving one microcontroller I/O port pin.

The host program must be able tointerrogate the T6963 controller todetermine when it has finished per-forming the last command it received.Note that this is done by reading aT6963 status register and examiningtwo individual busy bits (whichdepend on the type of command opera-tion being performed). It would havebeen nicer if the interface had includ-ed a dedicated ready line that could betied to a host IRQ line, freeing up thehost to perform other tasks while theLCD panel was busy drawing. However,the T6963 is not designed that way.Status checking is handled by theT6963WaitReady library function.

Unlike the AVR microcontrollerchip, which I’ve used with these LCDpanels, the Z8 Encore! runs off a 3.3-Vpower source, whereas T6963-basedLCD panels require a 5-V source. Ianticipated some problems here giventhe different logic levels involved.Actually, things worked out well. TheZ8 Encore! has 5-V tolerant inputs onits port pins, which means that the 5-Vlogic signals that the T6963 outputson its data lines during a read opera-

tion can be handled directly by the Z8Encore!. Checking out the T6963 con-troller’s datasheet, I found that itrequires a minimum of 2.7 V for alogic-high signal and a maximum of0.8 V for a logic low, both of which areprovided by the Z8 Encore! ports.Therefore, the two devices can beinterconnected without any glue logic.

The T6963 controller itself is capa-ble of generating character fonts inwidths of five, six, seven, or eight pixelsvia two font-select lines (FS0 and FS1).However, many LCD panels, includingthe one that I used, tie the FS0 line low,and bring only the FS1 line out to the20-pin I/O header. This limits the fontselection to six or eight pixels wide.

Deciding which font width to use is atrade-off. Regardless of your choice, theactual pattern used to generate the char-acters is the same. The 8 × 8 font justhas more space between the characters,which means it’s not any clearer or wellformed. Therefore, it seems logical touse the 6 × 8 font exclusively because ityields, for example, 40 columns of textrather than 30 on a 128 × 240 display.

I should note that the choice of thetext font size also affects the operationof the graphics part of the display.Briefly, when selecting the 8 × 8 fontsize, the organization of the graphicsbitmap divides the horizontal pixels intobyte-sized groups of eight. However, inthe case of the 6 × 8 font, the horizontalpixels are grouped by six. In practice,this means that if you use the 8 × 8 fontexclusively, the graphics routinescould be streamlined by taking advan-tage of simple shift instructions ratherthan multiply/divide instructions.

For versatility, my graphics library rou-tines handle both font sizes. Thus, theymust use the multiply/divide instruc-tions rather than streamlined routinesusing the shift instructions. However,you must choose one specific font sizefor a given project. Given that, you thenset the font size jumper properly and alsoset the variables Fontsize, LcdRows,and LcdCols accordingly (in statementsfound at the start of the Main procedure).The bitmap image routine, however, isimplemented for the 6 × 8 font size only,as I mentioned earlier.

All graphic LCD panels require anegative voltage (VEE) in addition to

the 5-V logic power supply. Althoughsome models include this VEE supply onthe controller PCB itself, the more com-mon ones, including the one I use, don’t.

The VEE supply must be approxi-mately –7 (for a 64 × 240) to –16 V (fora 128 × 240). Check your panel’sdatasheet for its exact requirements.

The current requirement for thissupply is extremely modest—onlyabout 2 mA. However, this voltagemust be stable and adjustable (using apotentiometer and software) in orderto change the contrast of the display.The voltage needed to provide opti-mum contrast is temperature-depend-ent. In an environment where theLCD panel is exposed to wide temper-ature variations, the controller mustadjust the VEE supply automatically inresponse to temperature changes, orthe display will be hard, if not impos-sible, to read. I didn’t makeallowances for automatic contrastcontrol over wide temperature swings.

I’ve handled the VEE power supply inseveral different ways in past projects.I started by using Maxim’s MAX749digitally adjustable LCD bias supplychip, which works well but is expen-sive. I later designed my own clone ofthis with a Tiny AVR microcontroller(“Build a Graphics LCD Bias Supply,”Circuit Cellar, issue 144, 2002). Forthis project, I retained the analogcharge-pump components of the afore-mentioned circuit, but let the Z8Encore! provide the PWM signal thatthe Tiny AVR microcontroller had pro-vided. This design is beneficial becauseit allows for software control of con-trast, requiring only a single Z8 Encore!I/O pin (a PWM output). In contrast,both the MAX749 and my Tiny AVRdesign required two I/O lines from thehost micrcontroller to control contrast.

In operation, the Z8 Encore! generatesan active-low PWM signal with a periodof 100 µs and a pulse width that variesfrom about 35% to 55% depending onthe 8-bit contrast parameter. This active-low signal drives a 2N3906 PNP transis-tor with its emitter connected to VCC

and forces current to flow through a 100-µH inductor to ground. During the timethat this transistor is shut off, the mag-netic field in the inductor collapses andgenerates a negative potential across C8

WW

W.G

iURUMELE

.Hi2

.RO

Page 71: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 69

(which must be a tantalum capacitor).An 18-V Zener diode connected acrossthis supply limits the maximum voltagedeveloped to a safe value. A 50-kΩ trim-ming potentiometer and an PNP emit-ter-follower provide for the coarse con-trast control. The software adjustmentof the PWM duty-cycle provides finecontrast adjustment.

Depending on your LCD panel’s VEE

voltage and current requirements, youmight have to adjust the PWM’s peri-od and width range by changing someconstants in the firmware itself. Mycode is optimized for the AZ DisplaysAGM2412B 128 × 240 panel, whichrequires about –14 V. The softwareadjustment of contrast is performed bythe VeeGen(period,width) proce-dure in the library.

I used the AGM2412B-NC-BTDLCD panel for this project. It’s a 128 ×240 panel with a CCFL backlight. Forany panel with a CCFL backlight, youneed a high-voltage supply. I’ve seensurplus modules advertised for approx-imately $5, but I used a standard Digi-Key JKL BXA-501/KIT module, whichtakes a 5-V input and produces approx-imately 600 V to fire the cold cathodefluorescent tube used as the backlight.The module is extremely efficient,requiring only a few hundred milliampsof current at 5 V to light the tube.

Figure 1 shows both the CCFL back-light power supply and R7 connected upto pin 9 of JP1 plus a ground on pin 20.R7 is a current-limit resistor for pow-ering an LED backlight like thosefound on some displays. You need onlyone of these two circuits, dependingon the backlight used in your display.

I used a Microchip 24LC256 I2Cflash memory device (U3) to takeadvantage of the Z8 Encore!’s built-inI2C port. This stores bitmap images.

Downloading required bitmap imagesfrom the PC, which is where they aregenerated, is done via an RS-232 serialdata link operating at 19,200 bps. Thelevel-shifting between the Z8 Encore!’s3.3-V and RS-232 levels is done by U2,which is a Maxim MAX232. AlthoughMaxim makes level-shifters specifical-ly designed for 3.3-V logic microcon-trollers, I had only MAX232 deviceson hand. They interfaced well withthe Z8 Encore! without causing any

problems, but I had to power themfrom the 5-V logic supply. Because Iused both 3.3- and 5-V devices in thisproject, I had to use two regulators—a7805 and an LM1086-3.3—to provideregulated power.

I built my circuit on a vector board(see Figure 1). As you can see in Photo 1,there’s plenty of space left for othercircuitry. Just before I finished writingthis article, I found an inexpensive Z8Encore! trainer board from Futurlec,which includes all of the components

in my circuit except the few passivecomponents that make up the LCDVEE generator. If you want to try out agraphics display on a Z8 Encore!, takea look at this option.

UTILITY PROGRAMTo use bitmap images with this proj-

ect, you must generate them on a PCin Windows bitmap format and thenuse the T6963Z8 utility applicationthat I wrote. This program allows youto choose a PC bitmap image, which

WW

W.G

iURUMELE

.Hi2

.RO

Page 72: GRAPHICS & VIDEO

70 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

Brian Millier is an instrumentationengineer in the Chemistry Departmentat Dalhousie University in Halifax,

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

SOURCESAGM2412B-NC-BTD LCD panelAZ Displays, Inc.www.azdisplays.com

JKL BXA-501/KIT ModuleDigi-Key Corp.www.digikey.com

Z8F6401 MicrocontrollerZilog, Inc.www.zilog.com

24LC256 Flash EEPROMMicrochip Technology, Incwww.microchip.com

Z8 Encore! trainer boardFuturlec, Inc. www.futurlec.com

T6963 LCD ControllerToshibawww.semicon.toshiba.co.jp

must be black and white and smallenough to fit the display, and down-load it to the 24LC256 I2C flash mem-ory device.

When using a brand-new 24LC256 I2Cflash memory device, you first must usethe initialize flash memory function.This puts a known signature pattern inthe flash memory and stores a user-selected, eight-character name. It alsozeroes out the entire flash memory chip,which takes approximately 5 min. If youattempt to initialize a flash memorydevice that already has image datastored in it, the program will notify youand give the flash ID name. Then, youwill have the option to abort or proceed,thereby erasing the existing image datastored in the flash memory device.

After this, you can select bitmapimages that you’ve prepared, and thendownload them to the flash memory.After each image is downloaded, awindow indicates the number of thenext free image. The utility programgenerates a map file, which has thesame name as the one you gave theflash memory chip during the initial-ization procedure, and a .MAP exten-sion. This text file contains the PC’s

bitmap file name and image numberassociated with each image stored inflash memory.

The utility program also contains amatrix where you can draw custom-defined characters for downloading tothe T6963’s CGRam. This is onlytemporary, of course, because theywill disappear when the LCD panel’spower is removed. However, the utili-ty program also displays the list of 8bytes needed to produce that customcharacter, and those values can behard-coded into your program for per-manent access to that character.

A NEW OPTIONAlthough I still intend to use the

Atmel AVR chips for most of my proj-ects, I do like many aspects of the Z8Encore! family. Now that I can con-nect it up to a graphics LCD panel, I’llprobably find a place for it in somefuture projects. I hope that you canmake use of the graphics library inyour own projects. I

Figure 1—This is the complete schematic of my LCD panel controller. The RS-232 link is needed only for initially downloading bitmap images, if used.

Canada. He also runs ComputerInterface Consultants. You may reachhim at [email protected].

WW

W.G

iURUMELE

.Hi2

.RO

Page 73: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 74: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 75: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 76: GRAPHICS & VIDEO

74 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

One of my more memorable excur-sions back in my college days was toHerkimer, New York. My buddies and Ihad been traveling for a number of hoursand needed to stretch. Pulling off theroad next to an abandoned railroad tres-tle, one of the guys got excited when hesaw the rock layers exposed in the exca-vated underpass. We spent hours lookingthrough the sedimentary layers for fos-sils until we were asked to leave by thelandowner. I still treasure a trilobite—aworthless ugly hunk of rock from thePaleozoic era (543–248 mya)—some-where amongst my cache of things.

Herkimer is known for its diamonds,not fossils. Yep, you can still prospect forHerkimer diamonds. Seeing dollar signs?Well, hold on, a Herkimer diamond isactually quartz. If you choose your claimwisely, you can still find some sizablehunks of quartz crystals buried in theground (see Photo 1). As you can see,these are considerably more attractivethan what you would see if you poppedthe can off of a microprocessor’s crystal.But, where would we be today if it was-n’t for the crystal? Don’t look now, butsoon the crystal might be just athing of the past.

Linear Technology hasreleased a programmable oscil-lator that covers a frequencyrange of 1 kHz to 68 MHz usingno external components. It isavailable with either an SPI(LTC6903) or an I2C (LTC6904)interface, and needs only a sin-gle supply from 3 to 5.5 V. Theclock output is available as nor-mal and/or inverted output, andit can be externally controlledusing the output enable (OE)

for the feedback loop to stabilize. (Youcan prevent frequency overshoot whenchanging frequencies by always chang-ing the DAC values first.)

SERIAL DATA CONNECTIONThe device powers up using a default

of OCT=0 and DAC=0 (1.039 kHz). Tochange values in the device, write a16-bit data word to its serial interface.The LTC6903 uses SPI, and the LTC6904uses I2C. Both devices are write-onlybecause neither have the circuitry forreturning data. The SPI device requiresonly the data word to be transmitted(maximum 20-MHz clock). The I2C

device, which requires an addi-tional address byte (maximum100-kHz clock), would be slow-er even if the clocks were equal.But, in this case, you can seethat the SPI device is orders ofmagnitude faster to begin with.

The data word comprisesthe 4-bit OCT value, the10-bit DAC value, and the2-bit CFG value. The config-uration value determines thestate of an output enabled bythe OE input pin. Table 2defines the choices. Figure 2

Lose the Crystal

FROM THE BENCH by Jeff Bachiochi

control input. Output selection also canbe controlled via the 2 least significantbits of the 16-bit serial data word,where the upper 14 bits are for fre-quency selection.

Refer to the LTC6903/4 innards inFigure 1, and you can see a master VCO(34 to 68 MHz), which receives its drivefrom a 10-bit DAC. The DAC is part ofthe closed-loop feedback to keep theVCO stable. The VCO and DAC aredesigned to run over a single octave fre-quency range, 1–2x (frequency mini-mum, x, to frequency maximum, 2x).This gives a fine frequency control ofbetter than 0.1% between the minimumand maximum frequency (approximately34 kHz steps between 34 and 68 MHz).The VCO output goes through a pro-grammable divider. The 4-bit octave(OCT) data controls the divider. This isthe coarse frequency control; it doesn’taffect the VCO frequency.

Table 1 shows ranges selected usingthe 4-bit OCT data. Changes in theOCT data provide instantaneous CLKoutput changes, whereas changes inthe DAC data may take up to 100 µs

There are many different silicon oscillators out there, but Jeff thinks the LTC6903 is a stand-out. Read on to learn how he used it with a microcontroller to control a four-digit LED.

Linear’s LTC6903/4 Programmable Oscillator

Photo 1—This exotic Herkimer diamond shows off itscrystalline structure thanks to Mother Nature.

8

+– Master

oscillator

fM0 = 68 MHz × kΩ ISET

V+ – VSET

ISET

+

–A1

VSET

Serial port

1 2 3 4

GND SDI SCK *SEN (LTC6903) ADR (LTC6904)

DAC

V+

7

OE CLK *CLK

Programmabledivider

6 5

OCT

6903 BD

Figure 1—This eight-pin device has circuitry to create a master VCO. The outputcan be divided for a wide range of user-controlled frequencies via an SPI(LTC6903) or I2C (LTC6904) interface.

WW

W.G

iURUMELE

.Hi2

.RO

Page 77: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR®Issue 168 July 2004 75

a good alternative where reduced accura-cy can be tolerated. Besides its smallsize, the digital programmable oscillator(DPO) has other advantages when usedas an input clock for a processor ormicrocontroller. At power-up, it defaultsto its lowest frequency 1.039 kHz. Thisallows a processor to begin executingcode. The processor can reprogram theDPO on the fly, thus speeding up itsexecution for normal operation. Whenthe circuit needs to save energy, it canthrottle back to a comfortable speedto reduce the required circuit current.It can even turn off the oscillator com-pletely, although this is a death sentenceuntil power is recycled.

Frequency error is approximately0.5%, while maximum error over theentire output range at 5 V is approxi-mately ±2.25%. The VCO used in theactual frequency generation has somejitter associated with it, which can con-tribute approximately 0.5% (at mini-mum undivided frequency, 34 MHz) to3% (at maximum undivided frequency,64 MHz). Other lower ranges reduce jit-ter because of averaging inherentin dividing the frequency.

PROJECT TIMEI’m always looking for ways

to create test equipment. TheLTC6903 seemed like it has greatpotential: it is no problem to geta microcontroller to set anydesired output frequency usingthis device. However, without auser interface inputting the

appropriate value for the desiredfrequency, it is next to impossible.Oh sure, you can watch the outputwith a oscilloscope and haveUp/Down buttons incrementthrough the 214 codes, if you canwait all day. So, to make the circuitportable, a user-friendly interface isimportant. And, because the devicedoesn’t have infinite resolution,you also need feedback on what fre-quency is actually obtainable.

This project uses a microprocessorto control a four-digit LED usingthree push buttons to set a frequencyvalue. The value is converted to theclosest OCT (4-bit coarse) and DAC(10-bit fine) control values. TheLTC6903 is updated with these, and

the LED is updated with the frequencyproduced using the OCT and DAC val-ues. This value can be different fromthe input values. Figure 3 shows the cir-cuit I used to support the LED, pushbuttons, and LTC6903 DPO.

WHO’S GOT THE BUTTON?I wanted to give you an easy way to

change frequency values without sim-ply incrementing or decrementing the14-bit DPO value with two push but-tons. I added a third button as a modecontrol. I created seven modes:change digit1, digit2, digit3, digit4,decimal point, multiplier, andLTC6903 (Run mode). You can tellwhich mode you are in via a flashingdisplay. Depending on the mode, theUp and Down buttons will incrementand decrement a digit, move the deci-mal point (around to one of the fourdigits), or change the multiplier (alter-nate between megahertz and kilo-hertz, one of the two colon dots).

In LTC6903 mode, the display val-ues are read and a frequency value is

defines the bit placement of theOCT, DAC, and CFG values.

SPI communication begins whenthe device is enabled (*SEN). TheLTC6903 is then ready for the mostsignificant bit of the 16-bit dataword. Data bits are clocked intothe device on the rising edge of theclock line. After the first 8 bits ofdata are received, they are trans-ferred into an internal register. Thesecond 8 bits received are trans-ferred internally as well after com-pletion. You can choose to end thetransmission by raising *SEN afteronly 8 bits if the lower 8 bits ofthe DAC and the 2 bits of configu-ration do not change.

I2C communication does notrequire a chip enable (*SEN). TheLTC6904 defines this pin as an addressselection input. Thus, you can have twoI2C devices connected to the I2C bus andcontrol them independently. An I2Ctransmission begins with a start bit.(It’s defined as a lowering of the dataline, SDA, while the clock line, SCL, isin a high state.) Data is considered goodduring the high period of the clock line.A transmission consists of 3 data bytes,the device address, the most significantdata byte, and the least significant databyte. After each of the 8 bits, thedevice responds with an acknowledgebit (ninth bit time) as an assurance thatthe data was received. Failure toacknowledge aborts the transmission.As with the SPI device, the I2C com-munication may end after the most sig-nificant data byte has been sent if thelower 8-bits of the DAC and the 2 bitsof configuration do not change.

REPLACING CRYSTAL We all have been content with using

crystals for a long time. Althoughthey’ve been reduced in size, they stillare susceptible to shock. Resonators are

Minimum frequency (≥≥) Maximum frequency (<<) Octave

34.05 MHz 68.03 MHz 1517.02 MHz 34.01 MHz 148.511 MHz 17.01 MHz 134.256 MHz 8.503 MHz 122.128 MHz 4.252 MHz 111.064 MHz 2.126 MHz 10532 kHz 1063 kHz 9266 kHz 531.4 kHz 8133 kHz 265.7 kHz 766.5 kHz 132.9 kHz 633.25 kHz 66.43 kHz 516.62 kHz 33.22 kHz 48.312 kHz 16.61 kHz 34.156 kHz 8.304 kHz 22.078 kHz 4.152 kHz 11.039 kHz 2.076 kHz 0

Table 1—The frequency resolution is approximately 0.001 × f. Theminimum frequency of an OCT is with the DAC=0x00, and themaximum frequency is with the DAC=0x3FF.

Figure 2—The 16-bit data word value comprises the 4-bit OCTvalue, the 10-bit DAC value, and the 2-bit CFG value. The datais sent most significant bit first. All three values can be changedwith a single transmission.

D15 D14

OCT.3

D13 D12 D11 D10 D9 D8

OCT.2 OCT.1 OCT.0 DAC.9 DAC.8 DAC.7 DAC.6

D7 D6

DAC.5

D5 D4 D3 D2 D1 D0

DAC.4 DAC.3 DAC.2 DAC.1 DAC.0 CFG.1 CFG.0

CFG1 CFG0 CLK *CLK

0 0 On CLK + 180°

0 1 Off On

1 0 On Off

1 1 Powered down

Table 2—The 2-bit configuration value determines howthe outputs CLK and *CLK are treated as well as thepower-saving circuitry.

WW

W.G

iURUMELE

.Hi2

.RO

Page 78: GRAPHICS & VIDEO

76 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

calculated. OCT and DAC values aredetermined and sent to the LTC6903.Finally, the OCT and DAC values areused to calculate a frequency and theLED display is updated with the actu-al frequency produced.

OCT & DACAlthough the LTC6903 uses a 14-bit

value to set a frequency, the OCT andDAC variables differ in function. Thebasic VCO circuit is designed to oper-ate at the 34- to 68-MHz octave. Anoctave, as in music, is a doubling of fre-quency (i.e., the range of the VCO). TheVCO operates within an octave’s rangebased on a 10-bit resistor DAC withinthe loop. A constant current feeds theDAC resistor, creating a voltage used toset the VCO frequency. Think of theDAC as a control that sets a frequencybetween 0.5 and full scale, or 68 MHz.Or, you can think of the 10-bit DACvalue as always adding an offset to theVCO’s lower frequency (34 MHz).

Using the latter line of thought, theoutput frequency is made up of twocomponents: the DAC (offset or finetuning) and the OCT (base frequency

tines—one for multiplication and onefor division—cut down on the codespace required for the math routines.

The code is based on the flow chart inFigure 4. The execution spends most ofits time in the main loop; periodically, it’sin the interrupt routine. There are twointerrupt routines. The first is a CCP1IFinterrupt. The CCP1 module takes inputfrom the LTC6903 and counts edges.When the count matches 50, the CCP1interrupt is generated and the count iscleared. By using this interrupt to togglean output pin, a frequency of one one-hundredth of the LTC6903 is created.

I plan to add a MAX7400 eighth-order,low-pass filter to the circuit using thisoutput as the filter input and theLTC6903 output as a clock into the fil-ter. The filter’s output will be a sinewave equal in frequency to the input.This will give both sine and square waveoutputs of one one-hundredth of theLTC6903’s frequency (10 Hz to 680 kHz).Note that this interrupt is unnecessaryfor this stage of the project.

The second interrupt, which is fromtimer2, is set for approximately 3 ms.The LED display is in the form of four

or coarse tuning):

where

and

The DAC fraction normally would bea number between zero and one. I avoid-ed using the large floating-point routinesby carefully rearranging the equation tokeep the numbers large but less than4,294,967,295, which is the maximumlimit of a 32-bit integer. This keepsrounding errors mostly insignificant.

I started using a number of multipli-cation and division routines (8 × 8, 8 ×16, 16 ×16, 8 × 24, etc.) and rapidly ranout of programming space. So, I decid-ed to use 32-bit math for almost everysituation. Although it was not thefastest execution when I only neededthe product of two 8-bit numbers, speedwas not critical. Having only two rou-

fine setting = coarse setting DAC fraction

or

fine setting

×

= 2 1,039 OCT × ×

DAC1024

coarse setting = 2 1,039OCT ×

f = coarse setting + fine setting

Figure 3—This project uses drive transistors to provide adequate column current for a port to sink a single digit (seven segments and a DP). The frequency displayed is trans-lated into commands to set the appropriate frequency on the LTC6903 output.

WW

W.G

iURUMELE

.Hi2

.RO

Page 79: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 77

multiplexed digits. Each digit plus thecolon has a column drive transistor tosupply approximately 100 mA for eachrow of LED segments. The seven seg-ments plus DP of each digit share theeight rows of the display. A digit’s seg-ment is enabled whenever data placedon a display row is low and its associat-ed column has been enabled by the col-umn-drive transistor. Each time aTMR2IF interrupt occurs, the last LEDcolumn driver is disabled, data for thenext digit is placed on the display rows,and the new digit’s column is enabled.

The five columns get updated every15 ms (5 × 3 ms), which is about 60Hz. Indication of which mode you’re inis handled by the interrupt routine aswell. After you press the Mode button,the mode variable is incremented (0–6).Mode 0 is the Run mode in which the

display does not flash. All of the othermodes flash various parts of the display.

Modes 1 through 4 flash one of the fourdigits. Mode 5 flashes the DP. Mode 6flashes one of the two colon dots (upperequals megahertz, lower equals kilohertz).A variable blink is incremented each timethrough the interrupt. During a columnupdate, the mode is checked. If there isa match, the column is enabled only ifblink is greater than 128. This flashes theproper segments at approximately 1 Hz.

SETTING THE LTC6903When the mode is less or greater than

zero (editing the display), none of thecalculation routines are being executed.This happens only after you have incre-mented through the editing modes (1–6).

After leaving mode 6, you are forcedback into mode 0. As you can see in

Figure 4, a number of callsare made to determinewhich value to send to theLCT6903 based on what youhave set on the LED display(using modes 1 through 6).The microcontroller hassynchronous serial porthardware and can communi-cate with the LTC6903 bysimply placing bytes in theSSPBUF register. (Note thatthis microcontroller also hassupport for I2C, and thiscould be used to talk withan LTC6904.) After theLTC6903 has been updated,additional calculations aremade to determine the actu-al frequency based on theOCT and DAC. This is doneso the display can be updat-ed with new values that arecloser to what is being pro-duced as opposed to whathas been asked for.

MSOP8The LTC6903 is only

available in the SMT ver-sion. Obviously, Linearwants the footprint to beless than that of a crystal soyou can eliminate yourcrystal without changingthe PCB space requirement.I often mount these devices

in a DIP header so I can easily plug theminto a DIP socket (see Photo 2). Afterbending the tiny leads up and down, Iwas able to tack on short lengths ofbare wire wrap wire to each leg usinga regular soldering iron. It takes morepatience than skill to do this. If you getthis far, use a small clip as a heatsinkon each wire as you solder the eightwires to a DIP header. This allows theinitial joint to remain cool.

Many companies have introduced sili-con oscillators, but the LTC6903/4 hasinnovations that make it stand out fromthe crowd. Linear might intend to replacethe crystal in many microprocessor appli-cations, but I think this device will findits way into a number of unusual designs.

Are those little wheels in your headspinning yet? Got any use for a largequartz crystal? I

Initialization

Main

Up buttonpushed?

Down buttonpushed?

Mode buttonpushed?

N

N

N

Y

Y

Y

Increment digit,DP, or multiplier

Decrement digit,DP, or multiplier

Increment mode(0-1-2-3-4-5-6-0)

Go todisplay

Interrupts

Exitinterrupts

CCP1 Countreached?

Timer2overflow?

Toggle DIV100output bit

Turn off last column.Update next column’s row data.

Turn on next column or skip basedon mode (flashing display).

N

N

Y

Y

Display

Mode = 0?

CallDigits2Freq

CallFreq20CTDAC

CallSet6903

CallOCTDAC2Freq

CallFreq2Digits

CallDigits2Display

Go toMain

N

Y

Figure 4—The main loop consists of the UI (buttons) and calculations. Theinterrupt routine displays the frequency using a four-digit LED display.

Photo 2—The LTC6903 is hand-wired to an eight-pinDIP header for easy removal. Three of the four pushbuttons are used as a user interface for editing the dis-play and ultimately the LTC6903.

Jeff Bachiochi (pronounced BAH-key-AH-key) has been writing for CircuitCellar since 1988. His backgroundincludes product design and manu-facturing. He may be reached [email protected].

SOURCES

LTC6903/4 Digital programmableoscillatorLinear Technology Corp.www.linear.com

PIC16F873 MicrocontrollerMicrochip Technology, Inc.www.microchip.com

PROJECT FILESTo download the code, go to ftp.circuitcellar.com/pub/Circuit_Cellar/2004/168.

WW

W.G

iURUMELE

.Hi2

.RO

Page 80: GRAPHICS & VIDEO

tricity and magnetism as discoveredcenturies ago by household names likeOerstad, Ampere, and Faraday.

Keeping things real simple, here aresome electromotive force (EMF) basics.A current passing through a conductorgenerates a magnetic field surround-ing the conductor. That’s what HansOersted (1777-1851) discovered almost200 years ago when he noticed that acompass needle would move underthe influence of the magnetic field sur-rounding a current-carrying wire. Inessence, Oersted’s moving compassneedle was the first electric motor.

Nature tends to balance things out,so the opposite is true, as MichaelFaraday (1791-1867) discovered.

78 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

According to the market statistics,something on the order of 5 billionelectric motors are shipped each year.It’s enough to make your head—and alot of other stuff—spin (see Photo 1).The fact that the number of motorsshipped is roughly equal to the num-ber of MCUs inspires contemplationof an underlying convergence of bothtechnical and societal factors.

As you’ll see, the inexorable marchof MCUs finds our little friends push-ing their way into ever-lower cost andhigher-volume motor control applica-tions. One driving force is a desire toconserve precious energy resources.That’s more than an abstract concernhere in California, where some resi-dents are wondering when the lightswill go out again, and others are wor-rying about the new power plant beingbuilt in their backyard.

Of course, the more that motors dothe heavy lifting, the less we thecouch potato-inclined populace haveto. Whether it’s an escalator, Segway, oreven the power windows in your car,motors make life easier, although somedecry the fact that we seemingly bankthe calories saved on our waistlines.

Whether you’re going green or gettinglazy, motor control is increasingly atopic of interest to engineers across abroad range of fields. Let’s see what’s up.

I’M AMPEDWhen it comes to selecting an electric

motor for a particular application, thereare myriad of choices (see Figure 1).Despite the various bells and whistles,they all rely on basic concepts of elec-

Change the magnetic field around aconductor (i.e., pass a wire near a mag-net), and a current is induced. That’show a transformer works, and it alsoexplains why a motor can be a genera-tor and vice versa.

As enunciated by Andre Ampere(1775-1836), the magnitude of theeffect (i.e., power of a motor) dependson the length of the wire within thatfield and the amount of current pass-ing through the wire. His original defi-nition (although subsequentlyreplaced with a slightly different inter-national standard) defined an ampereas follows: the amount of current intwo straight parallel conductors of infi-nite length a meter apart that gener-ates a magnetic attraction betweenthe conductors with a force of 2 × 10–7

newtons per meter.Another key factor is the orienta-

tion relative to the magnetic field,namely the force (torque) is maximizedwhen the wire is perpendicular to themagnetic field and minimized (zero)when aligned. This is simple enough tosee with a compass by forcing the nee-dle due east or west and releasing it.The needle accelerates quickly (maxi-mum torque) toward north, overshoots(mechanical inertia), and slowly (mini-mum torque) settles back to proper ori-entation. The exact amount of force atany particular point is related to thesine of the angle (i.e., 1 at 90° and 0 at0°). Dust off your old math bookbecause such trig relationships are, asyou’ll see, at the heart of motor control.

Thus, motor control basically boilsdown to the interaction between two

Motoring (Part 1)SILICON UPDATE by Tom Cantrell

Intelligent motor control should be the only kind of motor control you design into your proj-ects. But before you start sketching your next design, take some time to learn about the elec-tric motors at your disposal. Tom covers them all, from brush to brushless.

a)

Photo 1—Motors come in all sizes, from 1000-plus-hpbehemoths (Photo 1a courtesy of www.hampton-power.com/products.html) to tiny MEMS motors builtusing semiconductor manufacturing techniques(Photo 1b courtesy of www.sarcos.com/memsspec_wobble.html).

b)

Motor Basics

WW

W.G

iURUMELE

.Hi2

.RO

Page 81: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 79

magnetic fields, one in the sta-tionary part of the motor (sta-tor) and one the rotating part(rotor). By rotating one of themagnetic fields relative to theother, work is performed as therotor moves in a continual effortto restore magnetic alignment.The analogy that comes to mindis a dog chasing its tail, with abig dish of dog food serving asthe power supply.

With the previous discussionin mind, a few observationsbecome apparent. First, one ofthe magnetic fields can be cre-ated by permanent magnets;but at least one must (and bothcan) be created by electromag-nets in order to allow electrical cir-cuits to generate and control the rotat-ing magnetic field.

Going further, it’s apparent that theperformance characteristics of themotor (speed, torque, smoothness,efficiency, etc.) are vitally dependenton the ability to precisely control therotating magnetic field in the opti-mum manner for the task at hand.But, the task at hand varies greatly(i.e., there’s no single right way whenit comes to choosing or controlling amotor). Some applications are laugh-ably simple, such as a fixed-speed fan.Others, such as the motor in an elec-

tric vehicle, require infinitely variablespeed control. An application such asa conveyor belt that carries differentsize boxes (i.e., varying load) mayrequire constant speed, but variabletorque. Other applications call for justthe opposite—constant torque at vari-able speed (e.g., a stepper motor).

Many applications have start-upissues. Often, more torque is initiallyneeded to overcome the inertia of theload (including the motor and relatedmechanical apparatus itself) than isrequired after steady-state operation isachieved (e.g., disk drive spindlemotor). But sometimes it’s desirable

to limit torque at start-up tominimize mechanical shock(or whiplash for passengers inan elevator).

Another factor to consider isduty cycle, which encompassesa spectrum of time- and load-varying scenarios (see Table 1).It’s just this variability in appli-cations that explains why thereare so many different kinds ofmotors, and why the ability toexploit MCUs for intelligentmotor control is such a big deal.

KEEP IT SIMPLETo find out how we got

where we are, let’s take a brieflook at where we came from by

starting with the brushed DC motor.The common permanent magnet (PM)version relies on magnets mounted onthe stator with coils of wire wrappedaround poles on the rotor.

Operation is conceptually simple: passcurrent through the rotor coils, whichcreates an electromagnet whose fieldinteracts with that of the permanentmagnets, generating torque that causesthe rotor to turn. Conductive brushesrubbing against a rotor-mounted slipring provide the connection betweenthe power supply and the coils.

Great, so now you’ve got a motorthat will turn a bit and then, like a

Electricalmotor

Brushmotor

DC motor Universal motor

Brushlessmotor

Synchronous motor(permanent magnets)

Asynchronous motor(induction)

DC motor

Switchedreluctance motor

Stepper motor

Figure 1—Designers have a number of options when it comes to choosingthe appropriate motor for a particular application.

Duty cycle type Description

Continuous running Operation at constant load of sufficient duration to reach thermal equilibrium.

Short-time duty Operation at constant load during a given time, less than required to reach thermal equilibrium, followed by a rest enabling the machine to reach a temperature similar to that of the coolant (2°K tolerance).

Intermittent periodic duty A sequence of identical duty cycles, each including a period of operation at constant load and a rest (without connection to the mains). For this type of duty, the starting current does not significantly affect the temperature rise.

Intermittent periodic duty A sequence of identical duty cycles, each consisting of a significant period of starting, a period under constant load, and a rest period.

Intermittent periodic duty A sequence of identical cycles, each consisting of a period of starting, a period of operation at constant load, followed by rapid electric with electric braking braking and a rest period.

Continuous operation A sequence of identical duty cycles, each consisting of a period of operation at constant load and a period of operation at no load. There is periodic duty no rest period.

Continuous operation A sequence of identical duty cycles, each consisting of a period of starting, a period of operation at constant load, followed by an electric periodic duty with braking. There is no rest period.electric braking

Continuous operation A sequence of identical duty cycles, each consisting of a period of operation at constant load corresponding to a predetermined speed of periodic duty with related rotation, followed by one or more periods of operation at another constant load corresponding to the different speeds of rotation (e.g., duty). load and speed changes There is no rest period. The period of duty is too short to reach thermal equilibrium.

Duty with nonperiodic Duty in which the load and the speed generally vary nonperiodically within the permissible range. This duty includes frequent overloads load and speed variations that may exceed the full loads.

Table 1—International standards bodies establish motor specifications based on a number of factors, including duty cycle, as defined here by the International ElectrotechnicalCommission (IEC).

WW

W.G

iURUMELE

.Hi2

.RO

Page 82: GRAPHICS & VIDEO

80 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

compass, come to rest. The cleversolution is to split the brush connec-tion and coil wiring so that, just as therotor nears alignment with the perma-nent magnets, the current flow isreversed—a process known as commu-tation. Like our easily entertained dog,just when he’s almost got his tail, itmoves out of reach and round andround he goes.

The PM DC motor is pretty cool.The torque is constant across thespeed range, making for reliable start-ing and smooth operation. A brushedmotor doesn’t need an MCU becausethe control (i.e., pole sequencing) isbuilt into the mechanics of the motoritself. However, the clever mechanicsare also the downside because brushes

have wear-out and maintenanceissues. And don’t forget that sparkstend to fly when the current isreversed at the commutator, whichnot only creates electrical noise but,in fact, can be a showstopper in safety-critical applications (e.g., a fuel pump).

Variations on the DC brush motortheme include those that replace thepermanent magnets on the stator withelectromagnets using either a singlepower supply for both stator and rotor(series wound) or dual supplies (sepa-rately wound). The latter is well suit-ed for high-starting torque applica-tions (e.g., scooters, golf carts, etc.). A“universal” brushed motor is so-named because it’s wired in such away that it will work on either AC or

DC. It isn’t easily reversible, but that’snot a problem for a lot of applications(e.g., fans and kitchen appliances).

BRUSH OFFBecause of its simplicity, and thus

low cost and reliability, the AC induc-tion motor is probably the single mostwidely used type of motor. Alternatingcurrent passing through coils on thestator induces a magnetic field on therotor (either wound or the affection-ately named “squirrel cage”), therebyeliminating the need for brushes andtheir maintenance, electrical noise,and safety issues.

The good news is that a single-phaseAC induction motor is not onlymechanically simpler than a brushed

DC motor, but it’s also conceptuallysimpler. By virtue of the fact that thecurrent is alternating, the power sup-ply itself performs the commutation(i.e., the pole polarity switches alongwith the phase of the supply).

The bad news is that there are a fewpossible gotchas to watch out for. Thebiggest one is that the starting torqueis low. In fact, the motor may notstart at all, but just sit there vibrating.There are a number of jump-startschemes that all generally boil downto mixing and matching three differ-ent add-ons. First is the addition of aseparate start winding that’s designedso that it generates a field at a differ-ent angle than the main winding,thereby giving the motor a directional

bias at power-up. A start capacitor isusually thrown in to boost the currentavailable for starting to many timesthe rated continuous current. Afterthe motor reaches a speed at whichthe main winding torque is sufficient(e.g., 75%), a centrifugal switch cutsthe start winding out of the circuit.Variations include using permanentcapacitors (eliminating the need forthe centrifugal switch) or separatestart and run capacitors.

A so-called shaded pole single-phaseAC induction motor gets rid of thestarting add-ons altogether by shield-ing poles to induce relative lags in themagnetic fields in such a way that themotor starts turning. It’s simple andcheap, but the downside is low start-ing torque and low efficiency. That’sOK for something like a householdfan where the starting torque requiredis low and the motor doesn’t gothrough a lot of start/stop cycles, butthat’s about it.

Stepping up to a multiphase motoraddresses the starting problem direct-ly because the geometry of three sepa-rate coils in a triangle arrangementallows for the establishment of a cleardirectional bias from the get-go. Thisis helpful for applications that needmore starting torque or go through alot of start/stop cycles. Of course, thedownside is the higher cost of boththe motor itself and the control elec-tronics needed to juggle a three-phasepower supply.

Slip is an inherent factor for all ACinduction motors (see Figure 2).Normally, you would expect the speedof the motor simply to be determinedby the frequency of the alternatingcurrent (i.e., rate of rotation of themagnetic field in the stator), butbecause the field in the rotor must beinduced, there’s always some lag. Putanother way, if the rotor catches up tothe rotating magnetic field, there iszero torque. But because the motorhas inherent electrical and mechanicallosses that require some torque toovercome, the rotor can never catchup. As a result, the actual motor speedis slightly (e.g., 5%) less than the basespeed of the rotating magnetic field,and the amount of slip varies with theload changes.

10% 20% 30% 40% 50% 60% 70% 80% 90% 100%Rotor speed (percentage of full speed)

Sample load torque curve

Pull-up torque

Full-voltage start torque

Full-voltage stator current

Pull-out torque7 × FLC

LRC6 × FLC

5 × FLC

4 × FLC

3 × FLCLRT

2 × FLC

1 × FLC

Current (percentage of motor full-load current)

2 × FLT

1 × FLT

Torque (percentage of motor full-load torque)

Figure 2—At start-up, a three-phase AC induction motor draws a huge amount of locked rotor current (LRC) untilthe motor reaches 80% of full speed. At that point both current and torque drop quickly as the motor approaches95% of full speed, where it delivers full load torque (FLT) with high efficiency (i.e., low current).

WW

W.G

iURUMELE

.Hi2

.RO

Page 83: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 81

POWERFULLY CORRECTAny talk about AC and induc-

tive loads has to include discus-sion of power factor correction(PFC). The topic goes beyondmotors (it relates to all AC pow-ered devices), and the effect isfelt mostly by large generators(utilities) and users (e.g., com-mercial and industrial plants).Nevertheless, here goes.

Let’s start with the simpleexample of an AC supply driv-ing a resistive load (e.g., a lightbulb). If you hook up an oscillo-scope, you’d see that the voltageand current remain in phase(i.e., the sine waves are aligned),as you can see in Figure 3. Inthis case, the familiar watts =volts × amps equation holds.Notice that the power consumed(watts) is always positive (i.e., thevoltage and current are always eitherboth positive or both negative).

But if you replace the resistor withan inductor that draws the sameamount of current, look what hap-pens. Now the voltage and current areno longer in phase: the current flowlags by 90°, and there are regions ofboth positive power (positive voltageand current) and negative power (posi-tive voltage and negative current ornegative voltage and positive cur-rent). This seems odd. There is volt-age present and current flowing, butthere is no power!

Put more formally, the power factorof a circuit is defined as the cosine ofthe phase angle (one for perfectlyaligned voltage and current wave-forms, and zero for waveforms 90° outof phase). Because real-world circuitscomprise a mix of resistive and induc-tive loads, the line current is a com-posite of the two. For example, a cir-cuit containing equal resistive andinductive loads would have a phaseangle of 45° and, thus, a power factorof 0.71 (cosine of 45°).

This is more than a numbers game.A lower power factor translates into adirect loss of efficiency (i.e., watts inversus work out), so a motor’s actualwork output is derated, depending onits power factor. It also means generat-ing and distribution facilities must be

upsized to overcome the difference.With the emphasis on energy conser-vation (and the fact that nobody likespaying higher energy bills), it’s nowonder there’s been a big push toimprove power factors with regula-tions (and utility imposed price penal-ties) pushing for at least 0.9 andbeyond. A classic solution is to addcapacitors because capacitance causesa leading (versus an inductor’s lagging)phase angle.

Another often overlooked powerfactor, harmonics, comes into playany time the voltage and currentwaveforms deviate from a pure sinewave. For instance, a square waveapproximation generates many higher-frequency harmonics that cause anincrease in true versus apparent powerconsumption. Harmonics not onlyrepresent an additional power factorloss, but also can damage other equip-ment sharing the same line or eventhe power source itself. The push toimprove power factors includes theexplicit consideration of harmonics(see IEEE, Recommended Practicesand Requirements for HarmonicControl in Electrical Power Systems,519, 1992).

BEST OF BOTH WORLDSWouldn’t it be nice to have a motor

with the performance advantages of abrushed DC motor and the mechani-cal simplicity (no brushes) of an AC

Power

Average0

Average

Power

0

Voltage

Current0

0

Voltage

Current

Figure 3—As shown here, a purely inductive load exhibits apower factor of zero as measured by the sine of the phaseangle between voltage and current. Fortunately, this isn’t thecase for real-world circuits, but so-called wattless power (i.e.,power factor less than one) represents a loss of efficiency thatcalls for a power factor correction (PFC).

WW

W.G

iURUMELE

.Hi2

.RO

Page 84: GRAPHICS & VIDEO

Hot Chips 16 brings together designers and architects of high-performance chips, software, and systems. Presentations focuson up-to-the-minute real developments. This symposium is the primary forum for engineers and researchers to highlighttheir leading-edge designs. Three full days of tutorials and technical sessions will keep you on top of the industry.

Sunda

Sunda

Sunda

Sunda

Sundayyyy y

Aug

ust

22A

ugus

t 22

Aug

ust

22A

ugus

t 22

Aug

ust

22Monda

Monda

Monda

Monda

Mondayyyy y

Aug

ust

23A

ugus

t 23

Aug

ust

23A

ugus

t 23

Aug

ust

23TTTT Tuesd

auesd

auesd

auesd

auesd

ayyyy y

Aug

ust

24A

ugus

t 24

Aug

ust

24A

ugus

t 24

Aug

ust

24A Symposium on High-Performance ChipsAugust 22-24, 2004, Memorial Auditorium,Stanford University, Palo Alto, California

This is a preliminary program; changes may occur. For the most up-to-the-minute details onpresentations and schedules, and for registration information, please visit our web sitehttp://wwwhttp://wwwhttp://wwwhttp://wwwhttp://www.hotchips.org.hotchips.org.hotchips.org.hotchips.org.hotchips.org..... For general information please contact [email protected]@[email protected]@[email protected] also check out HOT Interconnects 12 (another HOT Symposium being held followingHOTChips 16) on their website http://wwwhttp://wwwhttp://wwwhttp://wwwhttp://www.hoti.org.hoti.org.hoti.org.hoti.org.hoti.org.....

SponsorSponsorSponsorSponsorSponsored bed bed bed bed by the y the y the y the y the TTTTTechnical Committee on Micrechnical Committee on Micrechnical Committee on Micrechnical Committee on Micrechnical Committee on Microproproproproprocessors and Microcessors and Microcessors and Microcessors and Microcessors and Microcomputers of the IEEE Computer Societyocomputers of the IEEE Computer Societyocomputers of the IEEE Computer Societyocomputers of the IEEE Computer Societyocomputers of the IEEE Computer Society

HOHOHOHOHOT Chips 16T Chips 16T Chips 16T Chips 16T Chips 16

1111166666ADVANCE PROGRAM

Organizing CommitteeOrganizing CommitteeOrganizing CommitteeOrganizing CommitteeOrganizing CommitteeChairChairChairChairChairBob Lashley SunVice ChairVice ChairVice ChairVice ChairVice ChairPradeep Dubey IntelFinanceFinanceFinanceFinanceFinanceAngela Lee HP

PublicityPublicityPublicityPublicityPublicityDonna WilsonAdvAdvAdvAdvAdvererererertisingtisingtisingtisingtisingStephan Mueller SunPublicationsPublicationsPublicationsPublicationsPublicationsTiziana PerinottiSponsorshipSponsorshipSponsorshipSponsorshipSponsorshipAmr Zaky QualcommRegistrationRegistrationRegistrationRegistrationRegistrationYusuf Abdulghani AppleLocal Local Local Local Local ArArArArArrangementsrangementsrangementsrangementsrangementsAllen J. Baum IntelWWWWWebmasterebmasterebmasterebmasterebmasterRanganathan Sudhakar AMDBill Humphries AppleAt LargeAt LargeAt LargeAt LargeAt LargeLily Jow HPHoward Sachs TelairityGail SachsAlan Jay Smith BerkeleyBob Stewart SRE

Program CommitteeProgram CommitteeProgram CommitteeProgram CommitteeProgram CommitteeProgram Co-ChairsProgram Co-ChairsProgram Co-ChairsProgram Co-ChairsProgram Co-ChairsBill Dally StanfordKeith Diefendorff MemoryLogixProgram CommitteeProgram CommitteeProgram CommitteeProgram CommitteeProgram CommitteeForest Baskett NEAAllen J. Baum IntelPradeep Dubey IntelNorm Jouppi HPChristos Kozyrakis StanfordJohn Nicholls NVIDIATom Petersen MIPSChris Rowen TensilicaMitsuo Saito ToshibaJohn Sell AMDAlan Jay Smith BerkeleyMateo Valero Catalonia

Morning TutorialUltraUltraUltraUltraUltrawideband;wideband;wideband;wideband;wideband; TTTTTechnologechnologechnologechnologechnology and Issuesy and Issuesy and Issuesy and Issuesy and Issues

Afternoon Tutorial J. J. J. J. J. Thomas PaThomas PaThomas PaThomas PaThomas Pawlowlowlowlowlowskiwskiwskiwskiwski MicronMicronMicronMicronMicronPPPPPerferferferferformance Comparison of State-of-the-Arormance Comparison of State-of-the-Arormance Comparison of State-of-the-Arormance Comparison of State-of-the-Arormance Comparison of State-of-the-Art t t t t VVVVVolatile andolatile andolatile andolatile andolatile andNon-VNon-VNon-VNon-VNon-Volatile Memorolatile Memorolatile Memorolatile Memorolatile Memory Dey Dey Dey Dey Devicesvicesvicesvicesvices

Mobile Processing• Bulv• Bulv• Bulv• Bulv• Bulverererererde - de - de - de - de - An An An An An Applications PrApplications PrApplications PrApplications PrApplications Processor focessor focessor focessor focessor for Phone and PDor Phone and PDor Phone and PDor Phone and PDor Phone and PDA A A A A ApplicationsApplicationsApplicationsApplicationsApplications IntelIntelIntelIntelIntel• SC10:• SC10:• SC10:• SC10:• SC10: A A A A A Video PrVideo PrVideo PrVideo PrVideo Processor and Pixocessor and Pixocessor and Pixocessor and Pixocessor and Pixel Shading GPU Fel Shading GPU Fel Shading GPU Fel Shading GPU Fel Shading GPU For Handheld Deor Handheld Deor Handheld Deor Handheld Deor Handheld Devicesvicesvicesvicesvices NVIDIANVIDIANVIDIANVIDIANVIDIA• SH-Mobile3:• SH-Mobile3:• SH-Mobile3:• SH-Mobile3:• SH-Mobile3: Application PrApplication PrApplication PrApplication PrApplication Processor focessor focessor focessor focessor for 3G Cellular Phones on aor 3G Cellular Phones on aor 3G Cellular Phones on aor 3G Cellular Phones on aor 3G Cellular Phones on a Lo Lo Lo Lo Low-Pw-Pw-Pw-Pw-Pooooowwwwwer SoC Design Platfer SoC Design Platfer SoC Design Platfer SoC Design Platfer SoC Design Platformormormormorm HitachiHitachiHitachiHitachiHitachiKeynote Rober Rober Rober Rober Robert Deniset Deniset Deniset Deniset Denise JPLJPLJPLJPLJPL

Mars Exploration RoMars Exploration RoMars Exploration RoMars Exploration RoMars Exploration Rovvvvvers — a ers — a ers — a ers — a ers — a VieVieVieVieView frw frw frw frw from the Insideom the Insideom the Insideom the Insideom the InsideHigh-End Audio and Video• Quar• Quar• Quar• Quar• Quartet:tet:tet:tet:tet: A Pipeline-InterleaA Pipeline-InterleaA Pipeline-InterleaA Pipeline-InterleaA Pipeline-Interleavvvvved Multithred Multithred Multithred Multithred Multithreaded eaded eaded eaded eaded Audio DSPAudio DSPAudio DSPAudio DSPAudio DSP CrCrCrCrCreativeativeativeativeative Labse Labse Labse Labse Labs• CS7050 High P• CS7050 High P• CS7050 High P• CS7050 High P• CS7050 High Perferferferferformance H.264/Aormance H.264/Aormance H.264/Aormance H.264/Aormance H.264/AVC HarVC HarVC HarVC HarVC Hardwardwardwardwardware e e e e Video DecoderVideo DecoderVideo DecoderVideo DecoderVideo Decoder Cor Cor Cor Cor Core fe fe fe fe for Multimedia SOC’or Multimedia SOC’or Multimedia SOC’or Multimedia SOC’or Multimedia SOC’sssss AmphionAmphionAmphionAmphionAmphionWireless Communication• IEEE802.11a Based • IEEE802.11a Based • IEEE802.11a Based • IEEE802.11a Based • IEEE802.11a Based WirWirWirWirWireless eless eless eless eless AAAAAV Module with Digital V Module with Digital V Module with Digital V Module with Digital V Module with Digital AAAAAV InterfaceV InterfaceV InterfaceV InterfaceV Interface TTTTToshibaoshibaoshibaoshibaoshiba• Single Chip CMOS Dir• Single Chip CMOS Dir• Single Chip CMOS Dir• Single Chip CMOS Dir• Single Chip CMOS Direct Conect Conect Conect Conect Convvvvversion ersion ersion ersion ersion TTTTTransceivransceivransceivransceivransceivers fers fers fers fers for or or or or WWWWWWWWWWAN & AN & AN & AN & AN & WLANWLANWLANWLANWLAN SirificSirificSirificSirificSirificMedia and Graphics Processing• • • • • The GeFThe GeFThe GeFThe GeFThe GeForororororce 6800 GPUce 6800 GPUce 6800 GPUce 6800 GPUce 6800 GPU NVIDIANVIDIANVIDIANVIDIANVIDIA• Ne• Ne• Ne• Ne• New Media w Media w Media w Media w Media ArArArArArchitecturchitecturchitecturchitecturchitecture fe fe fe fe for Next Generation or Next Generation or Next Generation or Next Generation or Next Generation Application PrApplication PrApplication PrApplication PrApplication Processorsocessorsocessorsocessorsocessors ARMARMARMARMARM• • • • • The MXP5800 Media PrThe MXP5800 Media PrThe MXP5800 Media PrThe MXP5800 Media PrThe MXP5800 Media Processorocessorocessorocessorocessor IntelIntelIntelIntelIntelEnabling Technology• SimNo• SimNo• SimNo• SimNo• SimNow:w:w:w:w: An ExtrAn ExtrAn ExtrAn ExtrAn Extremelemelemelemelemely Fast & y Fast & y Fast & y Fast & y Fast & Accurate PlatfAccurate PlatfAccurate PlatfAccurate PlatfAccurate Platform & Prorm & Prorm & Prorm & Prorm & Processor Simocessor Simocessor Simocessor Simocessor Simulatorulatorulatorulatorulator AMDAMDAMDAMDAMD• Microchannel Liquid Cooling Solutions• Microchannel Liquid Cooling Solutions• Microchannel Liquid Cooling Solutions• Microchannel Liquid Cooling Solutions• Microchannel Liquid Cooling Solutions CooligCooligCooligCooligCooligyyyyy• • • • • A NeA NeA NeA NeA New System-On-Chip Bus w System-On-Chip Bus w System-On-Chip Bus w System-On-Chip Bus w System-On-Chip Bus ArArArArArch.ch.ch.ch.ch. Optimized f Optimized f Optimized f Optimized f Optimized for 1GHz MIPS Pror 1GHz MIPS Pror 1GHz MIPS Pror 1GHz MIPS Pror 1GHz MIPS Processorsocessorsocessorsocessorsocessors PMC-SierPMC-SierPMC-SierPMC-SierPMC-SierrararararaPanel Moderated b Moderated b Moderated b Moderated b Moderated by Jy Jy Jy Jy John Nickohn Nickohn Nickohn Nickohn Nickollsollsollsollsolls NVIDIANVIDIANVIDIANVIDIANVIDIA

OutsourOutsourOutsourOutsourOutsourcing Engineering Decing Engineering Decing Engineering Decing Engineering Decing Engineering Devvvvvelopment Offshorelopment Offshorelopment Offshorelopment Offshorelopment Offshoreeeee

Potpourri• MDGRAPE-3 chip:MDGRAPE-3 chip:MDGRAPE-3 chip:MDGRAPE-3 chip:MDGRAPE-3 chip: A 165-Gflops A 165-Gflops A 165-Gflops A 165-Gflops A 165-Gflops ASIC fASIC fASIC fASIC fASIC for molecular dynamics simor molecular dynamics simor molecular dynamics simor molecular dynamics simor molecular dynamics simulationsulationsulationsulationsulations GenomicGenomicGenomicGenomicGenomic• • • • • Accelerating Next-Generation Public-kAccelerating Next-Generation Public-kAccelerating Next-Generation Public-kAccelerating Next-Generation Public-kAccelerating Next-Generation Public-keeeeey Cry Cry Cry Cry Cryptograyptograyptograyptograyptographphphphphy ony ony ony ony on General-Purpose CPUs General-Purpose CPUs General-Purpose CPUs General-Purpose CPUs General-Purpose CPUs SunSunSunSunSun• Ho• Ho• Ho• Ho• How SolarFlarw SolarFlarw SolarFlarw SolarFlarw SolarFlare Comme Comme Comme Comme Communications brunications brunications brunications brunications brokokokokoke the 10Gbps on UTP bare the 10Gbps on UTP bare the 10Gbps on UTP bare the 10Gbps on UTP bare the 10Gbps on UTP barrierrierrierrierrier SolarFlarSolarFlarSolarFlarSolarFlarSolarFlareeeeeKeynote Ste Ste Ste Ste Stevvvvve Je Je Je Je Jurururururvvvvvetsonetsonetsonetsonetson DFJDFJDFJDFJDFJ

Nanotech and the FuturNanotech and the FuturNanotech and the FuturNanotech and the FuturNanotech and the Future of Moore of Moore of Moore of Moore of Moore’e’e’e’e’s Las Las Las Las LawwwwwEmbedded Systems• • • • • A Fast PA Fast PA Fast PA Fast PA Fast Pooooowwwwwererererertrain Micrtrain Micrtrain Micrtrain Micrtrain Microcontrocontrocontrocontrocontrollerollerollerolleroller InfineonInfineonInfineonInfineonInfineon• • • • • The Mote ReThe Mote ReThe Mote ReThe Mote ReThe Mote Revvvvvolution:olution:olution:olution:olution: Lo Lo Lo Lo Low Pw Pw Pw Pw Pooooowwwwwer er er er er WirWirWirWirWireless Sensor Netweless Sensor Netweless Sensor Netweless Sensor Netweless Sensor Network Deork Deork Deork Deork Devicesvicesvicesvicesvices UC BerkUC BerkUC BerkUC BerkUC BerkeleeleeleeleeleyyyyyLow-Power Processors• • • • • A 90nm embedA 90nm embedA 90nm embedA 90nm embedA 90nm embedded DRAM single chip LSI with a 3D graded DRAM single chip LSI with a 3D graded DRAM single chip LSI with a 3D graded DRAM single chip LSI with a 3D graded DRAM single chip LSI with a 3D graphics,phics,phics,phics,phics, H.264 codec engine H.264 codec engine H.264 codec engine H.264 codec engine H.264 codec engine,,,,, and a r and a r and a r and a r and a reconfigurable preconfigurable preconfigurable preconfigurable preconfigurable processorocessorocessorocessorocessor SonSonSonSonSonyyyyy• • • • • A LoA LoA LoA LoA Low-Pw-Pw-Pw-Pw-Pooooowwwwwer Opterer Opterer Opterer Opterer Opteron Pron Pron Pron Pron Processorocessorocessorocessorocessor AMDAMDAMDAMDAMDInstruction Set Automation• • • • • The End of ISA Design:The End of ISA Design:The End of ISA Design:The End of ISA Design:The End of ISA Design: P P P P Pooooowwwwwer er er er er TTTTTools fools fools fools fools for Optimal Pror Optimal Pror Optimal Pror Optimal Pror Optimal Processor Generationocessor Generationocessor Generationocessor Generationocessor Generation TTTTTensilicaensilicaensilicaensilicaensilica• Long • Long • Long • Long • Long WWWWWororororords and ds and ds and ds and ds and Wide PWide PWide PWide PWide Porororororts:ts:ts:ts:ts: Rein Rein Rein Rein Reinvvvvventing the Configurable Prenting the Configurable Prenting the Configurable Prenting the Configurable Prenting the Configurable Processorocessorocessorocessorocessor TTTTTensilicaensilicaensilicaensilicaensilica• OptimoDE• OptimoDE• OptimoDE• OptimoDE• OptimoDE ARMARMARMARMARMHigh-End Processors• • • • • The Montecito PrThe Montecito PrThe Montecito PrThe Montecito PrThe Montecito Processorocessorocessorocessorocessor IntelIntelIntelIntelIntel• • • • • A 32-waA 32-waA 32-waA 32-waA 32-way Multithry Multithry Multithry Multithry Multithreaded SPeaded SPeaded SPeaded SPeaded SPARC PrARC PrARC PrARC PrARC Processorocessorocessorocessorocessor SunSunSunSunSun• Intel P• Intel P• Intel P• Intel P• Intel Pentium 4 Prentium 4 Prentium 4 Prentium 4 Prentium 4 Processor on 90nm ocessor on 90nm ocessor on 90nm ocessor on 90nm ocessor on 90nm TTTTTechnologechnologechnologechnologechnologyyyyy IntelIntelIntelIntelIntel

WW

W.G

iURUMELE

.Hi2

.RO

Page 85: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 83

induction motor? Yes, it would, whichis why brushless DC (BLDC) motorsare such hot items, especially underthe hood of the latest-and-greatesthybrid vehicles (see Photo 2).

Conceptually, a BLDC motor is apermanent magnet brushed DC motorturned inside out: the magnets aremounted on the rotor, and the coilsare on the stator. Because the coils nolonger rotate, there’s no need forbrushes to make the power connec-tion (see Figure 4).

Of course, without brushes, anotherway must be found to switch the polepolarity at the proper time. The solu-tion is to determine the rotor’s posi-tion in some way and to control thecoil drive in real time, a processknown as “electronic commutation.”Traditionally, BLDC motors includesensors, such as Hall effect, to deliverrotor position information to themotor controller. More recently, how-ever, sensorless BLDC motors havebecome all the rage.

As the name implies, these motorsdispense with the need for separaterotor position sensors. Instead, theyexploit a phenomenon known as backEMF. As I described earlier, currentpassing through the stator coil gener-ates a field that interacts with therotor’s permanent magnet field tocause the motor to turn. But alsorecall from EMF 101 that a conductorpassing through a magnetic field gen-erates current. So, as the rotor (mag-net) is flying past the coil (conductor),a small amount of EMF is generatedcounter to the EMF that’s causing themotor to turn in the first place.

By monitoring the back EMF, you

can determine the speed and positionof the rotor without needing any extrasensors, wires, or I/O ports. However,the relative magnitude of back EMFcan be small relative to forward EMF,and it also varies with the speed. Thatmakes low-speed back EMF detection(and thus precise control) especiallydifficult. Of course, in general, there’splenty of electrical noise to cutthrough as well. Fortunately, today’sMCUs and motor-control chips areincreasingly up to the task, allowingsensorless BLDC motors to make sig-nificant inroads against both brushedDC and AC induction motors.

Fulfillment of the promise offeredby intelligent MCU-based motor con-trols is found in the switched-reluc-tance (SR) motor, arguably the sim-plest of all. It’s somewhat similar to aBLDC, except the rotor has formedpoles (looks like a gear) and is made of

Rotor magnet N

Hall effect sensors

Accessory shaft

Hall effect sensor magnets

Stator windings

Stator windings

Rotor magnet S

Driving end of the shaft

Figure 4—Brushless DC motors are popular because they combine the performance (e.g., flat torque curve) ofbrushed DC motors with the mechanical simplicity and reliability of an induction motor. In order to perform electron-ic commutation, the motor controller monitors the rotor position using traditional sensors (e.g., Hall effect) and,more recently, sensorless (e.g., back EMF) techniques.

Photo 2—Advanced electric motors and their controlsare sparking the emergence of next-generation hybridgas and electric engines such as this one from Honda.Only 60-mm thick, the 144-V BLDC motor boostshorsepower by 10% and torque by 20% (photo cour-tesy of Green Car Group, www.greencars.com).

WW

W.G

iURUMELE

.Hi2

.RO

Page 86: GRAPHICS & VIDEO

positioning errors (e.g., stalls, externaldisturbances, loss of power, or con-troller errors). Using a stepper motoropen loop (i.e., no external positiondetection) versus a conventional DCmotor with position sensors runningclosed loop remains an interestingchoice for designers.

The fine positioning resolution andsmoothness of rotation can be furtherenhanced with half-stepping, asshown in Figure 5. Instead of fullyactivating a set of coils (as in full-stepping), partial coil activation caus-es the rotor to move to an intermedi-ate position between steps. However,because partial activation reduces theoverall current, the holding torque atthe half-step position is reduced. Tocompensate, a technique known ascurrent profiling increases the currentthrough the active coil so that thetotal current at all (full- and half-step)positions is the same.

Microstepping takes the current-profiling trick further. Instead of justfull- or half-activation, the coils aredriven with much finer granularitycapable of achieving fractional degreeaccuracy with tens or even hundredsof microsteps per full step. Althoughit’s a DC motor, the coil drive wave-

84 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

forms for microstepping startto look like overlapping sinewaves, little different fromthose that drive an AC motor.

CONTROL FREQWhew. I have to confess

that even this brief examina-tion of the various types ofelectric motors went onlonger than expected.Originally, I’d intended tocombine the motor and con-trols discussion in one arti-cle, but as I got into it, I real-ized each topic has more thanenough meat to justify itsown article. This month Italked about iron, copper, andmagnets. Next month I’ll talkabout silicon and software.

Everyone knows motors arehere to stay and new applica-tions continue to emerge.The real story is that even fortraditional applications, the

desire to go green and cut our energybills along with the march of siliconmeans the subject of motor controls isfar from old hat. As they say in poli-tics, the spinning is just beginning! I

a magnetically permeablematerial (something a mag-net will attract, like iron)rather than having it’s own(permanent or induced) mag-netic field.

When opposing pairs ofcoils on the stator are ener-gized, the nearby poles onthe rotor attempt to align. Ifthe number of coils andpoles are equal (or integralmultiple), the rotor moves toa stable position and thenstops. But by using fraction-ally less poles on the rotor(say, six) compared to thenumber of coils (say, eight),a coil/pole pair that’saligned during one phase isslightly out of alignment forthe next phase.

Precise control is requiredto overcome the main chal-lenge posed by SR motors,torque ripple. In essence, themotor wants to move in steps equal to360° divided by the number of coils(e.g., 45° steps for an eight-coilmotor). This can cause vibration,mechanical stress on the bearings,and audible noise.

STEP LIGHTLYSpeaking of steps, let’s finish up this

month with the aptly named steppermotor. It’s kind of like a BLDC onsteroids, one that divides a single rev-olution of the rotor into, for example,200 discrete steps (1.8° per step).Furthermore, as long as the coilsremain energized, the motor willexhibit strong holding torque at eachstep position. Torque is furtherenhanced for bipolar stepper motors inwhich the coils are driven with cur-rent in both directions.

With precise stepping angles andstrong holding torque, the steppingmotor is uniquely well suited for posi-tioning applications. As a practicalmatter, all other motors requireclosed-loop control for anythingapproaching precision positioning. Bycontrast, a stepper motor can be, andusually is, run open loop with perhapsa limit switch or intermittent calibra-tion as the only concession to possible

RESOURCESK. Berringer, “Motor ControlTutorial,” 2000, e-www.motorola.com/files/ microcontrollers/doc/train_ref_material/MOTORTUT.html.

R. Parekh, “AC Induction MotorFundamentals,” Microchip Technology,DS00887A, www.microchip.com/1010/suppdoc/appnote/all/an887/index.htm.

STMicroelectronics, “A Tutorial OnElectrical Motors,” www.st.com/stonline/products/support/motor/tutorial/tutorial.htm.

P. Yedamale, “Brushless DC (BLDC)Motor Fundamentals,” MicrochipTechnology, DS00885A, 2003,www.microchip.com/1010/suppdoc/appnote/all/an885/index.htm.

Tom Cantrell has been working onchip, board, and systems design andmarketing for several years. You mayreach him by e-mail at [email protected].

1 2 3 4

Full-step currenttwo-phase “on”

Phase 1

Phase 2

+I1

–I1

–I2

+I2

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8

Half-step current

Phase 1

Phase 2

+I1

–I1

–I2

+I2

Half-step currentprofiled

Phase 1

Phase 2

+I1

–I1

–I2

+I2

Figure 5—Controlling a stepper motor’s winding currents with finer granularity canboost the positioning resolution to hundreds (half-stepping) and even thousands(micro-stepping) of steps per revolution.

WW

W.G

iURUMELE

.Hi2

.RO

Page 87: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 85

IDEA BOXTHE DIRECTORY OF PRODUCTS AND SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet. ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2″″ ×× 3″″ FORMAT. Call for current rate and deadline information. Send your disk and digital submis-sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail [email protected]. For more information call Sean Donnelly at (860) 872-3064.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/ is your guide to a variety of engineering products and services.

experience xBOBturn serial data into video text

www.decadenet.com

DECADE ENGINEERING503-743-3194 Turner, OR, USA

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

(%!)"#(%**#(%!+,

!* !*)#!*#,!*!-#,!*#(,'#(,.%#

$!&/!*#$!&/"*%

'" $%!+&&)+$ +0#1"&#+(#

+(*

00 2"3

2 2 +&3*"00#

45 02 6 71+

891+ 02 :: .; 0 0 # (#

00 2 002 ::

< <&&"+ :0

'"=*+)+/20

;#12#)"'") <0> #

0><: ??7

: ) := 0 :#

# 0(1$)@+ 9 2:<9

#0 00

04A (BC$100

<: 22 0 333

00 000 4

www.phytec.com

phyCORE®

New GenerationSingle Board Computer

(800) 278-9913PHYTEC America, LLC 203 Parfitt Way SW, G100 Bainbridge Island, WA 98110 USA

WW

W.G

iURUMELE

.Hi2

.RO

Page 88: GRAPHICS & VIDEO

86 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

!"#$%$""&'"&

!"#$%&$

! "#

$ %&'()*

+,-./011/$,-./011/1

'

WW

W.G

iURUMELE

.Hi2

.RO

Page 91: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 89

AT-XTR-903 RF MODULES

www.abacom-tech.com

Tel: (416)236-3858 Fax: (416)236-8866

¶ Multi-Channel Intelligent Wireless Transceiver

¶ 3V operation

¶ 9600 to 38.4Kbps

¶ Virtual Wire Operation

¶ Wafer Thin, Tiny Footprint

¶ Low Current

¶ 433, 868 & 900MHz versions

¶ Standard serial I/O

¶ Programmable TX Power

¶ Programmable Frequency

¶ User Customizable Features

1.5 mm2.5 mm

5.5 mm

Pins 0.6mm x 0.6mm

30.48 mm(1.2 in.)

Introducin

g the

WW

W.G

iURUMELE

.Hi2

.RO

Page 93: GRAPHICS & VIDEO

www.circuitcellar.com CIRCUIT CELLAR® Issue 168 July 2004 91

RING-IT! TELCO SIMULATOR

• Caller-ID• LED display• Audio Output Jack• Real 20Hz Ring• $325 Sale $299.95

Telecom Hardware/Software DevelopersSTOP using your phone lines to test and demonstrateyour telecom devices. Our affordable telephone linesimulators offer authentic USA dial tone, busy signalsand ringing. Supports high speed analog modems too!

PARTY-LINE TELCO SIMULATOR

• Six Extensions• Caller-ID• Distinctive Ringing• CPC Disconnect• $425 Sale $399

134 Windstar CircleFolsom, CA 95630 USA

Tel: 916-985-7219Fax: 916-985-8460

http://www.digitalproductsco.com

WW

W.G

iURUMELE

.Hi2

.RO

Page 94: GRAPHICS & VIDEO

92 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

WW

W.G

iURUMELE

.Hi2

.RO

Page 96: GRAPHICS & VIDEO

Understanding Embedded Security

Closed-Loop Motion Control for Mobile Robots

PICs, DRAMs, and Graphics Displays: Build a Graphics LCD Driver

E-Field Sensor-Based Monitoring System

Ham Radio Repeater Locator

ABOVE THE GROUND PLANE Stepper Drive (Part 1): Analog

APPLIED PCs PSoC 101

FROM THE BENCH Is There a Robot in Your Future?: Emerging Robot Technologies

SILICON UPDATE Motoring (Part 2): Motor Control Chips and Software

94 Issue 168 July 2004 CIRCUIT CELLAR® www.circuitcellar.com

89 Abacom Technologies

89 ActiveWire, Inc.

93 All Electronics Corp.

93 Amazon Electronics

81 AP Circuits

7 Atmel

91 Bagotronix, Inc.

81 Bellin Dynamic Systems, Inc.

39 Belsoft

18 Beta Layout Ltd.

49 Bitscope Designs

14 CadSoft Computer, Inc.

87 Carl’s Electronics

88 CCS-Custom Computer Services

92 Conitec

85 Cyberpak Co.

1 Cypress MicroSystems

65 CWAV

91 DataRescue

85 Decade Engineering

85 Digital Creation Labs Inc.

91 Digital Products

85 DLP Design

25 Earth Computer Technologies

90 EE Tools (Electronic Engineering Tools)

26 EMAC, Inc.

35 Entrelogic Corporation

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.Page

71 ESC Boston

24 ExpressPCB

85 FDI-Future Designs, Inc.

87 Fitzhugh & Waggoner, Inc.

92 Front Panel Express

86 Hagstrom Electronics

21 HI-TECH Software, LLC

82 HOTChips 16 Symposium

48 ICOP Technology, Inc.

89 IMAGEcraft

31 Imagine Tools

86 Intec Automation, Inc

93 Integrated Knowledge Systems

91 Intrepid Control Systems

90 Intronics, Inc.

17 Jameco

64, 86 JK microsystems, Inc.

81 JR Kerr Automation & Engineering

9 Kg Systems, Inc.

83 LabJack Corp.

83 Lakeview Research

89 Lawicel HB

53 Lemos International

2 Link Instruments

69 Linx Technologies

34 MaxStream

88 MCC (Micro Computer Control)

11 Microchip

92 MicroControls

90 Microcontroller Services

95 Micromint

93 Micro Digital

92 microEngineering Labs, Inc.

88 MJS Consulting

90 Mosaic Industries, Inc.

41 Mouser Electronics

66 MVS

86 Mylydia, Inc.

C2 NetBurner

88 OKW Electronics, Inc.

92 Ontrak Control Systems

26 PCBpro

10 PCBexpress

87 PCB Fab Express

C4 Parallax, Inc.

85 Phytec America LLC

87 Phyton, Inc.

90 Picofab, Inc.

93 Pulsar, Inc.

88 Quality Kits & Devices

86 Quantum Composers, Inc.

87 R2 Controls

55 R4 Systems, Inc.

27 Rabbit Semiconductor

Page Page Page

11 Reach Technology, Inc.

25 Remote Processing

58 RoboNexus Conf. & Expo

93 Rogue Robotics Corp.

3 Scott Edwards Electronics, Inc.

88 Sealevel Systems

5 Sierra Proto Express

91 Softools

46 Syspec, Inc.

83 Systronix

89 TareTronics, Inc.

90 TAL Technologies

C3 Tech Tools

72, 73 Technologic Systems

87 Technological Arts

90 Tern, Inc.

86 Trace Systems, Inc.

91 Triangle Research Int’l, Inc.

46 Trilogy Design

47 Velocity Semiconductor

93 Weeder Technologies

91 Zanthic Technologies, Inc.

89 Z-World

September Issue 170Deadlines

Space Close: July 9Material Due Date: July 20

Theme:Signal Processing

Bonus Distribution:Embedded Systems Conference

Boston 2004

Wescon North America

ATTENTION ADVERTISERS

Call Sean Donnelly now toreserve your space!

860.872.3064e-mail: [email protected]

INDEX OF ADVERTISERS

Preview of August Issue 169Theme: Embedded Programming

WW

W.G

iURUMELE

.Hi2

.RO

Page 97: GRAPHICS & VIDEO

115 Timberlachen Circle | Lake Mary, FL 32746 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069

Dozens of Embedded Controllers with Countless Configurations to fit ANY Industry.

Reduce Your Time to Market.

Minimize your time from conception to production by utilizing one of Micromint’s market-provencontrollers. Whether your concerns are digital or analog, inputs or outputs, Micromint has a product to fityour needs. Order quantities of one to thousands. Custom design and configurations are available.

With over 500,000 controllers in the marketplace, Micromint has been providing innovative, turn-keysolutions to the OEM market for 24 years—from design through production, as well as packaging andshipping the final product. Our broad line of embedded controllers and turn-key solutions can turn yourimagination into reality.

Data sheets, Online Ordering and a Complete Catalog of Products at...

Visit our website @ www.micromint.com to see our complete line of OEM Solutions.

EmbeddedSolutions.

www.micromint.com

StartingasLowas$29–single qty

StartingasLowas$39–single qty

StartingasLowas$129–single qty

AsLowas$7–1k qty

Basic Interpreter

(on board)

Assembly or C

Tiny: .85" x 2" sq.

Weather Proof

No Dev. Tools Req.

Controllers

Data Acquisition

ADA, DAC, I/O, RTC,

LCD, Keypad...

Stand Alone

or Networked

Micro Modules

56k down to 2400

baud socket modems

Conexant Comp.

Caller I.D.

Parallel Line

Sensing

RF Modules - Tiny

433 MHz

900 MHz

X10 PLIX Interface

RS232 to RS485

Interface

Communications

Stackable - RTC

Backplane - BCC

Basic Interpreter

Assembly or C

Processor Boards

Expansion Boards

Relay Boards

3.5" x 3.5"

Custom Configurable

ADA, DAC, Opto

Isolated I/O, RTC,

LCD, Keypad...

Controller Boards

Basic Interpreter

On a Chip

No Dev Tools Req.

X10 PLIX Chips

Serial

Parallel

8051 Core

Low Cost

DIP or PLCC

Floating-Point Math

Commercial or

Industrial

Micromint Chips

WW

W.G

iURUMELE

.Hi2

.RO

Page 98: GRAPHICS & VIDEO

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

$," *-

& &%(,./012 "3 "4 564

&,44$72 82/9: ;" 19<//$. <)=

>:0? /9 &, @$ - + &,

A $- A B &,#

$")3 7&,$ )&,

A&,6AA$ -

$ &, &,A3

&@

[email protected]

96

4-,+@

PRIORITY INTERRUPT

WW

W.G

iURUMELE

.Hi2

.RO

Page 99: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO

Page 100: GRAPHICS & VIDEO

WW

W.G

iURUMELE

.Hi2

.RO