V ol. 28 No . 6 NUTS & V OL TS EXER GAME • FIBER OPTICS ...

100

Transcript of V ol. 28 No . 6 NUTS & V OL TS EXER GAME • FIBER OPTICS ...

Vo

l.28 No.6

NU

TS

& V

OLT

SE

XE

RG

AM

E •

FIBE

R O

PT

ICS

•S

ER

IAL P

OR

T •

MO

RE

WE

AT

HE

R S

TAT

ION

Ju

ne 2007

Cover.qxd 5/10/2007 4:08 PM Page 108

CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm

CCCiii rrrcccuuuiiittt SSSpppeeeccciiiaaalll iiissstttsss,,, IIInnnccc... 222222000 SSS... CCCooouuunnntttrrr yyy CCCllluuubbb DDDrrr... ,,, MMMeeesssaaa,,, AAAZZZ 888555222111000888000000--555222888--111444111777 /// 444888000--444666444--222444888555 /// FFFAAAXXX::: 444888000--444666444--555888222444

Visit our website for a complete listing of our offers. We have over 8,000 electronic items on line @ www.CircuitSpecialists.com. PC based data acquisition,industrial computers, loads of test equipment, optics, I.C’s, transistors, diodes, resistors, potentiometers, motion control products, capacitors,miniature observationcameras, panel meters, chemicals for electronics, do it yourself printed circuit supplies for PCB fabrication, educational D.I.Y. kits, cooling fans, heat shrink, cableties & other wire handleing items, hand tools for electronics, breadboards, trainers, programmers & much much more! Some Deals you won’t believe!

Digital SDigital Storage Oscilloscope Moduletorage Oscilloscope Module

PC based Digital Storage Oscilloscope,

200MHz 5GS/s equiv. sampling USB

interface

Convert any PC with USB interface to a highperformance Digital Storage Oscilloscope. Thisis a sophisticated PC basedscope adaptor pro-viding performance compatible to mid/highlevel stand alone products costing much more!Comes with two probes.

Details & SoftwareDetails & SoftwareDownload at Download at WWeb Siteeb Site

>> Test Equipment >> Oscilloscopes/Outstanding Prices

Item# 200DSO200DSO Only$819.00$819.00

Details at Details at WWeb Siteeb Site >> Miniature Cameras(Board,Bullet,Mini’s, B/W, Color)

SONYSONY SuperSuper HAD CCD ColorHAD CCD Color

WWeatherpreatherproof IR Camerasoof IR Cameras

•Day & Night Auto Switch•Signal System: NTSC•Image Sensor:1/3" SONY Super HAD CCD•Horizontal Resolution: 480TV lines•Min. Illumination: 0Lux

SONYSONY SuperSuper HAD CCD B/WHAD CCD B/W

WWeatherpreatherproof IR Cameraoof IR Camera

•Day & Night Auto Switch•Signal System: EIA•Image Sensor: 1/3" SONY Super HAD CCD•Horizontal Resolution: 420TV lines•Min. Illumination: 0Lux

Item# VC-317D:VC-317D:

SONYSONY SuperSuper HADHAD

CCD ColorCCD Color CameraCamera

Item# VC-805:VC-805:

•Weather Proof•Signal System: NTSC•Image Sensor: 1/4" SONY Super HAD CCD•Horizontal Resolution: 420TV lines•Min. Illumination: 1Lux/F1.2

SONYSONY SuperSuper HAD CCD ColorHAD CCD ColorWWeatherpreatherproof IR Cameraoof IR Camera

Item# VC-819D:VC-819D:

•Day & Night Auto Switch•Signal System: NTSC•Image Sensor: 1/4" SONY SuperHAD CCD

•Horizontal Resolution: 420TV lines•Min. Illumination: 0Lux

480480

TV LinesTV Lines

Resolution

Resolution

PricePriceBreakthrough!Breakthrough!

PrProtek 2.0 & 2.9GHz Field Sotek 2.0 & 2.9GHz Field Strtrength ength AnalyzersAnalyzers

>> Test Equipment >> RF Test Equipment

•Frequency Range : 100KHz ~ 2900MHz(2060MHz for 3201N)

•WFM/NFM/AM/SSB modulated signalsmay be measured.

•Sweep Trigger Mode: Free Run, SingleRun, Continuous Wave, Squelch Run

•Sweep Speed: 500 to 2000msec•PLL tuning system for precise frequencymeasurement and tuning

•Built-in Frequency Counter•RS232 interface

Item#’s 3290N & 3201N3290N & 3201N

3290N 3290N

SpecialSpecial$1750.00 (for$1750.00 (for 3290N)3290N)

$1329.00 (for$1329.00 (for 3201N)3201N)Details at Details at WWeb Siteeb Site

SONYSONYSuper HADSuper HAD

CCD™CCD™ equippedcamera’s feature dra-matically improved

light sensitivity

$59.50$59.50 $53.95$53.95$62.50$62.50

SSteppertepper MotorsMotorsPart #: Motor Frame

Size:Holding Torque: Price:

42BYGH404 NEMA 17 3.4kg.cm/47oz.in $17.95

57BYGH207 NEMA 23 8kg.cm/111oz.in $24.95

57BYGH303 NEMA 23 15kg.cm/208oz.in $29.95

57BYGH405 NEMA 23 20kg.cm/277oz.in $34.95

85BYGH350B-03 NEMA 34 48kg.in/665oz.in $79.95

85BYGH350C-03 NEMA 34 63kg.cm/874oz.in $119.95

Part #: Dimensions: MicroStep: Price:

XCW220 100mm x 61mm x 19mm

1(200), 1/2(400), 1/4(800),

1/8(1600)$39.95

CW220 99mm x 65mm x 30mm

1/2(400), 1/8(1600) $49.95

CW230 115mm x 72mm x 32mm

1(200), 1/2(400), 1/4(800),

1/8(1600), 1/16(3200),

1/32(6400), 1/64(12800)

$59.95

CW250 140mm x 94mm x 45mm

1(200), 1/2(400), 1/8(1600) $69.95

CW860 147mm x 97mm x 30mm

1(200), 1/2(400), 1/4(800),

1/8(1600), 1/16(3200),

1/32(6400), 1/64(12800),

128(25600), 1/5(1000),

1/10(2000), 1/25(5000),

1/50(10000), 1/125(25000),

1/250(50000)

$119.95

SSteppertepper MotorMotor ContrControllers ollers 2 Phase Micr2 Phase Microsteppingostepping

SSteppertepper MotorMotor DriverDriver (Bi-polar(Bi-polar & Unipolar& Unipolar Motors)Motors)

$132.00$132.00Item# VC-827D:VC-827D:

NewNew

RevRev. Now. Now

AAvailablevailable

OutdoorOutdoor ColorColor Speed Dome CameraSpeed Dome Camera

•1/4” SONY Exview CCD•768(H) x 494(V) effective pixels•Horizontal Resolution: 480TV lines•Up to 80 preset points•Line scanning•Continuous 360° horizontal rotation•Vertical rotation: 0-100°•RS485 control interface•Min. Illumination: 0.1Lux (color) / 0.001Lux (B&W)

Details at Details at WWeb Siteeb Site

>> Miniature Cameras(Board,Bullet,Mini’s, B/W, Color)

Item# VC-EX861VC-EX861

$899.00$899.00

Shown with optional wall mountShown with optional wall mount

CNC9000 Motion ContrCNC9000 Motion Control Machineol Machine

•Z, X and Y Axis. •Motor Type: Steppers, Nema 23 size motor mounts on allaxes. 277 Oz/in torque.

•Travel: X-22" Y-24" Z-4.5"•Footprint (overall size notincluding motors): 34" x34.75" x 21.75"

•Table top size: 32" x 26" •ABBA Brand Ball screwsand linear rails and truckson all axis

•5mm per turn pitch lead screws.•Direct drive motor coupling on all axis

•Using 3 each CW230 StepperMotor controllers and a300watt power supply at 36 Volts.

•Tested Tolerance on 6061 aluminum plate with .125 carbideendmil (0.001) 2"x2"x.025" Using a Porter Cable router.

•Standard (Feed rate of 50 inch per minute with stepper motors)•Made of 6061 Aluminum except rails, trucks, ball screws and fasteners.Steel and other materials.

Our Custom Designed and Manufactured CNC Machine comescomplete with all Stepper Motors, Controllers and Power Supply.

Features NOT found on the competition!

Item# CNC9000CNC9000

$2995.00$2995.00

Details at Details at WWeb Siteeb Site >> Motion Control >> Linear Motion

HOTHOTNEWNEW

ITEM!ITEM!

CoverInside.qxd 5/9/2007 2:22 PM Page 2

2900 Spafford Street, Davis, CA 95618 Tel 530.757.8400

Check out our new Wi-Fi and ZigBee®

core modules — the latest additions

to our pin-compatible family.

$72 (qty. 100)

RCM4510WZigBee RabbitCore®

$99 (qty. 100)

RCM4400WWi-Fi RabbitCore

Full Page.qxd 5/10/2007 2:18 PM Page 3

COLUMNS

10 TECHKNOWLEDGEY 2007Events, advances, and news from the electronics world.

16 GETTING STARTED WITH PICsC language introduction.

22 Q&ARuss Kincaid offers his ownsolutions to reader questions.

67 IN THE SPOTLIGHTThis month: SchmartBoard.

80 OPEN COMMUNICATIONFiber optics.

84 THE DESIGN CYCLEWorking with peripherals.

Due to technical difficulties, PERSONALROBOTICS will return next month.

Nuts & Volts (ISSN 1528-9885/CDN Pub Agree#40702530) is published monthly for $24.95 per yearby T & L Publications, Inc., 430 Princeland Court, Corona, CA 92879. PERIODICALS POSTAGE PAID ATCORONA, CA AND AT ADDITIONAL MAILING OFFICES. POSTMASTER: Send address changes to Nuts & Volts, P.O. Box 15277, North Hollywood, CA 91615 or Station A, P.O. Box 54,WindsorON N9A 6J5; [email protected]

30 CONTROL YOUR WORLDHome Automation — Part 5: Build a microcontroller-based weather station. By Michael Simpson

38 THE MUX MUX LIGHT DISPLAYSee how to light a displayone segment at a time. By Richard Satterlee

46 PROBING CORESBuild an oscilloscope accessory that displays the B-H curves of inductor cores. By Tom Napier

52 CREATE YOUR OWN SERIAL PORTWith a “bit” of luck, you can create a software serial port for your microcontroller. By G.Y. Xu

60 SONIC REALISMPart 2: Put the sound theoryfrom last month into practice. By Gerard Fonte

68 UNDERSTANDINGDIGITAL BUFFER, GATE, AND LOGIC IC CIRCUITSThis month, learn about NAND gate and OR gate circuits. By Ray Marston

72 CREATING AN EXERGAMEWITH THE HYDRA GAME SYSTEMStart your own dance dancerevolution with the latest offering from Parallax. By Bryan Bergeron

06 DEVELOPING PERSPECTIVES

08 READER FEEDBACK

26 NEW PRODUCTS

44 SHOWCASE

66 ELECTRO-NET

78 NV BOOKSTORE

92 CLASSIFIEDS

94 TECH FORUM

97 ADVERTISERS INDEX

JUNE 2007

4 June 2007

PROJECTS and FEATURES

60

46

38

DEPARTMENTS

TOC - Jun07.qxd 5/10/2007 11:35 AM Page 4

Link InstrumentsPC-Based Test Equipment

• 2 Channel Digital Oscilloscope• 500 MSa/s max single shot rate• 1Mpt sample memory

• Only 9 oz and 7” x 3.5” x 1.5”• Portable and Battery powered• USB 2.0• FFT Spectrum Analyzer

• 32 channels Logic Analyer• up to 32 channels Pattern Generator• up to 400 MSa/s• Variable Threshold• 2 External Clocks• SPI output and disassembly

• I2C output and disassembly

• up to 2Msamples/ch

IO-3208A $750IO-3232A $899IO-3232B $1399

Digital Oscilloscopes

500MSa/s

1Mpts

250 MSa/S (Dual channel) 512 Kpts500 MSa/S (Single channel) 1 Mpts

DSO-8202 (200MSa,128K) $799DSO-8502 (500MSa,1MPt) $950

Logic Analyzer &Pattern GeneratorNEW!

3.2” x 3” x 0.65”

USB 2.0 Powered

Portable

www.Link-instruments.com(973) 808-8990

June 2007 5

Full Page.qxd 5/9/2007 2:32 PM Page 5

6 June 2007

ith the recent rise in global competi-tion for technology and manufacturing

jobs, professional associations, labor organizations, and political groups in theUnited States have begun to emphasize theneed for innovation as a means of retainingand even expanding the domestic workforce. While many universities offercourses on innovation, it’s not an abilitythat can be acquired by passively attendinga lecture, reading a book, or surfing theWeb. Furthermore, innovators aren’t born.They develop their talents through active,directed, hands-on experience.

There is no one correct path to becoming an innovator. However, I’vefound experimenting with electronics,robotics, and microprocessors invaluable in developing the requisite skills, regardless ofthe areas in which innovation is eventually

applied. Designing a QRP transmitter, build-ing a PID controller for a robot drive mech-anism, and creating a smart appliance witha BASIC Stamp all involve creative problemsolving, adherence to the scientific method,as well as time and resource management.Not only is experimenting with electronicsan enjoyable avocation, but the fundamen-tals learned at the workbench can provideyou with the foundation for innovation atwork, school, and in your other pursuits.

Consider, for example, that there’s noescaping the scientific method in theprocess of correctly diagnosing a circuit.Working systematically, you make ahypothesis about the functionality of acomponent, run tests to prove or disprovethe hypothesis, and then, if necessary,move on to the next component or circuit.Like every good scientist or researcher,

you make notes about the process andyour findings so that you’ll be better ableto recognize and address similar problemsin the future. With experience, you’llbecome more proficient at diagnosis, andthe process will become intuitive —integrated in your subconscious thinking.

By mastering experimental funda-mentals, you’ll be in a better position toinnovate. In this regard, innovation is acombination of logic and creativity — leftand right brain activities that are normallyat odds with each other. Intentionallyshifting the balance between the logicand creativity will enable you to developnew circuits and devices in a controlledmanner. Although it’s possible to stumbleupon a valuable discovery through ran-dom trial and error, relying on serendipityis at best a frustrating, inefficient, and low-yield alternative to directed innovation.

In the following pages are contribu-tions from innovators spanning the fieldsof amateur radio, robotics, circuit design,microcontrollers, and fundamental electronics. As you read through the arti-cles, you’ll invariably encounter projectsthat either address a problem that you’refacing or that simply peak your interest.Some articles will be more appealing toyou than others, but they all providebuilding blocks upon which you candevelop and practice innovation.

Whether your immediate goal is toexplore the application of an electroniccomponent, build test equipment that youotherwise wouldn’t be able to afford, learnto program a new microcontroller, or pro-vide your family with the added safety andconvenience of a home automation project,you can make the most of the informationprovided by our authors by actively improv-ing on it. Don’t feel locked in to the descrip-tions or applications, but consider improv-ing on the designs by making a calculatedsubstitution here or a modification there sothat the end result better suits your needs.That is, innovate, don’t simply duplicate.

Now, turn to the article that mostinterests you, pick up your keyboard orsoldering iron, and start innovating. NV

USB - XBeeDongle

USB - XBeeDongle

www.newmicros.com Tel:214-339-2204

Wireless serial links are easy now. The

USB to XBee Dongle shown above hosts an XBee Pro 2.4GHz RF transceiver. It allows USB to remote XBee Pro ttl output serial communications at standard baud rates up to 115200 and ranges up to a mile. Dongle $39. Kit with Dongle and 2 XBee Pro modules for $111. Visit/call for details.

DEVELOPINGPERSPECTIVES

WW

by Bryan Bergeron, Editorby Bryan Bergeron, Editor

DevPerspective.qxd 5/10/2007 5:43 PM Page 6

32-bit performance at an 8-bit priceIntroducing the NetBurner Mod5213

Complete Development Package - $99Development Board and Mod5213IDE with project managerC/C++ CompilerGraphical DebuggerReal-Time OSDeployment Tools

Mod5213 - $39Processor Freescale 32-bit MCF5213Speed 66MHz, 62 MIPSFlash Memory 256 KBSRAM 32 KBSize 2.25” x 0.7” 40-pin DIPPeripherals Up to 33 GPIO

8-channel 12-bit Analog to Digital

Serial Interfaces 3 UARTs DMA capable

SPI I2C

CAN 2.0

TimersFour 32-bit timer channels

with DMA capability

Four 16-bit timer channelswith capture/compare/PWM

4-channel 16-bit/8-channel 8-bitPWM generator

Two periodic interrupt timers (PITs)

Special Features Hardware accelerated Multiply,

Accumulate and Divide

4-channel DMA controller

Watchdog TimerElectrical Specs Input Voltage

4 -7 VoltProcessor Operating Current at 3.3V

4mA to 40mAStop mode Current 130uA

Temperature range -40ºC to +85ºC

for embeddedapplications

0.7

2.25”

Full Page.qxd 5/9/2007 2:36 PM Page 7

Published Monthly ByTT && LL PPuubblliiccaattiioonnss,, IInncc..

430 Princeland Ct.Corona, CA 92879-1300

((995511)) 337711--88449977FAX ((995511)) 337711--33005522

Product Order Line 11--880000--778833--44662244wwwwww..nnuuttssvvoollttss..ccoomm

SubscriptionsInside US 11--887777--552255--22553399

Outside US 11--881188--448877--44554455P.O. Box 15277

North Hollywood, CA 91615

FOUNDER/ASSOCIATE PUBLISHERJack Lemieux

PUBLISHERLarry Lemieux

ppuubblliisshheerr@@nnuuttssvvoollttss..ccoomm

ASSOCIATE PUBLISHER/VP OF SALES/MARKETING

Robin Lemieuxddiissppllaayy@@nnuuttssvvoollttss..ccoomm

EDITORBryan Bergeron

tteecchheeddiitt--nnuuttssvvoollttss@@yyaahhoooo..ccoomm

CONTRIBUTING EDITORSChuck Hellebuyck Marvin MallonJeff Eckert Ray MarstonPeter Best Michael SimpsonRuss Kincaid Gerard FonteTom Napier Rich SatterleeGY Xu Lou Frenzel

CIRCULATION DIRECTORTracy Kerley

ssuubbssccrriibbee@@nnuuttssvvoollttss..ccoomm

SHOW COORDINATORAudrey Lemieux

WEB CONTENT/NV STOREMichael Kaudze

ssaalleess@@nnuuttssvvoollttss..ccoomm

PRODUCTION/GRAPHICSShannon Lemieux

Brad Stoddard

ADMINISTRATIVE ASSISTANTDebbie Stauffacher

Copyright © 2007 by T & L Publications, Inc.All Rights Reserved

All advertising is subject to publisher’s approval. We are notresponsible for mistakes, misprints, or typographical errors.Nuts & Volts Magazine assumes no responsibility for theavailability or condition of advertised items or for the honestyof the advertiser. The publisher makes no claims for the legal-ity of any item advertised in Nuts & Volts. This is the soleresponsibility of the advertiser. Advertisers and their agenciesagree to indemnify and protect the publisher from any and allclaims, action, or expense arising from advertising placed inNuts & Volts. Please send all editorial correspondence, UPS,overnight mail, and artwork to: 443300 PPrriinncceellaanndd CCoouurrtt,, CCoorroonnaa,,CCAA 9922887799.

EVERYTHING FOR ELECTRONICS

LOW DOWN ON THEDOWNLOAD

I would like to build the Digi-Log clockthat was in the Feb ’07 issue. However, thearticle does not tell me how to get thedownloaded source code into the PIC.Please advise.

Norman Hockler

Response: Nuts & Volts, like manymagazines that include software projects,does not list the code in the article for twobasic reasons. The first is space. Some pro-grams would require multiple pages to list.This is not cost-effective for the magazine.The second is speed and accuracy. Down-loading a file is much simpler and more re-liable that re-typing everything by hand. Forthese reasons I provide Nuts & Volts withthe software and they provide it free ofcharge at their website, www.nutsvolts.com. The file in question can be locatedunder the "FTP Index" associated with theissue and article. In this case, look at Feb-ruary 2007 and you'll see the "Clock.asm"file and a short description of the articlewith the title and author. Just click on thefile name and the download will begin.

Once you download the file, you have

to program your PIC device. This requiressignificant software from Microchip, themanufacturer of the PIC microcomputer.The good news is that this sophisticatedsoftware suite is also free from their website at www.microchip.com. Again youwill have to go to their website and locatethe file associated with "MP-LAB."

Note: I provide the source code for allmy projects. This is readable and can be eas-ily changed. However, it needs to be com-piled by the Microchip software before use(a simple command). Some others providethe object code. This does not need to becompiled but it still needs to be loaded intothe Microchip software so that it can becopied into the PIC device. Object code ismuch harder to understand and/or change.

The last thing you will need is a programmer of some sort. This physicallyconnects the PIC device to the MP-LABsoftware and it isn't free. I recommend thePIC-START, but it's a bit pricey now at $199(I think I got mine for about $50 original-ly). It interfaces with their software well andsupports virtually all of their products. Thereare probably hundreds of various otherthird-party "download cables" available thatcan cost under $20. Most of these are fairly limited and not as easy to use. It maybe possible to use one of Microchip's inexpensive development kit s as a

READER FEEDBACK

8 June 2007

ReadFeed Jun07.qxd 5/10/2007 10:33 AM Page 8

download cable. Check with a Microchip sales representative. Thismay seem like a lot of work. And for a single project, it certainly is.But few people use a microcomputer for only one project. Manyusers develop dozens or even hundreds of software ideas. Like anyother endeavor, it takes some up-front investment in time and mon-ey to obtain the capability to use microcomputers. But once you do,there is a whole new world that opens up. I hope this helps.

Gerard Fonte

SEE MORE C8051F120 APPS

I am wondering if Mr. Best will be using the C8051F120 in aseries of articles and what types of applications will be covered.

George Drouant

Response: Thanks for reading Design Cycle!What you saw in the April and May Design Cycle columns will

be taken a bit further one more time in this issue.I will not cover any specific C8051F120 “applications.” How-

ever, I will provide some additional practical coding examples thatare intended to show off the bulk of the C8051F120’s features whileproviding a leg-up to the prospective C8051F120 programmer. Forinstance, I’ll provide code that will demonstrate the use of theC8051F120’s Multiply and Accumulate module, as well as code toimplement interrupt-driven RS-232 communications.

I hope you’ve enjoyed the C8051F120 stuff that has been offered up thus far. Again, thanks for taking time to read Nuts & Voltsand the Design Cycle column.

Peter

CAN INVERTER(S) TAKE THE HEAT?

I enjoyed the article in the Dec ’06 issue about furnace back-up. I plan to do this, but I need an explanation about inverters. I am confusedabout the specs mentioned. There seemsto be quality issues with them. Maybe anarticle about inverters would be helpful.

My particular furnace has a 1/6 HP motor. The plate says seven amps input,115V. (I calculate 805 watts.) I am lookingat a Motor Trend brand sold through theSportman's Guide mail order catalog. It is a3,000 continuous/6,000 peak optimum efficiency 80%. I was thinking of also running a battery charger off of this to keepthe battery charged. Any ideas? Help withthis would be greatly appreciated.

Marc Krol

Response: Thank you for your feed-back! I am always appreciative of anyonewho drops me a nice note about what theyare doing.

Your power calculation is probablyfine; 805 watts (or 805 VA), is near enough

what your furnace requires to run. Actually, 1/6 HP is closer to 500 watts, but sometimes the current draw is based on a peak cal-culation, or perhaps your specification includes associated control

Extreme Robot Speed Control!

OSMC6

6

6

6

Monster power!14-50V3.15 x4.5”x1.5”3 wire interface

160A!”

www.robotpower.comPhone: 253-843-2504 [email protected]

Scorpion HX6

6

6

6

Dual (6A pk) H-bridgesfwd-only channel

5V - 18V1.6“ x 1.6” x 0.5”

2.5A12APlus

$79.99

Scorpion Mini6

6

6

2.5A (6A pk) H-bridge5V - 18V1.25“ x 0.5” x 0.25”

$119.99

Scorpion XL6

6

6

Dual H-bridge5V - 24V2.7“ x 1.6” x 0.5”

13A 45A Peak!

6

6

6

6

6

6

6

14V - 50V - Dual H-bridges - 150Adjustable current limitingTemperature limitingThree R/C inputs - serial optionMany mixing options - Flipped Bot InputRugged extruded Aluminum case4.25" x 3.23" x 1.1”

80A A+ Peak!

$29.99

$399

Introducing Dalf6

6

6

6

6

6

6

Closed-loop control of two motorsFull PID position/velocity loopTrapezoidal path generator

PIC18F6722 CPUC source for routines providedSee

Giant Servo Mode!

www.embeddedelectronics.net

$250

MADE IN

THE USA

H-bridges: Use with Dalf or with your Micro/Stamp

Simple-H6

6

6

6

6-28V 252.25 x2.5 x0.5”3 wire interfacecurrent & temp

protection

A!” ”

$79

Continued on Page 45

READER FEEDBACK

June 2007 9

ReadFeed Jun07.qxd 5/10/2007 10:34 AM Page 9

FUEL CELL POWEREDAIRPLANE TO BEDEMONSTRATED

One of the most ambitious fuel cellprojects out there is the Fuel Cell

Demonstrator Airplane project, whichactually began in 2003 at BoeingResearch and Technology — Europe(BR&TE), a division of the BoeingPhantom Works (www.boeing.com/phantom). The project has now enteredthe demonstration phase. According tothe company, “Given the efficiency andenvironmental benefits of emerging fuelcell technology, Boeing wants to be on the forefront of developing andapplying it to aerospace products.”

The project involves fitting a modi-fied Dimona glider, built by Austria’s Diamond Aircraft Industries (www.diamondair.com), with a Proton ExchangeMembrane (PEM) fuel cell/lithium-ion battery hybrid system. The PEM runs anelectric motor that provides all power forthe cruise phase of flight. (The planedraws from only batteries during takeoffsand landings.) The airplane, with awingspan of 53.5 ft (16.3 m), shouldcruise at about 62 mph (100 km/h). Theflight tests, set to be conducted in Spain,are intended to demonstrate for the first

time that a manned airplane can main-tain a straight level flight with fuel cellsas the only power source. Although

BR&TE does not predict thatfuel cell technology will everbe suitable for large com-mercial airplanes, it could bepractical for small mannedand unmanned air vehicles.

HARVESTINGBACKGROUNDENERGY

One of the challengesin the development

of practical nanoscaledevices has been how to power the things.

Batteries tend to be physically toolarge and, because they contain toxicsubstances, it is not always advisableto implant them in your body. Butnow researchers at Georgia Tech’sSchool of Materials Science andEngineering (www.mse.gatech.edu)have come up with a prototypenanometer-scale generator that canproduce DC current by tapping intomechanical energy from such environ-mental sources as ultrasonic waves,mechanical vibration, and blood flow.

The device is based on an array of

vertically aligned zinc oxide nanowires,located about 0.5 m apart on a substrate of gallium arsenide, sapphire,or flexible polymer. When vibrationsstrike the exterior, the wires move within a “zigzag” plate electrode toproduce power, taking advantage ofthe coupled piezoelectric and semicon-ducting properties of zinc oxide nanostructures, which produce smallelectrical charges when they are flexed.

The power generated is only in thenanoampere range, but that should beenough to run a range of tiny devices,thus eliminating the need for batteriesor external power. It is projected thatan optimized version could produceup to 4 W/cc, which would be enoughto make it useful in defense, environ-mental, and (because zinc oxide isnontoxic) biomedical nano devices,including biosensors, environmentalmonitors, and nanoscale robots.

COMPUTERS ANDNETWORKINGEIGHT-CORE MACINTRODUCED

So far, 2007 has not produced a cornucopia of computer

hardware innovations, but Apple(www.apple.com) has upgraded itsline of Mac Pro desktops to include aneight-core version. The top model

includes dual quad-core IntelXeon “Clovertown” proces-sors running at 3.0 GHz, asopposed to the lesser onesthat offer two dual-core“Woodcrest” chips running at2.0, 2.66, or 3.0 GHz. Thebox has four hard drive baysproviding up to 3 TB of internal storage, and you caninstall as much as 16 GB ofmain memory. The optionsare too numerous to mention,

TECHKNOWLEDGEYEVENTS, ADVANCES, AND NEWS 20

07

BY JEFF ECKERT

ADVANCED TECHNOLOGY

Layout of the fuel cell poweredairplane.

Schematic showing the DC nanogenerator using ZnO nanowire arrays with a zigzag electrode.

PHOTO COURTESY OF BOEING.

PHOTO COURTESY OF GEORGIA TECH.

10 June 2007

Tech2007.qxd 5/7/2007 9:26 AM Page 10

T E C H K N O W L E D G E Y 2 0 0 7

with up to 33 millionpossible configura-tions of the system.But the eight-corebox is said to run upto twice as fast asthe G5 quad, so ifyou need the extracrunching power,here it is. The newmodel will set you back atleast $3,997, plus whateverextras you choose.

WIDGETS 4 AVAILABLE

If you haven’t already checked out theWidgets software available from

Yahoo! (www.yahoo.com), it may betime. If you already have, be advisedthat Widgets 4 is now available.Formerly named Konfabulator, it is an application platform that engagesvarious small applications such as aweather widget (displays weather information), a digital clock, a stock ticker, and so on. It includes the newFlickr Widget, which is an extension ofthe Flickr photo-sharing service. It helpsusers to display, upload, and tag images,and you can now do drag-and-dropoperations on larger groups of photosand edit their tags and other information

without using a browser. All in all,Yahoo! is offering more than 3,400desktop Widgets developed andsubmitted by independent authorsfrom around the world. Best of all,it’s free and runs on Mac OS X,Win 2000, Win XP, and Vista.

BE CAREFUL WHATYOU GOOGLE

Back in 2003, New Jersey prosecutors charged Melanie

McGuire with first degree murder,desecrating human remains, pos-

session of a weapon for an unlawfulpurpose, and perjury after her husband,William McGuire, was found shot, dismembered, divided among three suitcases, and floating in theChesapeake Bay. Although not all theevidence has been made public, datagleaned from several seized computersshowed that Melanie did a Googlesearch on “how to commit murder” 10days before the crime. She also scannedthe Web for such phrases as “unde-tectable poisons,” “fatal insulin doses,”“where to purchase guns illegally,” and“how to find chloroform.” She faces 30years to life if convicted, and hopefullysome extra time for computer illiteracy.

CIRCUITSAND DEVICESBINOCULARS WITHDIGITAL CAMERA

Sooner or later, everymale of the species

admires a female amoment beyond what istotally prudent, resulting inthe dreaded, “Take a

picture, buddy. It’ll last longer.” Well,now you can, and from a safe distance.Several manufacturers of binoculars arenow combining them with a digital camera, so no matter what kind of a birdwatcher you may be, you can recordnoteworthy sightings for posterity and/orthe Internet with total discretion. You canpick up a set at Wal-Mart for about $50,but be advised that this will get you resolution as poor as 0.3 megapixels,which isn’t exactly high-res. But if you arewilling to shell out something closer toreal money, you can get both qualityoptics and high digital resolution.

One example is the VistaPix 8 x 22from Celestron, LLC (www.celestron.com). It starts out with a basic 8 x 22 sys-tem and adds a three megapixel camerawith a 1.5-in flip-up color LCD screen forpreviewing images. The LCD offers a 6xdigital zoom so you can look at details,and a removable 8x telephoto lens allows you to take close-up or high-magnification shots. In addition to stillphotos, you can do sound-enabled videocaptures, making movies of up to threeminutes in length. And just for the heckof it, Celestron even threw in an FM radio with earphones. The list price of$251.95 seems pretty reasonable. Whydidn’t someone think of this sooner?

NEW COLORINSPECTION SYSTEM

Banner Engineering Corp.(www.bannerengineering.

com) has introduced a pair ofvision sensors that, although notparticularly useful in the averagehome, could come in handy ifyou are involved in visible spec-trum analysis on a commerciallevel in such fields as packaging,pharmaceuticals, and general

June 2007 11

The latest Mac Pro modelfeatures dual quad-core Xeon processors.PHOTO COURTESY OF APPLE, INC.

The new Flickr Widget extendsYahoo!’s photo-sharing service.

Accused Google murderer Melanie McGuire.

PH

OT

O C

OU

RT

ES

Y O

F N

EW

JE

RS

EY

OFFIC

E O

F T

HE

AT

TO

RN

EY

GE

NE

RA

L.

TheVistaPix combines8x magnification, fully coatedlenses, and three megapixel resolution.

PHOTO COURTESYOF CELESTRON.

Tech2007.qxd 5/7/2007 9:27 AM Page 11

quality control applications. Examplesinclude inspection of candy and packages, blister packs, filled bottles,and so on.

The two-piece PresencePLUS Proincludes a separate DIN-mountablecontroller, whereas the P4 is a one-piece unit. Both are said to detect aninfinite number of color variationsaccurately, and the sensor can combine shape and color data todetect even minute variations.

Both models come with the company’s universal software withthree-step point-and-click setup;Ethernet, serial, and discrete I/O capabilities; live video display withoutthe need of a PC; and a selection oflenses, light sources, mounting brack-ets, and accessories. The systems run

off 10 to 30 VDC and are availablewith interfaces in nine different lan-guages. Prices start at about $3,500.

LITHIUM BATTERIESPACK BIG CHARGE

Tadrian Batteries Ltd. (www.tadiranbat.com) now offers a line of

lithium cells for applications requiringhigh power, long life, and extendedstorage, such as defibrillators andother portable medical devices,mil/aero systems, telemetry, andUAVs, and so forth. The newly introduced AA-size TLM 1550 provides 2 Wh of energy at 4.0V andthe ability to handle pulses of up to15A and continuous loads of 5A.

It is designed for long life inextreme environmental conditions (-40 to +85°C) and features a self-discharge rate of only three percent peryear at room temperature. Because thecells are built with a glass-to-metal hermetic seal and nontoxic and nonpressurized solvents, they can beshipped as nonhazardous. The quantityprice is said to be about $5 each, whichis a bit more than the average Ray-O-Vac, but may be worth the money tokeep your digital camera from fuzzingout in the middle of your next hikethrough the Grand Canyon. NV

12 June 2007

INDUSTRY ANDTHE PROFESSION100TH ANNIVERSARY

In case you haven’tkept up with such

things, 2007 marks the100th anniversary of

the invention of the three-electrode version of the Audion vacuum tubethat allowed amplification for radioreception. It was also called the DeForest valve until about 1919, sincewhich time it has been better known asthe triode. Perhaps more interesting is the inventor, Lee De Forest, whoapparently was a colorful fellow. Onthe positive side, he earned a doctorate

from Yale, held more than 300 patents,and was a charter member of theInstitute of Radio Engineers (a prede-cessor of today’s IEEE). However, legend has it that he did not evenunderstand how his own inventionworked (and, in fact, his prototypesdid not work), and another inventor,Edwin Armstrong, had to explain itsoperating principles to De Forest. Hewrote an autobiography called Fatherof Radio, although most of the worlddid not recognize him as such. Duringhis career, he presided over severalcompanies that failed, was once indicted (and acquitted) for mail fraud,and was involved in several patent lawsuits that nearly bankrupted him. In1913, he was forced to sell the triodepatent to AT&T at a bargain basementprice. De Forest went to that big vacuum tube in the sky in 1961.

Inventor Lee De Forest(public domain photo).

The PresencePLUS® vision sensorsdetect an infinite number of color variations.

PHOTO COURTESY OFBANNER ENGINEERING.

• Over 40,000 ProductsStocked

• Access to over 1.5 million electronic partsand related products

• Installer/Dealer pricing program

• Quotation team,send us yourquotes for quickresponse

refer to or visit

www.mcmelectronics.com/magazine

call toll free1-800-543-4330

Source Code: NVM50

FREECatalog!FREECatalog!

Tech2007.qxd 5/7/2007 9:27 AM Page 12

Microcontrollers •• Digital Signal Controllers •• Analog •• Serial EEPROMs

www.microchip.com/PIC24

Control Your Remote withControl Your Remote withLow-Cost 16-bit MCUsLow-Cost 16-bit MCUs

Whether your design is a home theater remote or any other embedded application, the PIC24F delivers the peripherals, performance, development tools and software you need.

With 16 MIPS performance and an extensive peripheral set, Microchip’s PIC24F microcontrollers are highlycost-effective solutions.

GET STARTED IN 3 EASY STEPS!1. Learn all about our 16-bit products in only

20 minutes! Our FREE 16-bit web seminars highlight our 16-bit architecture and comprehensive support suite that includes low-cost development tools, a variety of software libraries (many free), application notes, reference designs and more!

2. Take advantage of FREE resources for download!Our MPLAB® IDE Integrated Development Environment and a full-featured trial of the MPLAB C30 C Compiler from our web site gets you up and running fast!

3. Get hands-on technical training for as low as $25!Attend a 16-bit Embedded Control Solutions Seminar at a MicrochipRegional Training Center to take your designs to the next level!

MIC

ROCHIP

TECHNOLO

GY

REGIO

NAL T

RAIN

ING C

ENTE

RS

EXPLORE DESIGN

APPLY

Purchase and program your16-bit PIC24F devices andrelated development tools at...

Device Pins Flash (KB)

PIC24F FamilyFeatures

PIC24FJ64GA006 64 64 8 KB RAMParallel Master Port

5 - 16-bit Timers5 - Output Compare/PWM

5 - Input CapturesReal-Tme Clock Calendar2 - UART with IrDA® and

LIN Protocols2 - SPI, 2 - I²C™

10-bit ADC, 16 Channels2 Analog Comparators

PIC24FJ64GA008 80 64

PIC24FJ64GA010 100 64

PIC24FJ96GA006 64 96

PIC24FJ96GA008 80 96

PIC24FJ96GA010 100 96

PIC24FJ128GA006 64 128

PIC24FJ128GA008 80 128

PIC24FJ128GA010 100 128

Visit our web site for more information about additional16-bit devices with higher performance and added features like DSP and enter our 16-bit Embedded

Design Contest today!

microchipDIRECT

www.microchipdirect.com

The

Mic

roch

ip n

ame

and

logo

, the

Mic

roch

ip lo

go a

nd M

PLAB

are

reg

iste

red

trad

emar

ks o

f M

icro

chip

Tec

hnol

ogy

Inco

rpor

ated

in t

he U

SA

and

in o

ther

cou

ntrie

s.Al

l oth

er t

rade

mar

ks m

entio

ned

here

in a

re p

rope

rty

of t

heir

resp

ectiv

e co

mpa

nies

. ©

2007, M

icro

chip

Tec

hnol

ogy

Inc.

4/20/2007 1:44:52 PM

Full Page.qxd 5/9/2007 2:38 PM Page 13

TToopp PPiicckkss......JJuusstt ffoorr TThheemm!!

33--IInn--11 MMuullttiiffuunnccttiioonn SSoollddeerriinngg LLaabb

Take a closelook! On yourleft is a multi-function 3½digit digitalmultimeter. Itslarge backlit LCD display can be seen fromanywhere on your bench while you’re working.The DMM also features built-in transistor, diode,and continuity testing, data hold, and audiblealarm. Next up, the regulated lab DC power sup-ply. Switch selectable ranges of 3V, 4.5V, 6V, 7.5V,9V, and 12V provide a continuous duty current of1.5 amps with a 2 amp peak! Features both over-load protection and overload indication.

To the right we have a high quality temperatureregulated soldering station. The 24V low voltageiron features an isolated ceramic 48 watt tempera-ture controlled element. Front panel control givesyou variable tip temperature control from 150°C to450°C and LED indication of power-on and heat-ing-on. Runs on 120VAC.LAB1U 3-In-1 Soldering Lab $119.95

For nearly a decade we’ve been the leader in hob-byist FM radio transmitters. The FM30 series oftransmitters is the latest and greatest! We told ourengineers we wanted a new technology transmit-ter that would provide FM100 series quality with-out the advanced mixer features. They took it as achallenge and designed not one, but TWO trans-mitters! The FM30 is designed using through-holetechnology and components and is available onlyas a do-it-yourself kit, with a 25mW output verysimilar to our FM25 series.

Then the engineers redesigned their brand-newdesign using surface mount technology (SMT) fora very special factory assembled and testedFM35WT version, with 1W output for our exportonly market! Both are designed around an RFtight vinyl clad metal enclosure for noise free andinterference free operation.

All settings can bechanged without tak-ing the cover off!Enter the setupmode from the frontpanel and stepthrough the menu tomake all of youradjustments. A twoline LCD displayshows you all thesettings! In addition

to the LCD display, a front panel LED indicates PLLlock so you know you are transmitting. Besidesfrequency selection, front panel control and dis-play gives you 256 steps of audio volume (left andright combined) as well as RF output power. Aseparate balance setting compensates for left/rightdifferences in audio level.

In addition to settings, the LCD display shows you“Quality of Signal” to help you set your levels foroptimum sound quality. And of course, all settingsare stored in non-volatile memory for future use!The stylish black metal case measures 5.55"W x6.45"D x 1.5"H. Runs on 13.8-16VDC, plug-in110VAC power supply included.

(Note: The end user is responsible for complying with allFCC rules & regulations within the US, or any regulationsof their respective governing body. FM35BWT is for exportuse and can only be shipped to locations outside the con-tinental US or valid APO/FPO addresses or valid customsbrokers for end delivery outside the continental US).

FM30B FM Stereo Xmtr Kit $199.95FM35BWT FM Stereo Xmtr Export $299.95

PPaassssiivvee AAiirr BBaannddAAiirrccrraafftt MMoonniittoorr

For decades we have been known for our novel and creative product designs.Well, check this one out! An aircraft receiver that receives all nearby traffic withoutany tuning. It gets better... there is no local oscillator so it doesn't produce, andcan't produce, any interference associated with all other receivers with an LO. Thatmeans you can use it onboard aircraft as a passive device! And what will you hear?The closest and strongest traffic, mainly, the plane you're sitting in! How unique isthis? We have a patent on it, and that says it all!

This broadband radio monitors transmissions over the entire aircraft band of 118-136 MHz. The way it works is simple. Strongest man wins! The strongest signalwithin the pass band of the radio will be heard. And unlike the FM capture effect,multiple aircraft signals will be heard simultaneously with the strongest one theloudest! And that means the aircraft closest to you, and the towers closest to you!All without any tuning or looking up frequencies! So, where would this comein handy?

1. At an air show! Just imagine listening to all the traffic as it happens2. Onboard aircraft to listen to that aircraft and associated control towers3. Private pilots to monitor ATIS and other field traffic during preflight

activities (saves Hobbs time!)4. Commercial pilots to monitor ATIS and other field traffic as needed at

their convenience5. General aircraft monitoring enthusiasts

Wait, you can't use a radio receiver onboard aircraftbecause they contain a local oscillator that could gen-erate interfering signals!

We have you covered on that one. The ABM1 has nolocal oscillator, it doesn't, can't, and won't generateany RF whatsoever! That's why our patent abstract istitled "Aircraft band radio receiver which does not radi-ate interfering signals". It doesn't get any plainer thanthat! Available as a through-hole hobby kit or a factoryassembled & tested SMT version.

ABM1 Passive Air Band Monitor Kit $89.95ABM1WT Passive Air Band Monitor, Factory Assembled & Tested $159.95

Monitors the entire aircraft band without tuning! Passive design, can be used on aircraft, no local

oscillator, generates and creates no interference! Great for air shows Patented circuit and design!

SPECIFICATIONSFrequency Range: 118 MHz to 136 MHzReceiver Type: Patented Passive DetectorIF Frequencies: None!Receiver Sensitivity: Less than 2 uV for detectable

audioAudio Output: 700mW, 8-24 ohmsHeadphone Jack: 3.5mm stereo phoneExternal Antenna: Headphone cord coupled Power Requirement: 9VDC batteryDimensions: 2.25” x 2.8” PC Board

2.5” x 4.6” x .9” CaseWeight: 4 oz. with battery

DDiiggiittaall TTuunneedd HHiigghh PPeerrffoorrmmaanncceeAAiirrccrraafftt BBaanndd RReecceeiivveerr

Professional features at a hobbyist price! To begin with, we designed it with thelatest technology, utilizing a rock stable synthesized PLL dual conversion receiver. We gave itsuperb image and adjacent channel rejection to allow you to lock onto the signals you want and not to bebothered by those you don’t!

Once we got the RF portion designed we took a closelook at the features desired in such a receiver. Wegave it a neat 2x8 line LCD display to show you all thefunctions. Control of modes and setups is obtainedthrough the front panel controls and confirmed on theLCD display. On/Off/Volume and Squelch controls arealso provided on the front panel. We even gave it afront panel speaker in case you stack the lighting con-troller or something else on top of it! So far we’vedescribed the ultimate aircraft receiver that’s not onlythe perfect field monitor for a hangar or airport man-ager’s office, but for the serious enthusiast. Can it getany better than that? It sure can!

The top request we’ve had for a professional aircraftreceiver was to embed automatic runway lighting con-trol. Consider it done! The lighting controller follows the standard protocol for remote runway lighting. Thepilot “keys” his microphone on the local CTAF channel for the specified number of times. All you need to do isset the receiver for the lighting control mode, then make sure the squelch is closed and will open on a suitablystrong signal. Typically the number of “keys” or “events” according to the receiver control the lighting as fol-lows: 3 events, 25% brightness; 5 events, 50% brightness; and 7 events, 100% brightness. The AR2’sadjustable lighting timer sets turn-on duration to your needs. Includes the matching case and knob set andpower supply. For the aviation professional that is not interested in building the receiver, the AR2 and the light-ing controller are also available factory assembled and tested, ready to go. Just plug it in and you’re all set.

AR2 Synthesized Aircraft Receiver Kit With Case & AC Power Supply $199.95AR2WT Factory Assembled & Tested AR2 Synthesized Aircraft Receiver $269.95AR2L Plug-In Runway Lighting Controller Interface Kit With Case & AC Power Supply $59.95AR2LWT Factory Assembled & Tested AR2L Runway Light Controller $99.95

Rock solid dual conversion PLL receiver! Airport runway lighting controller output! 4 user memory scanner banks, 20 freq’s each Full band scanner with skip and skip/timer modes Internal front panel speaker External antenna input, speaker out, headphone out Stylish and shielded black metal enclosure Available as a hobby kit or factory assembled & tested

SPECIFICATIONSFrequency Range: 117.975 MHz to 137.000 MHz

25kHz stepsReceiver Type: Dual Conversion PLLIF Frequencies: 10.7 MHz & 450 kHzReceiver Sensitivity: Less than 1 uV across the bandImage Rejection: Greater than -80 dBAdjacent Ch. Rejection: Greater than -40dBScanner Banks: 4, 20 frequencies eachAudio Output: 1 watt, 8 ohms Light Controller Output: 3 events, 5 events, 7 events

output to controllerPower Requirement: 12VDC, 500mAExternal Antenna: BNC female, rear panelDimensions: 5.55”W x 6.45”D x 1.5” H

Get Your Grad & Your DadThe Neatest Gifts Around!

They Deserve It! DDiiggiittaall FFMM SStteerreeoo TTrraannssmmiitttteerr

NutNVolt200706.qxd 5/9/2007 2:43 PM Page 14

Get The Catalog!Get the brand new 2007 Ramsey HobbyCatalog! 96 value packed pages of theneatest goodies around! Order yourson-line today or give us a call! Or

download the PDF at www.ramseykits.com.

590 Fishers Station DriveVictor, NY 14564(800) 446-2295(585) 924-4560

Build It! Learn It! Achieve It! Enjoy It!

Prices, availability, and specifications are subject to change. Not responsible for typos, stupids,printer’s bleed, or early season sunburn. Robin gave me extra time for the June theme! Thanks!

Visit www.ramseykits.com for the latest pricing, specials, terms and conditions.Copyright 2007 Ramsey Electronics, LLC...so there!

MORE than just friendly on-line ordering!Clearance Specials, Ramsey Museum, User Forums, Dealer Information, FAQ’s, FCCInfo, Kit Building Guides, Downloads, Live Weather, Live Webcams, and much more!

www.ramseykits.com800-446-2295

WhereElectronicsIs Always

Fun!

VViissiitt wwwwww..rraammsseeyykkiittss..ccoommFFrreeee GGiivveeaawwaayyss aanndd AALLLL tthheeiinnffoorrmmaattiioonn yyoouu eevveerr nneeeeddeedd!!

Did You Know... It’s impossible to give you full specs on these products

in a 1” space! A lot of our kits are also available “factory assembled

and tested”, if you don’t want to build them! We have over 350 products currently available, and

all those don’t fit here!

The Solution!

HHiigghh RReessoolluuttiioonn AAiirr PPrreessssuurree && EElleevvaattiioonn SSeennssoorr

We really did it this time! The UP24 is one of ourmost advanced kits to date, and an absolute MUSTfor anyone serious about the environment aroundus. But the applications only begin there!

The unique design allows unprecedented super highresolution measurements and display of absoluteatmospheric air pressure. The UP24 senses ambientair pressure and critically calculates elevation withunheard of precision! Using a highly sensitive sensorand 24-bit A/D converter in a special noise-immunedesign, less than 1/3 of an inch of elevation resolu-tion is achieved! YES, we said 1/3 of an inch!

This high accuracy and resolution opens the door toa host of sophisticated environmental air pressuremonitoring applications.

Unlike your normal run-of-the-mill barometer, airpressure is sensed in Pa's or kPa's. What are thoseyou may ask? Pascals or KiloPascals. However,don't be afraid, for your convenience, and to fit anyapplication you may have, it is also displayed in mil-libars, bars, PSI, atmospheres, millimeters of mercu-ry, inches of mercury, and feet of water! Take yourpick! The range of the UP24 is 15kPa to 155kPa.And that also means:

15000 to 155000 Pascal's 150 to 1550 Millibars 0.15 to 1.55 Bars 2.175566 to 22.48085 Pounds per square inch 0.1480385 to 1.529731 Atmospheres 112.5093 to 1162.596 Millimeters of mercury 4.429498 to 45.77148 Inches of mercury 5.02 to 51.9 feet of water

We've talked about air pressure, now let's talk aboutelevation! The incredibly precise 24 bit A/D convert-er in the UP24 looks at the air pressure and convertsit to elevation above sea level. In both graph andtext, the elevation is displayed to a resolution of athird of an inch!

The applications for the super accurate elevationmeter are endless. From watching and recordingelevations during hiking trips to measuring andrecording the wave heights from your boat! Let yourimagination take over from there!

What if you're in the field and you want to save datacaptured in your UP24? The built-in FLASH storageprovides 13,824 samples of storage. Then you cantransfer your data to your PC with a standard USBinterface.

While the UP24 is small enough to be kept in yourcoat pocket it boasts a large 2.78" x 1.53" 128x64pixel LCD display screen making viewing easy.Display modes include both realtime pressure andelevation graphs as well as pressure and elevationstatistics.

There are 12 user selectable sample rates from1/10th of a second all the way up to every 15 min-utes. Includes a built-in NiMh battery pack for up to4 days of continuous use. 110VAC charger is includ-ed. May also be charged from a 6-12VDC source.

Needless to say, you cannot put all the specs and allof the screen shots in the limited space of this ad!Just check out the Elevation and Air Pressure dis-plays below! For detailed information and specs visitour website at www.ramseykits.com.

If you're looking for the finest air pressure and eleva-tion sensor, check out the UP24, truly a marvel inthe industry! Available in a ready-to-build kit or afactory assembled and tested version that you canstart using right out of the box.

UP24 High Resolution Air Pressure/Elevation Sensor Kit $239.95UP24WT Factory Assembled and Tested UP24 $299.95

PPeerrssoonnaall PPrraaccttiicceeGGuuiittaarr AAmmpplliiffiieerr && DDII

So you're a guitar musician, and you live in an apart-ment...what else needs to be said! You would love toplug into your 100 watt HiWatt (my favorite brand!)amplifier and let it crank, but the neighbors probablywouldn't share your enthusiasm! The PGA1 wasdesigned to give you hours of enjoyment playing yourfavorite electric guitar while isolating your family, friends,and neighbors from your music and your passion. (I stilluse the original engineering prototype with my SG withP90’s!)

Whether you use an electric, acoustic electric, or bass gui-tar, the PGA1 gives you an adjustable volume output toyour favorite headphones. Unlike a lot of practice amps,the PGA1 has a special bass boost to enhance bass guitaruse. One practice amp for all your guitars! If you wantto practice to your favorite music, the PGA1 has a stan-dard style audio input to play to your favorite music! Justplug in your Walkman style CD player, MP3 player, oreven the headphone output on your mixer board andyou'll hear both your music source and your guitar inyour headphones!

The PGA1 uses a powerful LM386 power amplifier toprovide one watt of power to your headphones, or evena small speaker! It gets even better...use the PGA1 as acheap and easy direct inserter box to match your guitarinto an aux input of a stereo receiver amplifier or PAamplifier! It sounds GREAT! A standard ¼" audio inputconnector is used for your guitar input, matching yourstandard guitar cables. A top mounted on/off/volumecontrol adjusts the headphone output level through thefull range. The small belt clip pocket size device runs ona standard 9V battery (not included). A LED indicatespower-on and relative battery condition. The attractivecompact case measures 4.5"H x 2.7"W x 1.1"D.

Available in a kit form to “learn as you build” or factoryassembled and tested to get playing right out of the box!

PGA1 Personal Practice Guitar Amp Kit $64.95PGA1WT PGA1 Factory Asmb & Tested $99.95

Practice your guitar or bass without disturbing others!

Standard ¼” guitar audio plug input

CD/MP3 player audio headphone input to practice to your favorite music!

Switchable bass boost! Great as a DI to your home stereo amplifier! Uses standard 9V battery Includes guitar strap/belt clip case!

Pressure resolution greater than 0.0001kPa! 128 x 64 pixel graphical display! Shows realtime elevation & pressure changes! USB computer interface for easy data transfer! 13,824 samples of FLASH storage available! Special pilots menu Multiple built-in alarms

What The Customer’s Are Saying...“Simply Stunning!”

Elevation Graph Elevation Statistics

Air Pressure Graph Air Pressure Statistics

NutNVolt200706.qxd 5/9/2007 2:45 PM Page 15

The response to the speed-test article was amazing. I got more

emails from that article than any article prior. Several knowledgeable C language people pointed out mymistake. I also had a few people pointout that Revolution Education’sPICAXE programming system couldbe “overclocked,” meaning it could berun with an 8 MHz or 16 MHz resonator in place of the 4 MHz resonator I used in the speed test. At 16MHz, the PICAXE would run almost asfast as Basic Micro’s Basic Atom.

This was great feedback, since itindicates that readers of this columninclude programmers from variousexperience levels and are reading thedetails. In other words, they aren’tfalling asleep reading my stuff. Nowlet me explain the error.

CODE ERROR EXPLAINEDIf you missed the April column

speed test, I just did a simple For-Nextloop that continued for 255 iterations,and within the loop I processed a

simple math equation to increment avariable. I toggled a pin outside theloop so I could measure the processingtime on an oscilloscope, as shown inFigure 1. In the article, I made one mis-take that several C programmers point-ed out. In the section where I comparedPICBasic Pro to the PICC-Lite compiler,I declared two “int” variables in the Ccompiler version of the speed-test code.

This was a huge mistake in aspeed test program, since “int” createsa 16 bit variable in the C program —but in all the Basic versions of thecode I declared byte variables. Thisgreatly affected the speed results. Yousee, the PIC MCUs I used in the article were eight bit microcontrollers,meaning they have an eight bit widedata bus. To process a 16 bit variable,the program has to perform the mathfunction in two steps: low byte thenhigh byte. This takes twice as long.Therefore, it incorrectly showed the Ccompiler slower than PICBasic Pro.

To add to the confusion, I didn’teven realize until much later that I alsosent the final version of the article with

a typo in the C codeembedded in the text. TheC code in the publishedcolumn included the For-Loop variable changingfrom 0 to less than 256;when in reality I ran it 0 toless than 255 because Iknew a byte variable wouldalways be less than 256.

Changing from 256 to 255 should havetipped me off to the “int” variable error,but I completely missed it. You see, abyte variable will roll over to 0 afterreaching 255 — since the 256 decimalis 100000000 binary. As this shows, ittakes nine bits to store the 256 decimaland the lower eight bits (or byte) arezeros. So, I was thinking byte variable inmy corrected code, but left the 16 bit“int” variable declaration in the code. IfI wasn’t focusing on a speed test, itwouldn’t have been an issue.

I even admitted I was shocked by the results of the PICBasic Pro compiler being faster than C. I testedit on another processor, but got thesame results since I made the samemistake. If an operating system supplier finds a bug, then they releasean upgrade. This article is my upgrade!I’m correcting my mistake and clearlypointing out that the speed of thePICBasic Pro was fast, but not as fastas the corrected version of the C codecompiled by the PICC-Lite compiler.

After a very nicely written emailfrom Langue Rodriguez pointed outmy mistake, I went back and declaredthe variable in the C program as anunsigned “char” variable (which madeit an eight bit variable) and re-ran thespeed test. The corrected code isshown in Listing 1. This re-test showedthe PICC-Lite C program was fasterthan PICBasic Pro by 460 microsec-onds, with the setup running at 4MHz. The PICBasic Pro program took

PICs BY CHUCK HELLEBUYCK

THE LATEST IN PROGRAMMING MICROCONTROLLERS

IN MY APRIL COLUMN, I DID A SPEED-TEST comparison of various PIC®

microcontrollers (MCUs) that were programmable in Basic, and then compareda Basic and C compiler. I made a mistake that affected the results. I claimedthat microEngineering Labs’ PICBasic Pro compiler outperformed HI-TECH’sPICC-Lite compiler for speed, and I was wrong. PICC-Lite compiled code runsfaster. I’ll explain how I goofed a little later.

C LANGUAGE INTRODUCTION

GETTING STARTED WITH

FIGURE 1

16 June 2007

GetStartedWithPICs.qxd 5/7/2007 2:11 PM Page 16

1.76 milliseconds and the correctedHI-TECH PICC-Lite version only took1.3 milliseconds.

This was a good lesson for me tohave extra eyes review my codebefore releasing articles in the future,and I promise to do that. It also taughtme something I never really thoughtof prior to this. Declaring the correctsize variables can have a huge impacton the processing time of your code.

I remember many times when Iwanted to create a variable that wouldcontain values only slightly larger than255. I would declare a 16 bit value or aword variable in PICBasic Pro. Now Isee how this cost me significant pro-cessing time. To understand exactlyhow much it cost me, I re-ran thePICBasic Pro code with a 16 bit“word” variable declared. It was alot slower than the C program withthe “int” variable. PICBasic Pro took2.6 milliseconds with a 20 MHz res-onator and 13.1 milliseconds with a4 MHz resonator. The PICC-Litecompiler took 720 microseconds at20 MHz and 3.6 milliseconds at 4MHz. It’s very clear by looking atthis the PICC-Lite compiler handles16 bit math much more efficientlythan the PICBasic Pro.

All this speed comparingbetween these two fine compilers isrelative, though, because — despitethis 16 bit variable slowdown —PICBasic Pro with a 16 bit variabledeclared and running at 4 MHz wasstill faster than the PICBasic standardversion — even with the variable stillset as a byte (reference Table 1 fromApril). I’m often asked, “Why shouldsomeone spend a couple of hun-dred dollars for the PICBasic Procompiler when they can programwith a cheaper option?” This is clearly one of the reasons.

In many projects, high speedswon’t matter. But in cases where itdoes, it’s good to know the limits —especially if your program has lotsof math equations. Those applica-tions may be the time where youuse a byte variable for the lowbyte, and then have a second bytevariable for the high byte, followedby a check to see whether the lowbyte overflowed before updating

the high byte. This would save processing time, since you are working with byte-sized variables.

OTHER COMPILERCHOICES

Another batch of comments camefrom people curious about other com-pilers, such as Crownhill Associates’Proton Basic compiler. I’ve tried it inthe past and remember it using a slight-ly different setup than Parallax’s BASICStamp PBASIC style, which the testprogram was based on. I decided to try

Proton on this speed-test code. I down-loaded the sample version of Proton tosee if it supported the same chips Iused. The sample version doesn’t sup-port the PIC16F876A or PIC16F877A,but did support the PIC16F877. I dugaround and found one of those olderchips, so I was able to run it. I waspleasantly surprised to find the samespeedtest.bas program compiled inProton, but I got a few warnings.

Proton prefers you to use the DIMinstead of VAR directive for creatingvariables, and it uses a different command than PAUSE for delays. Thecompiler did compile it, though, and

G E T T I N G S T A R T E D W I T H P I C s

LISTING 1#include <pic.h> // Include HITECH CC header file

void Pause( unsigned int usvalue ); //Establish pause routine functionvoid msecbase( void ); //Establish millisecond base function

main()

PORTB = 0; //Clear PortC portTRISB = 0; //All PortC I/O outputs

while(1) //loop forever

unsigned int z, y;RB0 = 1; // Turn on RC0 LEDfor(z=0; z<255; z=z+1)

y=y+1;

RB0 = 0; // Turn off RC0 LEDPause(10); // Pause 10 msec

//End while //end main

//*******************************************************//pause - multiple millisecond delay routine//*******************************************************

void Pause( unsigned int usvalue )unsigned char x;

for (x=0; x<usvalue; x++) // Delay usvalue in millisecondsmsecbase(); // Millisec delay routine

//*******************************************************//msecbase - 1 msec pause routine//*******************************************************

void msecbase(void)

OPTION = 0b00000001; //Set prescaler to TMRO 1:4TMR0 = 0xd; //Preset TMRO to overflow on 250 countswhile(!T0IF); //Stay until TMRO overflow flag equals 1T0IF = 0; //Clear the TMR0 overflow flag

June 2007 17

GetStartedWithPICs.qxd 5/7/2007 2:11 PM Page 17

just gave warnings. The warnings evenstated the commands were recognizedfor backward compatibility, which is anice feature. I only ran the test at 20MHz on the PIC16F877. As it turnedout, my test showed Proton ran exactlyequal to PICBasic Pro, completing theloop in 350 microseconds @ 20 MHz.

Langue also sent me an email thathe had tested a corrected version ofthe C file on the CCS C compiler, andincluded the results in his email. Hereported a result of 1.794 ms at 4 MHzwith the variable corrected to eight bits(int8). According to this result, CCS isslower than PICBasic Pro’s 1.76 ms ineight bit mode, but I really wanted toconfirm this, so I ran it myself.

I measured 1.792 ms when I test-ed Langue’s code with the CCS PCMversion and a PIC16F877A at 4 MHz.To get this accuracy, I used a muchfiner resolution on the scope. I wentback and re-measured the PICBasicPro code at this scope resolution, andfound it to be 1.790 ms. Therefore, Iconcluded that the CCS and PICBasicPro compilers ran at the same speed,and that my previous measurementhad some resolution error. I ran thePICC-Lite at this finer resolution, but

got the same 1.300 ms result asbefore. Langue’s CCS code is shown inListing 2 if you want to test it yourself.

C INTRODUCEDThis seems like a good point to

introduce some simple C coding tothose who haven’t worked with this language. The C language at first seemsa lot different than Basic, but in reality,it’s more format that anything. C codefor PIC MCUs is different than trying towrite C code for a PC application. Inthis respect, having the PIC MCU experience from programming in anyother language is a bonus, because youunderstand the internal setup. Forexample, let’s take the very simple program in Listing 3 written for the HI-TECH PICC-Lite compiler. (It justlights an LED on PORTB bit 0.) I use itbecause it shows the basic structure ofC coding. The top of the file has the line

#INCLUDE <pic.h>

This includes all the necessary PICC-Litecompiler setup information in the program, and each C compiler will haveits own version of this included file.

The next line estab-lishes the configurationsettings. I wrote this simple program inMicrochip’s MPLAB®

integrated developmentenvironment (IDE) and

set it up as a project. In the projectsetup, I selected the PIC16F876A. The#if to #endif block of code tests for thisprocessor selection, and if any of thoselisted are selected in the MPLAB IDE,the compiler will include the configura-tion fuses to run in the external crystalmode (XT) with watchdog timer (WDT-DIS), brownout reset (BORDIS), andlow voltage programming (LVPDIS) disabled. This will get transferred to theprogrammer automatically, through thefinal compiled and assembled .hex file.

The main body of the code isnext. All C programs begin executionin a function named “main()”, whichmay be passed any arguments from anexternal source. Every function in C isbounded by a set of braces, andmain() is no exception. The first thingwe do in main() is to set up thePORTB and TRISB registers. We clearthem both to make all of the PortBpins set to outputs and cleared. Thisdoesn’t look much different than aBasic program.

The program then executes a continuous loop with the while() statement. The expression in theparenthesis is evaluated and, as long as it is true (a logical 1), the commands within the while statement’s set of braces are executed.This is also not much different than the While command in many Basiccompilers, except the commands arenot contained within parenthesis. Inthis case, the formula is simply “1”,

18 June 2007

LISTING 2***************************************************

c-file follows:

// Basic program to compare speed and code size#include <16F876A.H>#device *=16 #fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP#use delay(clock=4000000)

#define RB0 PIN_B0

//======================================void main()int8 z, y;while (true)output_high(RB0);for (z=0;z<255;z++)

y++;output_low(RB0);delay_ms(10);

***************************************************

LISTING 3#include <pic.h> // Include HITECH CC header file

#if defined(_16F873A) || defined(_16F874A) ||\defined(_16F876A) || defined(_16F877A)__CONFIG (XT & WDTDIS & BORDIS & LVPDIS);

//XT Crystal Mode, Watchdog off, BrownOut Disabled#endif

main()PORTB = 0; //Clear PortC portTRISB = 0; //All PortC I/O outputs

while(1) //loop forever

RB0 = 1; // Turn on RC0 LED //End while

//end main

end;

GetStartedWithPICs.qxd 5/7/2007 2:12 PM Page 18

which is a wonderfully useful expression mechanism in C — justabout everything can be used as aboolean value (those things zero areFALSE, those non-zero are TRUE).Since the while() loop conditional will always return TRUE, it will loopforever. The commands within while()sets RB0 or PortB bit 0 to a one, whichturns on the LED.

The program is completed by putting the closing braces for both themain() function and while() loop. Itcloses with an end command.

One thing to note with the structure of C is that all command lines— AKA statements — end with a semi-colon. This is one of the biggest errorsfor beginners, as it is not required inassembly or Basic. Also, comment linesstart with a double backslash — not acolon or semi-colon like assembly orBasic. If you can get past the bracesand colons, the program doesn’t lookmuch different than a PICBasic pro-gram. You can see some of the differ-ences between the HI-TECH PICC-Liteand the CCS C compilers by comparingListing 3 to Listing 2. I mainly wanted tointroduce the basics of C code, andplan to help you learn more as this column progresses along.

CONCLUSIONI still feel that programming PIC

MCUs in Basic is the best option forthe beginner, but if you want to doany programming outside of the hob-byist arena, you should at least learnsome C. I started with assembly andhave used Basic for years, so those arelike second nature to me. Adding C tomy software skills made programmingPIC MCUs even more fun, and I hopeto pass on what I know to those thatwant to learn C, as well.

I’ve watched and helped manycomplete beginners get started

programming by using the Basic Atomand PICBasic Pro. I also know otherswho learned with the various otheroptions. There is no single correctchoice. If Proton or PICC-Lite orPICAXE or BASIC Stamp or any otherchoice gets you started programmingPIC MCUs, then go for it. When I start-ed, the choices for the hobbyist orbeginner were limited and findinghelp was next to impossible.

I often wished that I had someone

teaching me or had books to readwhen I got started, but I couldn’t findmany. Those books I did find were writ-ten for the professional and were oftenway over my head. I had to find all thisout on my own. I hope you keep reading, and I’ll be more careful aboutthe errors. Send me emails with yourfeedback, because as you can see, I listen. Send them to [email protected] and stop by my website anytimeat www.elproducts.com. NV

June 2007 19

The NEWEST Semiconductors | Passives | Interconnects | Power | Electromechanical | Test, Tools & Supplies

The Newest Products For Your Newest Designs

Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.

• The ONLY New Catalog Every 90 Days

• NEWEST Products & Technologies

• Over 800,000 Products Online

• More Than 330 Manufacturers

• No Minimum Order

• Fast Delivery, Same-day Shipping

mouser.com (800) 346-6873

Easy Ordering In Nanoseconds

Mouser_NutsVolts_6-1-07.indd 1 5/3/07 8:45:20 AM

NOTE: PIC and MPLAB are registeredtrademarks of Microchip Technology,Inc., in the USA and other countries.All other trademarks mentionedherein are property of their respective companies.

G E T T I N G S T A R T E D W I T H P I C s

GetStartedWithPICs.qxd 5/7/2007 2:38 PM Page 19

Full Page.qxd 5/9/2007 3:01 PM Page 21

Variable Timer.

Solar Cells.

PCB Layout Programs.

VARIABLE TIMER

QI need a timer to charge small rechargeable batteries.I need outputs of 1, 2, 4, 8, and 16 hours. I have

a 1, Pole 5, throw switch for time

selection. I can do all the peripheralwork such as relays and LEDS, etc. I just need the outputs. I already have the power supply and transistors for charging and discharging the outputs at about one amp. I have4060s, 4040s, 555s, other ICs, and

the resistors and capacitors.— William D. McMurray

AI don’t know why you wanta timer because a battery can be left permanently connected to a good charger

Q&A WITH RUSSELL KINCAID

22 June 2007

WHAT’S UP:Join us as we delve into thebasics of electronics as appliedto every day problems, like:

FIGURE 1

In this column, I answer questions about allaspects of electronics, including computer hardware, software, circuits, electronic theory,troubleshooting, and anything else of interestto the hobbyist. Feel free to participate withyour questions, comments, or suggestions.

SSeenndd aallll qquueessttiioonnss aanndd ccoommmmeennttss ttoo::Q&[email protected]

Q&A.qxd 5/9/2007 4:13 PM Page 22

without a problem. But, since I don’t know your application, here is my solution:

I can see you put some thoughtinto this. Having the times in binaryincrements makes it easy to use a binary counter. The 4060 has abuilt-in oscillator and we want an output in one hour (3,600 seconds).The 14th stage of the 4060 divides by 2^14 = 16384. If we divide3600/16384 = .2197, that is the inputperiod needed to give a one houroutput period. But there is a problem:The output starts at zero; after a halfhour, the output goes high and stays high for a half hour. I want tofeed the output back to the reset pin— which is active high — in order forthe counter to cycle every hour. So, I need to double the input period to .439. The data sheet gives theequation for period as: T =2.2*Rx*Cx. Choose Rx = 1 megohm,then Cx = .439/2.2 µF = .2 µF. Since0.2 µF is hard to find, use 0.1 µF, thenRx = 2 megohms. The resistor, Rs, justhas to be large; use 4.7 meg. See theschematic in Figure 1.

In the feedback loop, I used a 10Kand .01 µF cap to provide some delay;otherwise, the reset pulse will be sonarrow that you can hardly see it on a100 MHz scope.

I chose a 4013 set-up as a set-reset flip-flop to start and stop the charge. The two flip-flops in the4013 are connected in parallel inorder to give more output drive. Amomentary push button is used tostart the charge; the five positionswitch selects the time to reset theflip-flop and stop the charge. Thereset pulse is fed to a 4040 counterto produce the longer times. The first output (Q1) will be two hours;the next output (Q2) will be fourhours, etc. I had to introduce someOR gates in order to reset the counters at the same time that thestart flip-flop is set.

The charging circuit uses anLM317T. It has a current limit of 1.5amps; if that is enough current, youcan eliminate Q2 and R6. The2N5883 is rated 25 amps maximumbut cannot supply that much currentin this circuit. Here is why: It takes

one-half amp throughR6 to start turningQ2 on; that leavesone amp base cur-rent for Q2 when theLM317T is at currentlimit. Referring toFigure 2, Hfe versuscollector current,note that the gain isdown to 20 at 20amps, so with onlyone amp base current available, thatwould be the maxi-mum current output.But the base-emittervoltage increaseswith base current,further reducing thepossible output.Referring to Figure 3,the line labeledVbe@Vce=4V is pertinent. Note thatVbe at 20 amps collector current is1.6 volts. With oneohm and 1.5 amps,we can’t get there, so20 amps output isnot possible. Let’ssee if we can get 10amps. At 10 amps,the gain from Figure

QUESTIONS & ANSWERS

June 2007 23

FIGURE 2

FIGURE 3

YOUR COMPLETE BATTERY SOURCE

Authorized DealerOEM Battery Packs

[email protected]

2-way Radio Cellular Digital CamcorderLaptop Chargers Analyzers Cells

HIGHER CAPACITY HUGE SAVINGS!

Custom Assembly & Battery Rebuilding for:• Handheld Radios • Laptop • Camcorder • Test Equipment

5000+ Batteries Online Toll Free

20585 Camino Del Sol Unit B, Riverside, CA 92508

WWW.NICDLADY.COM 800/906-6423

Q&A.qxd 5/9/2007 4:15 PM Page 23

2 is 40. Vbe, from Figure 3, is 1.1volts, leaving 0.4 amps for base current. 40 X 0.4 = 16 amps, so 10amps at least is possible.

I put a 47 ohm, one watt resistoracross Q2 to provide a trickle chargeto the battery when the charger is off.When the battery is fully charged(about 14 volts), the peak voltageacross R10 will be four volts, giving apeak trickle current of 85 mA.

The size of the fuse in the transformer primary can be deter-mined as follows: The transformerratio is 10:1 so, the primary current isone amp when the load is 10 amps.Use a two amp fuse so it only blowsunder conditions of transformer orregulator failure.

SOLAR CELLS

QI am a novice when it comesto solar cells. I recentlybought six cells and startedplaying with them. I noticed

that even though they are all from the

same company and the same make,they produce different outputs. Is thisnormal? Also, when I paralleled twocells, if I did not put a diode in serieswith each, I would get a lower valuethan the average cell voltage. I was notexpecting these results.

Could you please shed some lighton this? Do you always need to use adiode in parallel with each cell whentrying to build up the amperage? I guessit goes without saying that you onlyneed one diode in series with two cellsin series for greater voltages.

Background: If you test the cells by themselves (open circuit), four ofthese solar cells are producing 15 to 17VDC, with two only producing eightvolts. The short circuit current is 100 to 140 mA.

Also, could you explain how to choose a solar cell for a project? Iunderstand if I am running four 12 volt fans at 100 mA, I would add upthe total amps: 400 mA for the project.But from what I am seeing on my meter, my voltage drop is a lot lower

than what I would expect for a parallelcircuit. Do I need to add a capacitor or something?

— DW

AMost solar cells are madefrom silicon and have an output voltage of 0.5 volts.What you have is a series ar-

ray of about 30 cells, giving an outputof nominal 15 volts. There are severalways to make a solar cell, but they allact like diodes. You can connect themin parallel and the output will be thatof the highest cell. I don’t know whatis causing the effects that you see. Perhaps you bought some productionrejects. You should not need a diodebetween units; the units themselves area diode. The power output of the solararray must meet or exceed the powerrequired by the load. If you need 400mA at 12 volts (4.8 watts), the solar array must exceed that because the sunis not at maximum most of the time.You can get good information from thisURL: www.solarserver.de/wissen/photovoltaik-e.html#from.

(The July issue of Nuts & Volts willhave extra “green power” coverage, sostay tuned!)

PCB LAYOUT PROGRAM

QI would like to download aPCB artwork program. Doyou know of any?

— Anonymous

AI assume you mean a free PCBlayout program. A Googlesearch turned up these pos-sibilities: www.ExpressPCB.

com, www.PCB123.com, www.freePCB.com, and www.cadsoft.de. Thefirst two are produced by companiesthat hope you will use their facility tomake the PC boards. My reading of reviews indicates that these are full fea-tured. FreePCB is open source freewareand the one review I saw indicated thatit was good. I included Cadsoft becauseI am using their Eagle program. The freeversion is limited in board size and partscount but should be adequate for youruse. There is a good manual and onlinehelp is excellent. NV

24 June 2007

Q&A.qxd 5/9/2007 4:16 PM Page 24

Full Page.qxd 5/9/2007 3:03 PM Page 25

THE ULTIMATECORD ORGANIZERCLIP

Delta 9 Products (DNP) introducesthe Ultimate Cord Organizer

Clip. Rick Nelson, DNP Product Manager explains, “Our product provides an innova-tive way for the professional to organize andtrack cables,cords, andwires betweenelectronic de-vices.” “Eachslot in the

Ultimate Cord Organizer Clip has a let-ter assigned to it and retains the cablesand cords when open. The UltimateCord Organizer sorts by size and type,but also allows you to channel, isolate,and track cords, cables, and wires. Theorganizer is available in four standardcolors: black, gray, neon orange, andneon green. Custom colors are available. The organizer is sold in fivepacks ($9.95), 10 packs ($18.90), 20 packs ($35.90), and 60-pack($102.35) quantities.

USB ACMONITOR

J-Works is now shipping model JSB-370 which monitors an AC line

and reports the on/off status of the lineover the standard USB (Universal Serial Bus). The user may select that anon-board relay turns on and off based on the status of the AC line. Theuser communicates with the modulefrom any pro-gramming or testlanguage thatsupports USBcommunications.This small formfactor module

P R O D U C T SNEW

HHAARRDDWWAARREE SSOOFFTTWWAARREE GGAADDGGEETTSS TTOOOOLLSS

For more information, contact:Delta 9 Products

Tel: 530-333-2014Web: www.ultimatecord

organizer.com

Order a 9XTend Development

Kit Today!

9XTend™

Long Range OEM RF Module

Toll-free 866-765-9885www.rf-modem.com/nv

• ISM 900 MHz operating frequency

• 1 mW - 1 Watt power output(up to 40 mile range)

• 256-bit AES Encryption

• Advanced networking topologies

26 June 2007

NewProductsJun07.qxd 5/10/2007 4:03 PM Page 26

replaces internal PC-based plug-in cardsin various test, control, monitor, andmeasurement applications. Completeproduct specifications are available atthe J-Works website. Single unit pricefor the Model JSB370 starts at $75. Delivery is from stock.

$99 DEVELOPMENTTOOL

Enabling design-ers to quickly

develop ultra lowpower medical, industrial, and con-sumer embeddedsystems using eithera highly integratedsignal chain on

chip (SCoC) MSP430FG4618 or small 14-pin F2013 microcontroller,Texas Instruments announces the availabilit y of the MSP430 Experimenter's Board (part numberMSP EXP430FG4618). Along with the two 16-bit MSP430 devices, the board includes a TI (Chipcon) radiofrequency (RF) module connecter for developing low power wireless networks. The board also features a number of input and output options such as a microphone,buzzer, liquid crystal display (LCD), capacitive touch-pad, push buttons,and pin board prototyping space,

among others.

Multiple Design Optionswith Two MSP430 devices

With two MSP430MCUs, designers can easilydevelop a variety of lowpower and battery-operatedproducts including costand space sensitive sensingapplications like motiondetectors, all the way to

highly integrated applications like high precision portable medical andindustrial sensing.

The F2013 is a small 4 mm x 4mm, 14-pin device that features a fullyprogrammable clock system that provides wake-up from an industryleading 500 nano-amp standby to full-speed operation in less than onemicrosecond. The F2013 device also includes a 16-bit sigma-delta analog-to-digital (ADC) for high-precision sensing systems, 2KB ofFlash and 128KB of RAM memory,and a basic serial communicationinterface (USI) which makes SPI andI2C implementations easy.

The FG4618 MCU includes116KB of Flash memory and incorporates the MSP430X corearchitecture with an extended 1MBmemory model. The extended memory access is ideal for larger system requirements andallows for the development of verysophisticated real-time applications,completely in modular C libraries. Up to three operational amplifiers —

H A R D W A R E S O F T W A R E G A D G E T S T O O L S

For more information, contact:J-Works, Inc.

11024 Balboa Blvd. Ste. 402Granada Hills, CA 91344

Web: www.j-works.com

June 2007 27

NewProductsJun07.qxd 5/10/2007 5:24 PM Page 27

to handle high precision instrumenta-tion — coupled with the on-board200ksps 12-bit ADC, one microsec-ond code-to-code settling time 12-bit digital-to-analog converter(DAC), and direct memory accesscontroller (DMA) complete a SCoCsolution that reduces overall systemcost and eliminates the need forexternal components.

Multiple Board Input and OutputOptions Allow For Fast SystemDevelopment

Combined with the two devicesis a host of interfaces and input/output options that allow a designerto quickly evaluate the suitability of either MSP430 MCU. JTAG headers on the board make bothdevices accessible for programmingand debugging, as well as communi-cation between the two MSP430s or to other external devices. A variety of input options include a microphone, capacitive touch-pad, and push buttons. Output peripherals include a buzzer, LCD,

RS-232 communication interface,and 3.5 mm headphone jack for analog output.

To accelerate the developmentof low power wireless RF systems,the Experimenter's Board includesconnectors for various Chipcon evaluation modules, which cover the <1 GHz and 2.4 GHz frequency bands (including IEEE802.15.4/ZigBee™ standards).Supported modules are the CC11x0, CC25x0, and the CC2420evaluation kits, which are availableseparately.

The MSP430 ExperimentersBoard is available for $99 and requires a Flash emulation tool, suchas the MSP-FET430UIF, available separately starting at $99. Chipconevaluation boards are available atwww.ti.com/estore.

VERSATILEMILLIOHMMETER FORPRECISIONRESISTANCEMEASUREMENTAPPLICATIONS

The CropicoDO4A from

Clare InstrumentsUS, Inc., is a highlyversatile, digital ohmmeter used for lowresistance measurement across a diverserange of production, safety, and designengineering applications.

Of particular relevance is theinstrument’s role in the precisionresistance measurement of electroniccomponents and switches, as well aselectrical connectors, crimp joints,fuses, and similar products.

The DO4A uses True 4 Wire measurement to eliminate lead resistanceerrors across a push button selectablerange from 40 mW to 4 kW with respec-

H A R D W A R E S O F T W A R E G A D G E T S T O O L S

28 June 2007

For more information, contact:Texas Instruments

Web: www.ti.com

NewProductsJun07.qxd 5/10/2007 4:04 PM Page 28

H A R D W A R E S O F T W A R E G A D G E T S T O O L S

tive resolutions between 10 mW and 1W.Contained in an aluminum case

with a tilted carrying handle, the robustunit is a highly practical instrument thatcan be used in the workshop, by fieldor maintenance engineers, or as part ofmore comprehensive electrical testfacilities. Input protection is providedup to 415 volts rms.

For ease of operation, the controlfunctions have been kept to a minimum and a four digit LCD givesdirect readings of the resistance measured, with over range and lowbattery indicators also provided.

Other special features include anauto zero facility where thermal EMFmay cause a large measuring errorand warning LEDs to indicate an opencircuit lead condition.

Rechargeable batteries provide fullportability with over 14 hours of con-tinuous working on the lowest rangesand 28 hours of operation on others.

The Cropico DO4A is suppliedready for immediate use and comescomplete with battery, mains cord, andmeasuring leads. In addition, a widerange of optional accessories includingduplex handspikes, other specialist clips,long length leads, and wire clamps fur-ther extend the instrument’s versatility.

THE NEWSCHMARTMODULE

SchmartBoard, the developer of anew technology that has significantly

simplified the creation of electronic circuits for hobbyists, education, and industry, announces the release of a newproduct — the Power SchmartModule.

A few benefits to the new moduleinclude: they allow virtually anyone to hand solder; users can surfacemount components easily, quickly,and flawlessly; and dexterity to hand

solder surface mount componentswith small pitches is not required.

Additionally, SchmartModulesoffer pre-designed common circuitsthat allow designers to quickly andeasily add common functionality with-out having to “re-invent the wheel.”

The Power SchmartModule allowsusers to power up circuits with one ofseven voltages, which include: -9, -12,+2.5, +3.3, +5, +9, and +12 volts. Theproduct comes as a bare board with abill of materials, schematic, and simple

instructions. Users solder the compo-nents onto the board themselves. Theboard uses SchmartBoard’s patent-pending “ez” technology to make soldering fast and easy. Because theproduct has variable power options,one can reuse the product on many different circuits if they choose. The sug-gested retail price of the board is $15.

June 2007 29

For more information, contact:Clare Instruments US, Inc.

6304 Benjamin Rd., Suite 506Tampa, FL 33634

Tel: 813-886-2775Fax: 813-886-2754

Web:www.clareinstruments.com

For more information, contact:SchmartBoard

Web: www.schmartboard.com

NewProductsJun07.qxd 5/10/2007 4:05 PM Page 29

PROJECTS

LEVEL RATING SYSTEM

To find out the level of difficultyfor each of these projects, turnto our ratings for the answers.

. . . . Beginner Level

. . . . Intermediate Level

. . . . Advanced Level

. . . . Professional Level

THIS MONTH’S PROJECTSWeather Station . . . . . . . . . . . .30

Mux Mux Light Display . . . . . .38

Probing Cores . . . . . . . . . . . . . .46

Software Serial Port . . . . . . . . .52 CCOONNTTRROOLLYOUR WORLD WITHAN X-10 INTERFACE

In the first couple ofinstallments of this

series, we used a PC totake measurements anddisplay the results fromour 1-Wire sensors.The

major drawback forbuilding a PC-based

weather station is thatthe PC has to be on all

the time.While theprograms can run in thebackground, you do tie

up any serial port youhave connected to your

PC. In this article,

I am going toshow you how tobuild a complete

microcontroller-basedweather station

complete with colordisplay.

30 June 2007

Let’s take a look at some of thebenefits of a microcontroller-

based weather station:

• Multiple 1-Wire networks for reliability.

• Full color display.

• Does not tie up the PC.

• Calculates Dew Point, Wind Chill,and Heat Index.

• Displays one minute wind speedaverage, as well as gusts.

• Displays real-time wind directionupdated several times a second.

• Real-time status indicator for eachsensor.

• Plots last 24 hour readings fortemperature, humidity, and windspeed.

• Tracks and plots last 24 hourbarometer readings.

• Displays 12 hour barometer forecast.

• Large portion of the display area isavailable for other sensors such aslighting, or moisture gauges.

Display System

For our display system, we will be using the ezLCD001 fromEarth Computer Technologies, Inc.;www.EarthLCD.com (Figure 1).

The ezLCD001 has a 240x160TFT color display. It has a built-in, software controlled backlightand several interface options:

• RS-232 level serial interface• TTL level serial interface• USB interface• I2C interface• SPI interface• Eight-bit parallel interface

In this article,

Microcontroller-Based Weather Station

FIGURE 1

Simpson.qxd 5/7/2007 3:16 PM Page 30

we are going to be using the I2Cinterface with our weather station. To power the display,anything from 3V to 6.6V willwork. I am going to use aDiosPro microcontroller becauseof its low cost and the fact that italready has a complete set ofbuilt-in ezLCD001 and 1-Wirelibraries. We will be using theDiosWorkboard Basic as thecarrier for both the DiosPro andezLCD001.

Initial Construction

We need to add a couple ofheaders so that we can plug theezLCD001 into the Workboard.Schematic 1 shows the displayhookup. Note that we have connected the display to ports10, 11, and 12. You may useother ports as well, but keep inmind you will need to changethe ezLCDinitI2c parameters ifyou do.

Before you continue, youneed to think about how you aregoing to mount the Workboard andthe external modules/connectors. Imounted mine to a 5” x 7” piece ofcompressed PVC. I used a narrowRJ11 jack for my outdoor network, asshown in Figure 2. This can beattached by screws or double-stickfoam tape.

The Workboard is attached using1/4” standoffs but could have beenattached without them.

STEP 1: Build the Dios WorkboardBasic as per the instructions includedwith the kit available from KronosRobotics (see Web Links). The onlymodification that you need to make isto add a TO-220 heatsink to theonboard 5V regulator. This is done bygently bending the regulator so that itis standing up. Once this is done, youcan slip the heatsink over the regula-tor as shown at the top of Figure 3.

Why do we need a heatsink anyway? We need to supply 14V to

the Hobby Boards barometer. In orderto do this, we need to supply at least16V to the DiosPro coax. This willyield approximately 14V to the inputof the 5V regulator. With the addedload of the display, as well as the outdoor 1-Wire network, the onboardregulator starts to get warm. Theheatsink will keep the temperatureswithin the operating range.

After building the board, plug inthe DiosPro and test the board as perthe included instructions.

STEP 2: To mount the LCD, we needto add a couple of headers and run afew wires.

Take a six-pin header and attach it to the pads marked RC2-RH2, asshown in Figure 4.

Next, take a 13-pin header andattach it to the pads marked XC4-XO4, as shown in Figure 5.

Now, take a second 13-pin headerand attach it to the pads marked YC1-YO1, as shown in Figure 5.

June 2007 31

BY MICHAEL SIMPSON

SCHEMATIC 1

FIGURE 2 FIGURE 3

Simpson.qxd 5/7/2007 2:18 PM Page 31

STEP 3: Take a small jumper and con-nect the pad marked RE1 and attach itto the pad marked, as shown in Figure6. Note this is the small green jumper.

Attach a jumper between RH1and one of the VDD pads, as shownin Figure 5. This is the white wire.

STEP 4: Attach two 1K resistors to the

pads shown andXH2 (see Figure7) and solder inplace. The tworesistors hold theezLCD001 SDAand SCL portshigh until pulledlow by theDiosPro. Sincethe interface tothe ezLCD is 3V,they are pulledhigh to a 3V reference provid-

ed by the display itself.

STEP 5: Connect the ezLCD001 I2CSDA port to Dios port 11. The padmarked XH1 is the I2C SDA port.Solder in place, as shown in Figure 8.

Now connect the ezLCD001 I2CSCL port to Dios port 10. The padmarked XI1 is the I2C SCL port, as

shown in Figure 8.

STEP 6: Connect a wire from YI2 to

port 12. This is the reset port onthe ezLCD001. The software willbring this port low each time thesoftware starts in order to reset the display.

Connect a 14-pin header tothe port pads, as shown in Figure9. Note this is the header on theleft side of the board. The headerwill give you access to I/O ports 0-12, as well as Vss.

Connect a 15-pin header tothe port pads, as shown in Figure9. This is the header on the rightside of the board and gives youaccess to I/O ports 13-25, as wellas Vss and Vdd.

STEP 7: Let’s perform a simple displaytest.

Without the ezLCD displayplugged into the Workboard, applypower to the DiosWorkboard via thecoax connector. This should bebetween 15V and 17V. If you are notgoing to use the Hobby Boardsbarometer module, you may use anything within the range of 7-16V.

Load Program 1 into the DiosPro.The file called LCDtest.txt is includedin the download files.

Power down the Workboard andplug the display into the six-pin and13-pin connecters and apply power tothe DiosWorkboard. The words“Hello World” should print onto the display in blue. If it does not, goback and check all your connectionsvery carefully.

Network ConnectorConstruction

For detailed information on 1-Wire and connec-tion techniques,check out theMarch installmentof the series called“Env i ronmenta lSensors.” We willbe running two 1-Wire networks offof the DiosPro.

32 June 2007

FIGURE 4 FIGURE 5 FIGURE 6 FIGURE 7

Program 1'EZLCD001 Test Programfunc main()

'Setup ezLCDezLCD1initI2c(11,10,12) 'Pass sda,scl and reset portezLCDLIGHTON()ezLCDCLS(ezWHITE)

ezLCDFONT(3) 'Large FontezLCDPRINTXY(30,10,"Hello World",ezBLUE)

endfunc

include \lib\EZLCDI2c.lib 'ezLCD001 Library

FIGURE 8

FIGURE 9

Simpson.qxd 5/7/2007 2:19 PM Page 32

The first will be our outdoornetwork. This network will runto our weather pole where allour outside sensors are located. The second networkwill run to a Hobby Boardsbarometer module which willform our indoor network.

Schematic 2 shows theconnections of the two net-works. Note that I added R3, a100 ohm resistor in series withmy outdoor network. I have200-300’ Cat3 cable run whichis the worst case scenario andthe resistor helps to reduceerrors. I actually placed theresistor inside the modular boxso it could be removed when Iupgraded the cable to Cat5.

I am also using I/O port 15to supply 5V to the pullup resis-tor R1. You could have tied theresistor to VDD, but this makesit easier to connect the resistorto the removable header.

Let’s start by adding a connection to a modular jackso that you can easily connectyour outdoor sensors to theweather station.

STEP 1: Take a snapable femaleheader and cut off a three-pin sectionand place it on the WorkBoard header labeled VSS, VDD, and P13. Solder a 1K resistor between theVDD and P13 leads, as shown inFigure 10.

STEP 2: Attach a 4” piece of blacktelephone wire to the lead labeledVSS, then attach a yellow wire to the lead marked P13, as shown inFigure 11.

STEP 3: Attach a modular jack to thebase you are using for the project.Most modular jacks come with foamtape for this. I used small #4 machinescrews to mount mine.

Attach the black wire (connectedto VSS) to the green wire on the connector. Attach the yellow wire(connected to P13) to the red wire onthe connector, as shown in Figure 12.

STEP 4: The connection to the indoornetwork is similar to the outdoor network. Start by cutting off a two-pin section from a female headerand slip it over ports 14 and 15.Solder a 1K resistor between the

two leads on this header then attach a 4” yellow wire to the lead connected to port 14, as shown inFigure 13.

STEP 5: Snap off a two-pin section

Microcontroller-Based Weather Station

June 2007 33

FIGURE 10 FIGURE 11 FIGURE 12

SCHEMATIC 2

Simpson.qxd 5/7/2007 2:20 PM Page 33

from a female header and slip it over the PWR header pins markedVIN and VSS. Next attach a 5” redwire to the VIN lead and a 5” greenwire to the VSS lead, as shown inFigure 14.

STEP 6: Attach the Hobby Boardsbarometer to your project base. Next attach the three red, yellow, andgreen wires to the board, as shown inFigure 15.

STEP 7: With construction complete,you need to remove the ezLCD display if it is attached and power-upthe Workboard.

Load the file named Networktest.txtthat is included in the download filesand program it into the DiosPro. Theprogram will display the status of thetwo networks.

When you plug your outdoor network into the modular jack, it should

report a good network.

Weather StationSoftware

Okay, all the hard work is done.The hardware construction is complete and tested. Now comes themost rewarding portion of the project.

I am going to take you throughadding the code for each sensor oneat a time so that you can customizethe software for your configuration. Aswe add each software component,you will see your weather stationcome to life.

The ezLCD display screen was difficult to photograph because theglass bezel on the display added amoiré pattern. In order to show youwhat the different gauges should look like, I created some drawings that actually came very close to theactual display.

You will need the registrationnumbers from all the devices on yournetwork so that you can paste them

into the appropriate rou-tines. If you don’t alreadyhave these numbers, loadand run the DiosPro filecalled Networksearch.txt.This program will displaythe registration numbers oneach of the networks in thedebug window, as shown inFigure 16.

Outside TemperatureSensor

Load up the file calledLCDweather1.txt. Take a

look at the file and you will noticethree sections in the program. Each ofthe programs that we are going toload have these three sections.

• Basic Setup — This is where the 1-Wire ports are defined, the timersare started, and the LCD is initialized.This part is the same for each of the programs we are going to load inthis section.

• Draw Gauges — Each of the gaugeshas to be drawn before they can be used. This is where we make a callto the function that handles the particular sensor we are adding to theweather station. In the case of theOutside Temperature Sensor, thefunction is called readthermometer.Also notice that we pass 0 as aparameter. This tells the function thatwe simply want to initialize and drawthe gauge.

• Main Processing Loop — Here wemake the same call to the processingfunction with a parameter of 1, whichtells the function to take a reading anddisplay the results.

Include FilesAt the end of the program, there

are a series of include files. These files contain functions that make up the weather station. The firstinclude file is called LCDtmp.lib. Thispoints to the file that actually containsall the routines that take the temperature readings and display the results. We will adding additionalLCD include files as our weather station progresses.

The second include file containsthe functions that set up the timers weneed for our weather station. Thereare six timers that we used for thisweather station. The timers run in thebackground and each one incrementsa global variable once every 10 milliseconds. We use these timerswith various modules to help us createplots and averages for the individualsensors.

The last include file is the ezLCDlibrary.

34 June 2007

FIGURE 13 FIGURE 14 FIGURE 15

FIGURE 16

Simpson.qxd 5/7/2007 2:21 PM Page 34

The Dios editor has a feature thatif you double click on an include filename, it will load that file into an editor form so that you can makemodifications to the file. Go aheadand double click the LCDtemp.libname. This will open up the file containing definitions for the outsidethermometer functions. Looking at theLCDtemp.lib file, you will notice atable entry called AAGTempROM:This defines the device registrationnumber. You will need to change thisnumber to match one of the DS1820thermometers on your outdoor network. The registration number willneed to be changed in each includefile to match those on your network.

Once the registration is changed,save and close the include file. Thenprogram the LCDweather1.txt program into the DiosPro. You shouldsee a thermometer on your displaylike the one shown in Figure 17.

Figure 17 actually shows threethermometers. The first is what thethermometer looks like when it displays a normal temperature. If theconditions are present to create aWind Chill, it will be displayed as athin cyan bar like the one shown on the second thermometer. If theconditions are present to create aHeat Index, it will be displayed as adark red bar like the one shown in thethird thermometer. Since we don’thave a humidity or wind sensor module loaded yet, you won’t seeeither of these two indicators, nor willyou see the Dew Point calculation.

Wind Speed SensorLoad up the file called

LCDweather2.txt. If you look at thefile, you will see that it is identical toLCDweather1.txt. The only differenceis that we added a call to the readspeed function to both the DrawGauges and Main Processing Loopsections. There is also a new includefile added called LCDspeed.lib. Goahead and open this file and edit the table entry in the readspeed function, then program the DiosProwith the file.

The wind speed gauge cluster has

three sections shown inFigure 18. The maingauge has a small hand that points tothe indicated speed. The numberabove this gauge is the actual speedwith a .1 mph resolution. These read-ings are actually averaged over thelast 30 seconds. The number in thesmall circle in the upper left hand of the display cluster is the gust indicator. If a gust is detected and thevalue is higher than the number thatis already displayed, it will replacethat number and reset an internal gusttimer. The timer also gets reset if thegust is the same as the one displayed.If no new gust is received that isgreater or equal to the one displayedover a five minute period, the indica-tor will be cleared.

Wind Direction SensorLoad up the file called

LCDweather3.txt. A new functioncalled readspeed has been added. Editthe LCDdir.lib file and make the registration changes to the table entry.The AAG wind direction uses theDS2450 Quad A-to-D device.

The wind direction gauge shownin Figure 19 takes a reading a coupleof times each second and displays thedirection the wind is blowing from.

Outdoor Humidity SensorLoad up the file called

LCDweather4.txt. Here we added thefunction called readhumidity. Thehumidity sensor uses a DS2438device.

You may have noticed small greenpips that were displayed near the center of the screen, as shown inFigure 20. These are sensor status indicators. When green, the sensor isworking properly; red indicates theyfailed on the last reading. It is normalto get an occasional error.

The pips represent the following sensors:

• Pip 1 — Wind Speed• Pip 2 — Wind Direction• Pip 3 — Temperature• Pip 4 — Humidity• Pip 5 — Barometer

Barometric SensorLoad up the file called

LCDweather5.txt. Here we added thefunction called readbar. The barome-ter sensor uses a DS2438 device andis on the indoor network. In additionto the table entry, you need to set theslope and intercept constants, as well.These are what you used when youcalibrated your barometer.

Figure 21 shows the barometergauge. The red plot line is a history ofthe last 24 hours. The blue plot line isa prediction for the next 12 hours. It isbased on the rate of change for thelast four hours. The blue number andweather prediction is based on the 12hour point on the plot.

The sensor is read once perminute and the red bar number is updated. The plot lines and prediction are only updated once perhour. The last 24

Microcontroller-Based Weather Station

June 2007 35

FIGURE 18 FIGURE 19

FIGURE 20

FIGURE 22 FIGURE 21

FIGURE 17

Simpson.qxd 5/7/2007 2:22 PM Page 35

hour settings are stored into theDiosPro built-in EEPROM. Thismeans if you reset the chip or have apower failure, you won’t lose yourprediction data.

HistoryAll the sensors have been added.

Now let’s add a bit more processing.

Load up the file calledLCDweather6.txt. Take

a close look at the program. I have anew set of functions called calchisto-ry. All the sensors that we haveadded use global variables to storetheir readings. The calchistory function takes the temperature,humidity, and average wind speedand plots them on the graph onceper hour, as shown in Figure 22. Thisway, the last 24 hours are shown. Inaddition to the display, these readings are stored in the DiosProsEEPROM so that if we have to reset the chip, we won’t lose thegraph information.

Final Thoughts

We covered quite a bit of material in this article. I understandthat many of you will want to build

a custom weather station and may not be using the exact sensorsthat I have used here. I will be glad to answer any of your questions to help you make your modifications.Please use our Weather Center and Home automation forum atwww.kronosrobotics.com/forums/viewforum.php?f=25.

There is plenty of unused space on the ezLCD display. In the future, I will be adding a raingauge, as well as moisture and variousother sensors.

I have been experimenting withthe SCP1000 available from SparkFun Electronics shown in Figure 23.This is one accurate pressure sensorand can track barometric pressure tothree decimal points. It’s faster andmore accurate than the 1-Wire sensors. It also has an onboard temperature sensor. This particularmodel uses a two-wire I2C interfaceand a complete Dios library is available. If you decide you want to use one of these, check out theapplication note on the Kronosrobotics website at www.kronosrobotics.com/Projects/SCP1000.shtml.

What’s Next

Next month, I am going to look atadding a couple remote Zigbee unitsto the sensors on our weather pole.This will make our weather stationtruly portable.

All the source code is available fordownload at www.kronosrobotics.com/Projects/weathermicro.shtml. NV

36 June 2007

FIGURE 23

PARTS LIST EarthLCD ezLCD001hhttttpp::////ssttoorree..eeaarrtthhllccdd..ccoomm//LLCCDD??sscc==77&&ccaatteeggoorryy==229977

HOBBY BOARDS DS18S20 1-Wire Temperature Sensorwwwwww..hhoobbbbyy--bbooaarrddss..ccoomm//ccaattaalloogg//pprroodduucctt__iinnffoo..pphhpp??ccPPaatthh==2266&&pprroodduuccttss__iidd==9933

Barometer Module (B1-R1-A) — wwwwww..hhoobbbbyy--bbooaarrddss..ccoomm//ccaattaalloogg//pprroodduucctt__iinnffoo..pphhpp??ccPPaatthh==2222&&pprroodduuccttss__iidd==3366

Humidity Module (H3-R1-A) — wwwwww..hhoobbbbyy--bbooaarrddss..ccoomm//ccaattaalloogg//pprroodduucctt__iinnffoo..pphhpp??ccPPaatthh==2222&&pprroodduuccttss__iidd==4466

AAG Weather Instrument — wwwwww..hhoobbbbyy--bbooaarrddss..ccoomm//ccaattaalloogg//pprroodduucctt__iinnffoo..pphhpp??ccPPaatthh==2222&&pprroodduuccttss__iidd==9922

SPARK FUN ELECTRONICS SCP1000wwwwww..ssppaarrkkffuunn..ccoomm//ccoommmmeerrccee//pprroodduucctt__iinnffoo..pphhpp??pprroodduuccttss__iidd==88116611

KRONOS ROBOTICS DiosPro 40 chipwwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166116688

DiosWorkboard Basic

wwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166445533

14V DC Adapterwwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166550000

36-Pin Female Headerwwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166229911

40-Pin Male Headerwwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166229900

TO-220 Heatsinkwwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166225500

1K Resistorswwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166117788

Expanded PVC 5x7wwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//pprroodduucctt..pphhpp??pprroodduuccttiidd==1166443322

Free Dios Compiler (Includes ezLCDand 1-Wire libraries) — wwwwww..kkrroonnoossrroobboottiiccss..ccoomm//ddoowwnnllooaaddss//DDiioossSSeettuupp..eexxee

OTHER RJ11 Surface Mount Box — I used aGE TL26101. Can be purchased frommost home centers.

WEB LINKS Hobby Boardswwwwww..hhoobbbbyy--bbooaarrddss..ccoomm

Spark Fun Electronicswwwwww..ssppaarrkkffuunn..ccoomm

Kronos Roboticswwwwww..kkrroonnoossrroobboottiiccss..ccoomm//xxccaarrtt//ccuussttoommeerr//hhoommee..pphhpp

EarthLCDwwwwww..EEaarrtthhLLCCDD..ccoomm

Simpson.qxd 5/7/2007 2:22 PM Page 36

And that’s inaddition to theindustry-bestpricing youalready get at Jamecoevery day!

You alreadyknow aboutJameco’sbest-in-the-business

low pricing...Now we’re

out to get a newmessage across:Major Brands—atJameco pricing!

To dramatize thepoint, we’re giving

you an additional 15% discount on twodifferent major brands each week. Fromnow through the end of May!

And that’s on top of oureveryday discounted pricing!

We wanted to make thisso good a deal that you justcouldn’t pass it up. So... Want to know whichtwo major brands you can

save extra-big on this week? Just headto the website...

WINBIG

G r e a t P r o d u c t s . A w e s o m e P r i c e s .

www.Jameco.com/NVS

EVERYWEEK

— AT —

JAMECO

• T.I. Semiconductor

• Augat/Tyco • Bourns

• CTS • Cypress

• C&K Switches

• Comair Rotron

• Condor • Grayhill

• Intel • Micron

• Philips • Power-One

• Raychem/Tyco

• Renesas • SanDisk

• Toshiba

• Vishay Siliconix

TAKE AN

EXTRA15%

OFFON 2 NEW

MAJORBRANDSEVERY WEEK!

SEEWHO’S UP

THIS WEEKGO TOTHE WEBSITE

Every week, Jameco is

giving extra discounts on

major brands like these:

• AlcoSwitch • AMP/Tyco

• Dallas Semiconductor

• Intersil • Maxim

• Microchip • Molex

• Panasonic • AVX

• Fairchild Semiconductor

• Tyco • Aromat

• Aavid Thermalloy

• Atmel • ST Micro

June 2007 37

Full Page.qxd 5/9/2007 3:05 PM Page 37

Seven-segment LEDs still havesome advantages over the LCD

displays that are very popular now.They are self lighting, large, and easyto read (like from across the room.)They are inexpensive, don’t requirecomplicated voltage converters forfussy backlit displays and toleratewide temperature ranges (LCDsdon’t work too well below freezingwhile LEDs are quite happy operat-ing there.)

Many of the seven-segmentdesigns that I’ve seen drive all eightof the segments (seven plus the decimal point) of a digit at the sametime. The problem is that there canbe quite a bit of current sourcedthrough the common connection of

the digit.One thing I noticed

in existing PIC designswere four PNP transis-tors tied to the anodesof a typical four digitdisplay. This is to manage the worst casecurrent draw. For exam-ple, the display that Iuse typically drawsabout 5 mA per seg-ment. Multiply that by 8and you have 40 mA of

current being sourced to each digit.A PIC can only source or sink a max-imum of 25 mA through any singleoutput pin. So the PNP transistorsare used as current amplifiers.

But if we only drive part of thedigit at a time, we can cut down the total current requirement! I wondered if I could wire the displayso the PIC sources and sinks only asingle segment each pass. Wouldthe duty cycle for each segment betoo low, causing the display to bedim? I did a little bit of math andcame up with the following:

1/(4 digits * 8 segments/digit) *60Hz(a good refresh rate) = about

500 microseconds

That’s no problem for a PIC running the internal oscillator, especially since the only other thingthat it’s doing is reading charactersfrom the serial input. Still, that’s onlyabout a three percent duty cycle.Would that be enough?

Let’s see what we have to do.For an LED, we have a diode (lightemitting diode, remember?) A diodeonly conducts current when theanode is positive and the cathode isnegative. Further, the anode voltage

THE MUX MUX

LLIIGGHHTTDDIISSPPLLAAYY

I needed a seven-

segment remote

display that received

its data from RS-232,

and I wanted it fast.

Here’s a little project

that can be built in a

weekend and will give

you four digits of

information.You can

use either common

anode or common

cathode seven-segment

displays without

changing the hardware!

I also wanted to use a

PIC microcontroller for

it in Figure 1.You’ll see

what I wound up with.

38 June 2007

How to Light a Display OneSegment at a Time

FIGURE 1

Satterlee.qxd 5/7/2007 10:44 AM Page 38

must be greater than the forward voltage of the diode (usually 1.7-2.0V).Also, there is little current flow (practi-cally none) when the diode is reversebiased, or when the cathode is morepositive than the anode.

Since I’m using a common anodedisplay, each digit has a single connec-tion to each of the anodes of the seg-ment. The cathodes of each segment ofthe digit are connected to the cathodesof the other digit’s segments. So bysourcing current in one chosen anodeand sinking current in one or morecathodes (segments), a single digit canbe lit on the display. By sourcing current in a different anode, anotherdigit is lit. By doing this rather quickly,persistence of vision makes it seem thatall digits in the display are lit at once.

If either the anode voltage is lowand/or the cathode voltage is high,then there is no current flow, and nolight from the segment. So if the circuit drives one of the anodes high,then optionally walks a zero thougheach one of the cathodes, we canhave the display turn off and on eachindividual segment. If we turn on onlythe desired segments in rapid enoughsuccession, then we can have the display show four unique digits at minimum current draw.

Furthermore, if we limit the currentto what each PIC pin can tolerate, we

can get rid of the PNPtransistors all together.We will still need a current limiting resistorthough. The forwardcurrent specification ofan LED is for continu-ous (DC) levels, but if we have a dutycycle, we can increasethe amount of currentthrough the device.Since we are trying a3% duty cycle, we can pass close tothe maximum current from a PIC output through the LED. We just haveto be a little careful when debuggingthe code and not leave a segmentstuck in the on position for too long.

So now we have the verbaldescription of the problem. Oh wait,there’s something else (isn’t therealways?). I want a small form factor forthe circuit without a lot of space takenup around the display itself. But I stillwant to use through hole design, notsurface mount. It might be good tohave an optional power supply on theboard, too as you never know whattype of power we will have around.

Now we have all of the require-ments for the design. I’ve got a collec-tion of four digit common anode, seven-segment displays that I bought fromRSR Electronics. In quantity 10, they are

$1.25 each, which is not too bad. Thedigits are about a half inch high andhave a right hand decimal point aftereach digit. They didn’t come with anyspecs, but a low voltage power supplyand a series resistor showed what thepinouts of the display are (Figure 2).

Now, what if you have troublefinding common anode displays (seethe Finding an LED Display sidebar)?There are common cathode displaysout there with segments and digits

June 2007 39

BY RICHARD SATTERLEE

FIGURE 2

FOUR DIGIT, 12 PIN

LED CONNECTIONS

1 — Segment E 12 — DIGIT 42 — Segment D 11 — Segment A3 — Decimal Pt. 10 — Segment F4 — Segment C 9 — DIGIT 35 — Segment G 8 — DIGIT 26 — DIGIT 1 7 — Segment B

LED displays don’t seem to besourced by the “old name” OEMsmuch anymore. I don’t know why, butI couldn’t find references to them inmany of the mail order catalogs that Ilooked at.

I think that one of the originalparts offered was the MSQ6911C fromFairchild. Fairchild has since sold theirline to Everlight so you can find docu-mentation for that part at either site.

In the article, I made reference to adisplay (or a bunch of them) that I pur-chased from Electronix Express. Theirstock number is 08FYT5641B. Thesedevices have a part number of FYQ-5641 B on them. I Googled this num-

ber and came up with a few hits on thesearch — all in Russian! After lookingat the datasheets at wwwwww..rrcctt..rruu (thetitles were not readable, but fortunate-ly schematics and ratings are), it surelooked like the right part. So, althoughI didn’t have the name of the vendor,I was on the right track. These are common anode displays.

A broader search on Google witha reference to just 5641 brought up alot more hits.

Futurlec sells a part with a reference of 7FR5641BS. This lookslike it would sure work.

Hobby Engineering has a partH2276 that cross-references to

Fairchild MSQ6911C.Jameco has a couple of parts that

will work. The orange display (JamecoP/N 335185PS) has a higher luminosi-ty than the green display that they ref-erence as 335193PS. The green displayis a little dim in a brightly lit room withthis design. I’m sure that it wouldwork well with more current through itand/or a higher duty cycle. It’s usable,just not very bright in this application.

So, you have a variety of optionson getting one of these displays. In the article, I discuss using either common anode or common cathodedisplays and you can also use eitherred or green.

FINDING AN LED DISPLAY

Satterlee.qxd 5/7/2007 10:44 AM Page 39

going to the same pins. The only prob-lem is that the direction of the LEDsare reversed, but that’s just a codechange for the PIC. We just reverse thelevel on the outputs on the same pins.If you want a segment to light, you stilljust apply a positive to the anode(which is on the same pin as a cathodefor the common anode design) and anegative to the cathode (which is onthe same pin as an anode on the com-mon anode design). I know it sounds abit strange, but look at Figure 2 andreverse the direction of the diodes.Then pick a segment and a digit andapply the logic levels. I’ve allowed foreither in the code (more on that later).

I have a collection of 16F648A PICmicrocontrollers. I bought these at aquantity 25 price break and they are mylittle “go to” microcontrollers. The designcould also use the 16F627 and 16F628

parts. The -A models just have twice asmuch program Flash memory and theyonly cost a couple of pennies more thanthe lower capacity parts, so I typicallyuse these. But if you have some of theother parts, by all means, change theconfiguration word and the processortype in the source code and use those.

For little designs like this, I oftendo the printed circuit board designfirst and then do the schematic. It’s alittle backwards, but allows for somemuch simpler layouts. I first lock outthe special pins of the PIC (like MCLR,the RS-232 pins, RB4, power, andground). Then with the pins left over, Iconnect to the display. To keep thesmall form factor for the board, Imounted the display on the solderside of the board and the rest of thecomponents on the other side. Thismeans that I could put the PIC inside

the footprint of the display. With a little bit of thought, I got a single-sidedboard without a jumper.

After doing the layout, I generatedthe schematic (see Schematic 1). Thereare four current-limiting resistors foreach of the anodes, the microcon-troller, and a simple inverter made froma 2N2222 or other general-purposeNPN transistor. This is required for thePIC’s serial input. The signal must beinverted (have a low true signal for thestart bit). Note that this inverter circuitis not within RS-232 specs, however Ihave used this circuit with many differ-ent serial interfaces without a problem.The power supply is just a full bridge linear regulator design, and without it,there is only the PIC, one transistor, thedisplay, and seven resistors. That’s apretty low parts count!

After the schematic was done, I

40 June 2007

1RA2

2RA3

3RA4

4MCLR/RA5

5Vss

6RB0

7RB1

8RB2

9RB3

18RA1

17RA0

16RA7/OSC1

15RA6/OSC2

14Vdd

13RB7

12RB6

11RB5

10RB4

U1 16F648A

R7

R5

R4

R310K

R6

+5V

NC

NC

+5V

R110K

3

2

1

2N2222Q1

R2

5.1K

D4

D3

D2

D1

ACIN

ACIN

RS232-IN

GND

GND

IN OUT

7805GND

1

2

3

VR1

DCIN

5VDC

+5V

12

C1470 uF

C2

0.01 uF

C3

0.01 uF

+5V

4 DIGIT7 SEGMENTLED DISPLAY

OPTIONAL REGULATEDPOWER SUPPLY

7B

13A

12F

1E

2D

3DP

4C

5G

12CA4

9CA3

8CA2

6CA1

120

120

120

120

1N4148

1N4148

1N4148

1N4148

SCHEMATIC 1

Satterlee.qxd 5/7/2007 10:45 AM Page 40

could then do the register map for the PIC program and Icould start writing code. I’ve done several PIC projects, so Ihave snippets of code that I have used to initialize Timer0and the USART. I’ve specified 9600 baud for the serial inputbut you can modify the code to support the baud rate ofyour choosing. The code uses Timer0 for the time betweendisplay changes; I choose around 500 µs for a flicker freedisplay. The register map is:

; **************************************************; PORT A & B I/O definitions for 16F648A version;; BIT 7 6 5 4 3 2 1 0; PORTA DP c MCLR NC f a e d; PORTB g CA4 CA3 CA2 CA1 NC RS232 b;;**************************************************

where DP is the decimal point, a-g are the segments, and CA1-CA4 are the digits. Note that my configuration has the leftmost digit as CA4 while most documentation has it as the rightmost. I doit this way in case I have three digit displays. NC stands for no connection.

There is an assembler define statementthat selects either common anode or common cathode displays. If you have a common cathode display, comment out the #define COMMON_ANODE statement and reassemble.

All the real work of the code is done inthe interrupt service routines. WhenTimer0 generates an interrupt, the codegoes to the next segment to light or notlight, as required. Let’s look at a portion ofthe code to see how we multiplex the display. We will use the common anodedesign. The code is listed in the LEDSegment Selection sidebar.

The segments are stored in an array in general-purpose registers fromseg7digit to seg7digit+3 where each byterepresents a digit. There is a pointer (modulo 4) named this_digit, which rollsfrom 0, 1, 2, 3, 0, 1... and selects whichdigit we will display. The pointer plus theoffset address to the base of seg7buffer isadded together and put in the field selectregister (FSR). The contents of the registerpointed to by the address in the FSR is read from memory using the INDR(indirect register) and placed in the W register. Then this value is held in the register, decoded_digit. This has all eight segments for the current digit we are displaying.

There is also a bit mask register named this_segment.This has the “bit selector” for the or operation to isolatethe bit, by shigting a zero through a field of ones. Theresult of the logical-or operation is mostly ones. For theselected bit, and the decoded digit, if both bits are low,then the output of that bit will be low, driving the cathodefor that segment low and the ones in the other bits willleave the other cathodes high (hence, no current will flow). So, we will have, at most, only one segment litat any one time.

For the common cathode design, the voltage levels arereversed, so we have to perform a logical-and function in afield of ones with a mask of mostly zeros. The result of theand operation is mostly zeros. For the selected bit and the

The Mux Mux Light Display

June 2007 41

LED SEGMENT SELECTION

NOTES:1) Only the common anode code is shown for clarity. Refer to the sourcecode for additional details.

2) The seven-segment values have been stored in seg7digit buffer, NOTbcd values. They are converted while in the serial interrupt service routine.

3) Turning on the common anodes is done outside this code and is not shown.

;————-; update the LED display with the new values.; this is done on about a 500 microsecond rate to allow for all; 32 iterations through the display. ;————-; set up to do the next segment

bsf STATUS,C ;set carry bitrlf this_segment,F ;set up next segmentbtfsc STATUS,C ;see if we have rotated throughgoto led_update100 ;still working on this digit

; here if we have rotated through all segments of the current digit; set up for next digit.

movlw B’11111110’movwf this_segmentincf this_digit,Fmovlw B’00000011’andwf this_digit,F ;modulo 4 incrementmovf this_digit,W ;hold digit as pointer offsetaddlw seg7digit ;add in offsetmovwf FSR ;use FSR for buffer selectmovf INDF,W ;hold digit in Wmovwf decoded_digit ;hold onto value

; Turn off all cathodes and anodes in PORTBled_update100:

movlw B’10000001’movwf PORTB

; Do PORT A; Turn off ALL cathodes PORTA

movlw H’FF’movwf PORTA

; Turn on the selected segment on the displaymovf this_segment,W ;get the desired segmentiorwf decoded_digit,W ;and with decoded digitmovwf decoded_segment ;and hold it

Satterlee.qxd 5/7/2007 10:45 AM Page 41

decoded digit, if both bits are high,then the output of that bit will also be high, driving the anode on for that segment.

After setting the cathodes in bothoutput ports, the turn_on_anode subroutine is called. This routine thenturns on one and only one of theanodes based upon the digit number.This routine is found at the start of program memory as it uses a comput-ed goto for its operation. The PIC isprogram-page sensitive when doingcomputed gotos, so I usually stickthem at the beginning of memory toavoid page faulting.

If we are using a common cathode, the turn_on_cathode subroutine is called. This routine turnsthe cathode zero rather than theturn_on_anode, so it is now sinkingcurrent.

If the zero from this_segment is rolled into the carry bit, we knowwe have finished all eight segments of this digit. We reset the mask andput the next digit value into decod-ed_digit. For the common cathode,it’s a one in a field of zeros, so if we

rotate a one intothe carry, we are

finished with this digit.The process continues

each time we have a Timer0interrupt.

The code also consists ofan interrupt service routinefor a character beingreceived from the USART.Refer to the source code forall of the details but it’s pretty standard in design:when the USART interrupts

with a character received, the interrupt service routine first checksto see if there has been an error in transmission, in which case, thecharacter is ignored. The character isthen checked for either a period,blank, or a minus ASCII value. If it isa period, then the decimal point ofthe last digit (rightmost) is cleared,which will turn the decimal point on,and no shifting of the buffer is done.If the character is a blank, then the code will put all ones into a register named charin. Similarly, if thecharacter is a minus, then the codewill put a value with the “g” segmentlit into the register charin.

If neither a period, minus, orblank, then we range check the char-acter for an ASCII value of 0 through9. If outside this range, then the codeignores the character. If it is in range,the code converts the ASCII characterinto a BCD value then calls the subroutine bcd_2_7seg again found inthe beginning of program memory.This computed goto routine convertsthe BCD value into its correspondingseven segment value. The code will

hold this value in charin.Finally, the seg7buffer

is shifted left one digit and the decoded valueheld in charin is put into the rightmost digit buffer.(The entire program may be downloaded from theNuts & Volts website atwww.nutsvolts.com)

Code in hand, Ithought I’d best check outthe idea on a prototype

board. I used one of those push-intypes and you can see the results ofthis rats nest in Figure 3. Not pretty,and might be prone to open circuits,but should test the theory of opera-tion without having to go through a lotof fabrication for nothing. In fact, I leftoff the serial input inverter and justloaded up the seg7digit buffer with allzeros. This will turn ON all the cathodes and have the display showall 8s with their decimal points set.

This showed that the display wasindeed bright enough and that the180Ω resistors were an adequatechoice. Well, not quite. I found agreen common cathode display and itwas not very bright. Throwing a littlemore current through each segmentwith 120Ω proved to be much better.

Construction of the printed circuithardware is straightforward. If youhave a DC supply, there’s no need to have the bridge rectifier and filtercap. If you have a 5V DC power supply, there is no need for the 78L05voltage regulator, so you can leavethat out, too.

When assembling the board, Isuggest that you use a cut up machinepin socket for the display. Cut thissocket and remove any supportingholders for the rows to have two six-pin single inline sockets. Put thesein the display and put the wholeassembly in the board. Raise theassembly with a couple of toothpicks(Figure 4) and you should be able tosolder to the pads.

After the single inline socketshave been soldered, remove the display from the sockets and continuewith the assembly. No need for a regulated supply for me, so the component view (Figure 5) does nothave it populated.

After programming, the PIC needsto be inserted into the board andpower applied. Nothing should happen, so don’t panic. That’s whatit’s supposed to do!

After the smoke test, you can connect up a serial output port forcontinued testing. You can useHyperterminal under Windows orMinicom under Linux. Both use the

42 June 2007

FIGURE 3

FIGURE 4

Satterlee.qxd 5/7/2007 10:45 AM Page 42

serial port of a PC as a terminal emulator. Configure the terminal program for 9600 baud, 8N1. (Notethat after configuring the baud rate inthe terminal program you may have toexit the program and restart it for thebaud rate to go into effect.)

Because I haven’t mentionedwhich pins on the serial cable to connect to the board, some cableshave their transmit and receive datalines crossed. For a DB9 type connector, tie pin 5 to the ground ofour board. Jumper pin 2 of the DB9to the base resistor of the invertertransistor. With a logic probe on thecollector of the transistor, hit a couple of keys on the keyboard. Ifthe logic probe shows that the collector pulses low, then you havethe right pin. Otherwise, try theprocess again with pin 3 of the DB9.One or the other should work. If not,connect pins 2 and 3 together andtype on the keyboard. You shouldsee characters on the screen. If not,there is something wrong with theterminal program. Otherwise, a bit oftroubleshooting is required on theboard around the inverter.

If you have figured out whichDB9 pin to use, then you should beable to type in any of the followingkeys and see the results show up onthe display. If characters 0 through 9are typed, you should see them oneat a time left shifted one digit eachtime a key is pressed. If you type a blank (space bar) after you havetyped a digit, you should see a blank digit in the rightmost positionand the visible digit shifted left oneposition.

If you type a period, the displaydoes not shift left by one, but the decimal point for the rightmost digitwill be lit. The lit decimal point will follow that digit to the left as addition-al characters are typed in.

Finally, you can type a minus signand it will show up in the rightmostdigit position. That’s about it for the operation.

The software on your PC, single board computer, or dedicatedmicrocontroller can now send

numerical data to this remote display in anotherpart of your houseor office lettingyou keep an eye on importantinformation! NV

The Mux Mux Light Display

FIGURE 5

June 2007 43

PARTS LIST REF QTY DESCRIPTION C1 1 470 µF electrolytic (optional) C2 1 0.01 µF 25V (optional) C3 1 0.01 µF 25V D1-D4 4 1N4148 diode (optional) Q1 1 2N2222 or general-purpose NPN R1,R3 2 10K Ω 1/4W carbon resistor R2 1 4.7K Ω 1/4W carbon resistor R4-R7 4 120Ω 1/4W carbon resistor U1 1 PIC (select one): 16F627(A), 16F628(A), 16F648AV R1 1 78L05 +5V regulator (optional)

1 Common anode or common cathodefour digit, seven-segment display

Satterlee.qxd 5/7/2007 10:46 AM Page 43

QUALITY PRODUCTFAST DELIVERYCOMPETITIVE PRICING

9901 W. Pacific Ave.Franklin Park, IL 60131

Phone 847.233.0012Fax 847.233.0013

www.pulsar-inc.com • [email protected]

PRINTED CIRCUIT BOARDS

* Aluminum Backed PCB* Single & Double sided* SMOBC/RoHS* LPI mask* Through hole or SMT* Nickel & Gold Plating* Routing or scoring* Electrical Testing* Artwork or CAD data* Fast quotes* Flex Circuits

10 pcs (3 days) 1 or 2 layers $249

10 pcs (5 days)4 layers $695(up to 30 sq. in. ea.)

includes tooling, artwork, LPI mask & legend

We will beat anycompetitor’s prices!!!

SHOWCASESHOWCASE

OceanServer provides tiny, low-cost digital compass products for uses in precision heading or attitude sensing applications. Compasses are tilt-compensated in three axes, incorporating highly accurate MEMs two-axis accelerometers. Serial or USB interconnect options simplify system integration. Compasses provide reliable heading, roll, pitch, and optionally depth reading when connected to standard pressure transducers.

OceanServer Technology, Inc. (508) 678-0550www.ocean-server.com

Evaluation Kits

$299.00

5 Amp Smart Battery ChargerFor Gel-Cell or Lead Acid Batteries

The Model 155 chargermaintains large batteries:marine, auto & deep cycle.Features include a precisiontemperature trackingvoltage reference and threemode charging sequence.May be left connected, willnot overcharge. If a load is applied, the charger willcontribute it’s bulk currentto the load. When the loadis removed, charger current will flow into the battery. Not aswitcher! Low RF noise linear charger. Good for Radio UseSee review by W1ZR in MAR 04 QST. Input 120 VAC. Output13.8 VDC. Weighs 10 lb, 7“W x 8”D x 4 3/4”H. Custom unitsand various output cables available, see website for details.

Assembled & Tested (Order #155-ASY)........ $149.95CA Residents add 7.75% sales tax. S & H $12.50 to US 48 (insured)

AK, HI and Foreign Orders, please contact us for details

w w w . a - a e n g i n e e r i n g . c o m

2521 W. LaPalma #K • Anaheim CA 92801 (714) 952-2114 • FAX (714) 952-3280

Showcase-ReadFeed Jun07.qxd 5/10/2007 11:42 AM Page 44

SHOWCASESHOWCASE

June 2007 45

electronics. The inverter you mentioned inyour email most likely has plenty of powerto start and run your furnace. Some considerations about inverters are:

1. Zero or no-load power consump-tion. In other words, how much powerdoes this inverter draw from a batterywhen it is simply "on" and not carrying aload. Less expensive inverters will drawanywhere from one-half to one amp ofstandby current, so if you leave it permanently connected to a battery, it will eventually draw the battery down tonothing unless you are charging it with acharger capable of supplying more thanthat current. Of course, you can simply dis-connect the inverter from the battery whenit is not in use to eliminate this problem.

2. Sine wave or modified square waveoutput. Less expensive inverters employ adigitally-generated approximation of a sinewave at the output. Most AC fan motors areinductive motors and may be particularabout the "quality" of the power theyreceive, especially when starting up. Mygeneral experience is that inverters madetoday are good enough to start even themost picky inductive motors, provided youhave enough headroom in the power ratingof the inverter you choose. A general rule-of-thumb is if you choose an inverter ratedfor 200% or more of the motor's power rat-ing, it will probably start reliably. Fan motorshave a fairly limited load on them (usually asquirrel cage fan) and are easier to start thansay, a refrigerator or air-conditioner motor.

3. Battery life. You want your battery

to be available and up-to-snuff when youeventually need it. This requires putting aquality charger on it — one with a fullyautomatic cutoff — and you will need tooccasionally check on it to make sureeverything is working properly and thewater levels are correct, etc.

So, in the end, you should find your-self a decent battery charger, deep-cyclebattery, and inverter, and with the breakoutbox I described in the article, you shouldbe able to switch over to battery power onyour furnace in less than 10 minutes. Iwould not recommend leaving the furnaceon the inverter as a permanent installation,as this may be hard on your battery, invert-er, and possibly your furnace fan motor(s).

I will consider a separate article on

inverters for the future — thanks for the suggestion!

Kenton Chun KE4IEF

READER FEEDBACK

USA Office: 14019 Whispering Palms Dr.Houston, TX 77066, PH. 281-397-8101 FAX: 281-397-6220

Mexico Plant: Alamo 93, 4o. Piso, Sta. Mónica, Tlalnepantla, Edo. de México 54040

PH: 011 52-555 360-3648 & 011 52 555-361-3351FAX: 011 52-555 361-5996

Blink Manufacturing

Automatizacion, Ensambles Y Cir. Impresos, S.A.C.V.

Site: www.vandvmachy.comEmail: [email protected] or

[email protected]

Continued from Page 9

DOWNLOAD the HIDmaker FS Test Drive today!

www.TraceSystemsInc.com

301-262-0300

NEW! HIDmaker FS for Full Speed FLASH PIC18F4550

Creates complete PC and Peripheralprograms that talk to each other overUSB. Ready to compile and run!

• Large data Reports• 64,000 bytes/sec per Interface• Easily creates devices with multiple

Interfaces, even multiple Identities!• Automatically does MULTITASKING• Makes standard or special USB HID

devices

NEW! “Developers Guide for USB HIDPeripherals” shows you how to makedevices for special requirements.

Both PC and Peripheral programsunderstand your data items (even oddsized ones), and give you convenientvariables to handle them.

PIC18F Compilers: PICBASIC Pro,MPASM, C18, Hi-Tech C.

PIC16C Compilers: PICBASIC Pro,MPASM, Hi-Tech C, CCS C.

PC Compilers: Delphi, C++ Builder,Visual Basic 6.

HIDmaker FS Combo: Only $599.95

Showcase-ReadFeed Jun07.qxd 5/10/2007 9:51 AM Page 45

Why Use Cores?

The field induced in a ferro-magnetic core by an appliedcurrent can be thousands of times higher than that generated inair by the same winding. Inductorswith iron-dust or ferrite cores are much smaller than air-coredones as they store more magneticenergy in the same space. Theyneed fewer turns of wire so theirresistive losses are lower, leading toa higher Q.

Such cores have three disad-vantages. One is that if the corematerial conducts, it behaves like aresistive secondary winding andabsorbs input power. Most coresare made either from high resistivitymagnetic solids such as a ferrite orfrom very fine iron dust in a non-conducting matrix. Cores intendedto reduce high frequency interfer-

ence and oscillation arelossy and are unsuitable fortuned filter or DC-DC converter applications.

With a core, inductancedepends on the current flowing. It’s high for smallcurrents but falls enormouslywhen some threshold — the

saturation current — is reached.Some cores remain magnet-

ized after the current drops tozero. This effect is known as hysteresis. Early computers usedtiny two-state cores to store data bits. At one time DC-DC converters used hysteresis to control their oscillation frequency.My unknown cores might havebeen intended for that use.

B-H Curves

Saturation and hysteresis canbe explored by displaying a core’sB-H curve on an oscilloscope. This curve plots the relationshipbetween the magnetic intensity (H)applied to the core and the result-ing magnetic flux (B) in the core. Itcan be displayed on an oscilloscopeswitched to its X-Y display mode. Ina toroid, H equals NI/L. N is thenumber of turns, I is the current,and L is the mean circumference of the toroid. Here, N and L don’t change so H is proportionalto the current.

In this tester, the inductor current is swept linearly above andbelow zero. This current also drivesthe oscilloscope’s X input. The Yinput is made proportional to themagnetic flux. This, as I’ll explain, isnot measured directly.

In air B = H and the B-H curve

PROBING

CCOORREESS

Some time ago, I builta handy self-contained

inductance meter(What the L is it?, Nuts& Volts, August ‘05). It

works well, but itregistered nothing

when I tested someinductors I’d picked up

at a hamfest. I set upmy old standby — aparallel capacitor, a

signal generator, and anoscilloscope — and found

these inductors wereextremely lossy.As their

cores were wound frommetal tape, I wondered

if they were designedto have square-loop

characteristics.

I put together adevice to display

their behavior.Here it is.

Build an Oscilloscope AccessoryThat Displays the B-H Curves ofInductor Cores

FIGURE 1. The B-H curveof a just-saturating 470 uHinductor.

46 June 2007

Napier.qxd 5/7/2007 11:13 AM Page 46

is a straight line with unit slope. The ratio B/H is the relative permeability of the core. It may be as low as five in some dust cores and as much as 5,000 in ferrite cores. The curve is now much steeper; the oscilloscope’s Y gainmust be readjusted to create a reasonable display.

Typical core materials show astraight line which curves towardsthe horizontal at both ends (seeFigure 1). The curved tips show the core’s permeability falling at high currents.

Using the Curves

In many DC-DC converters, aconstant voltage is applied to an inductor. Initially, the currentincreases linearly with time, storingenergy in the inductor. When thecurrent reaches the saturation level,the inductance falls and the rate ofcurrent increase rises. This increasedcurrent stores little additional energy in the inductor but may damage the switchingtransistor. In DC-DCconverters, inductorsnearly always oper-ate below their saturation level sothis level is essentialdesign information.

Low-loss corematerials have a B-Hcurve in which the positive- and negative-going curvesalmost match. A loopwith a gap betweenthe two traces, as inFigure 2, reveals bothcore losses and resid-ual magnetization. I’dwound this inductoron a large ring usedas an interferencesuppressor in an

old keyboard.

The B-HInstrument

For clarity, I’ve splitthe tester schematicinto the ramp currentgenerator (Figure 3)and the core analyzer(Figure 4). The partnumbers are sequential across bothfigures.

The current ramp drives theinductor under test with equal positiveand negative peak currents. These areadjustable up to 0.5 amps with switchSW1. A one ohm resistor (R18) inseries with the inductor measures theactual current flowing and suppliesthe horizontal (X) sweep signal for theoscilloscope.

It isn’t practical to directly sensethe flux in the core so it’s calculated

from the coil voltage. Since the rateof current change is constant, thisvoltage is proportional to the coil’sinductance. With a pure inductor, itwould be a square wave with positiveand negative values proportional tothe inductance times the rate of change of the current. If the permeability changes, then so doesthe inductance and the voltagechanges accordingly.

For the oscilloscope’s vertical (Y)input, we want a voltage that rises

June 2007 47

BY TOM NAPIER

FIGURE 2. This noisefilter toroid won’t make ahigh-Q inductor.

FIGURE 3. The rampcurrent generator.

Napier.qxd 5/7/2007 11:14 AM Page 47

linearly to match the increasing current. This is achieved by feedingthe inductor voltage to an integrator.This cancels the differentiation of the input current by the inductor. The result is a curve whose sloperepresents the permeability.

In an integrator, any input offsetcauses the output to grow withoutlimit. As there should be no net DCvoltage across the inductor, the meanY voltage must be zero. This is emulated by placing a 1 megohmresistor (R24) across the integratingcapacitor. This doesn’t materially alterthe displayed curve but any net DC Youtput should be ignored.

Real Inductors

Any real winding has some resist-ance so the voltage across an inductorhas a term proportional to the drivecurrent. Since the X voltage is a linearfunction of the current, we can sub-tract a little of it from the coil voltageto correct for the winding resistance.VR2 lets you make this adjustment forwindings up to 2.5 ohms. Switch SW1has a calibration setting which appliesa current square wave to the inductorunder test.

With the oscilloscope in its normal mode, the resulting Y outputshould also be a square wave. Any tilt

in its horizontal sections reveals aresistive imbalance that should betrimmed out. In practice, I found Icould adjust VR2 to give a plausible B-H display in the normal test mode.Loops whose tips cross themselvesshow misadjustment.

Design Details

This tester arose from my interestin inductors for small DC-DC convert-ers. Thus, the test range is 10 to 1,000µH and the maximum test current is500 mA. The latter limit let me powerthe tester from a conventional wall-transformer and to use ratherskimpy heatsinking.

The time taken to sweep the current from -500 mA to +500 mAdepends on the voltage one wantsacross the maximum inductance. Ichose the peak-to-peak voltage for a 1mH inductor to be 2V.

A voltage (V) across an inductor(L) causes the current through it toincrease at V/L amps per second. Onevolt across 1 mH causes a 1 A/ms current change. The opposite alsoapplies; a 1 A/ms rate of currentchange induces 1V across a 1 mHinductor.

The maximum test current rampsfrom -0.5A to + 0.5A in 1 ms. Thisinduces a +1V signal across the

reference inductor. As the currentramps down from plus full scale to minus full scale, the inductor voltage becomes -1V, giving thedesired 2V peak-to-peak signal. Asthe test signal ramps up for 1 ms anddown for 1 ms, the repetition rate is500 Hz.

Making a Ramp

I avoided a lot of board clutter byusing an ICL8038 signal generatorchip (U3) to create the ramp wave-form. This chip contains the necessaryswitched current sources, compara-tors, and buffer amplifiers to generatea ramp having equal positive and negative peaks. It also has sine andsquare wave outputs. The latter supplies the test signal for setting VR2.

The ramp length is controlled bytwo equal resistors and a capacitor.The capacitor (C5) is 0.047 µF andshould be plastic foil, not ceramic.The resistors (R1 and R2) should be 1% types and, ideally, should be matched. The six-way switch(SW1) selects one of four output peakamplitudes: 50 mA, 100 mA, 200 mA,and 500 mA. It also selects the squarewave and zero.

Driving Current

An ordinary op-amp can’t supplya bipolar current output. Here, I usedan old trick. An op-amp drives a loadresistor and its power pins supply positive and negative drive currents toa push-pull output stage. The op-ampused should have an output stage withmatching NPN and PNP transistors.The TL081 would be ideal, but I onlyhad TL082 (dual) and TL084 (quad)amplifiers in stock. I used both halvesof a TL082 and gave each half its own200 ohm load resistor.

The current driver runs open-loop.I tried feedback from the current-sensing resistor but it was unstablewhen driving a test inductor. This

48 June 2007

FIGURE 4. A differential amplifiermeasures the current. An integratorsupplies the vertical signal.

Napier.qxd 5/7/2007 11:14 AM Page 48

version assumes that the op-amp’soutput and supply currents change instep and that the driver stage has awell-defined gain. It uses modifiedPNP and NPN current mirrors.

Each power transistor (Q2 andQ4) has a large emitter resistor thatdrops over a volt at the current peaks. These transistors are driven byopposite polarity emitter followers sothe base-emitter voltages of each pairroughly cancel. The drivers’ bases areconnected to the amplifier’s powerpins and to the power rails via 51 ohmresistors (R12 and R13).

The current gain of this combina-tion is 23. Apart from about 3 mA of static current, the amplifier’spower currents equal the currentflowing through its combined 100 ohm load. That is, a 100 mVamplifier input generates 23 mA atthe driver output. SW1 selects a suitable drive voltage for each current range. C6 reduces noise andstray feedback and makes the currentramp much cleaner.

The op-amp’s static current causes the output transistors to passnearly 100 mA when the output current is zero. I tried reducing this, but only introduced cross-overdistortion. We must just live withabout 1.6 wasted watts. The regulators’ and transistors’ peak dissipation is around 5W, but noheroic heatsinking is required.

The output transistors’ base currents are adjusted to balance outoffsets. Short the inductor terminalsand set the switch to its groundedinput position. Measure the voltageacross R18 with a multimeter on its200 mV scale and adjust VR1 untilthe meter reads zero. The specifiedoutput transistors have current gainsexceeding 150 at 500 mA. Manypopular power transistors have lowergains and won’t work unless R14,R15, and VR1 are reduced to supplymore base current.

Why Eight Volts?

The current driver doesn’t needmore than about +-2V of output com-

pliance, so bipolar 5V powerrails might have sufficed.However, at a current peakthe input to the current mir-ror is 1.3V less than the posi-tive or negative power rail. Ifthe main power were ±5V,the net supply to the op-ampwould be about 8.5V. Sincethe TL082 is rated for 10Vminimum, I boosted thepower rails to ±8V to avoid risking oddnon-linearities. This means huntingdown 7808 and 7908 three-terminalregulators. By the way, I used 2,200 µFreservoir capacitors for space reasons,4,700 µF ones would be better.

I/V Sensing

One end of the inductor undertest is grounded. This makes measur-ing the voltage across it easy, but youneed a floating current-sensing resistor(R18). A differential amplifier (U5a)drives the scope’s X input with a scalefactor of 5V per amp. The inductorvoltage goes to the integrating amplifier (U5b) whose output drivesthe scope’s Y input. As mentionedabove, an adjustable amount of the Xvoltage is fed to the integrator input to compensate for the inductor’swinding resistance.

The control switch has an off position that shuts off the ramp generator. Ideally, it should be put inthis position before removing theinductor under test. Theoutput voltage swingsfrom one power rail tothe other if you don’t.

Construction

I built this project ona piece of perforatedboard (see Figure 5),intending to put it into a

plastic or metal box at a later date. I’dalready cut a 2.5” by 4.6” board, so Ijuggled things to fit. To simplify making changes, I used wire-wrapsockets for all the small components.This adds considerably to the boardheight and you might be more comfortable using PC sockets andsleeved bus wire.

The back edge of the board is fitted with a length of 0.5” by 0.75”aluminum angle. This supports thepower input socket and the two BNCsockets that connect the unit to theoscilloscope. It also acts as a heatsinkfor the power regulators and the twooutput transistors. If you put the boardin a case, this angle fits flush againstone wall so use a metal box.

Power comes from a 9 VAC wall transformer. Mine is an oldRadioShack one rated at 780 mA.These ratings are about the minimumacceptable for this application. If you use a 12 VAC or higher voltagetransformer, you’ll need a biggerheatsink.

FIGURE 5. The unboxedB-H tester board.

FIGURE 6. As suspected,my metal tape cores showa square loop.

Probing Cores

June 2007 49

Napier.qxd 5/7/2007 11:14 AM Page 49

The inductor under test can beconnected with banana-pin screw terminals. You can get away with a

foot or so of test lead between thetester and the inductor; we’re not talking RF here.

Applications

This tester can be usedto analyze a core materialor to evaluate a finishedinductor. In the former case, as many or as fewturns as one needs may beput on the core. Use the highest test current toavoid winding more turnsthan necessary. The loop’sY voltage depends on theinductance so you may run out of scope gain if you try to test very smallinductors. The results youget tell you what type the core is. As Figure 6shows, my unknown cores were definitely square-loopdevices.

When testing a pre-wound inductor, theparameter of interest is itssaturation current. The testcurrents let you focus in onthe most interesting part ofthe curve. Some inductors may not saturate even atthe highest test current.This design could be adapted to considerably

higher currents, but I’ll leave thatdevelopment to the more intrepidreaders. NV

Item Description U1 +8 V regulator, 7808, JRC U2 -8 V regulator, 7908, JRC U3 Function generator, ICL8038,

Harris U4 Dual op-amp, TL082, TI U5 Dual op-amp, TL082, TI Q1 PNP transistor, 2N3906 Q2 NPN power transistor, MJE200,

ON Semiconductor Q3 NPN transistor, 2N3904 Q4 PNP power transistor, MJE210,

ON Semiconductor D1 1A rectifier, 1N4001 D2 1A rectifier, 1N4001 C1 Electrolytic capacitor,

2,200 µF 16V C2 Electrolytic capacitor,

2,200 µF 16V C3 Electrolytic capacitor, 470 µF 10V C4 Electrolytic capacitor, 470 µF 10V C5 Plastic capacitor, 0.047 µF 50V C6 Ceramic capacitor, 1,000 pF 50V C7 Ceramic capacitor, 0.1 µF 50V C8 Ceramic capacitor, 0.1 µF 50V C9 Plastic capacitor, 0.047 µF 50V R1 1% resistor, 13.0K R2 1% resistor, 13.0K R3 1% resistor, 3.01K R4 1% resistor, 3.01K

Item Description R5 1% resistor, 6.04K R6 1% resistor, 18.2K R7 1% resistor, 2.21K R8 5% resistor, 39K R9 5% resistor, 1K R10 1% resistor, 200 ohm R11 1% resistor, 200 ohm R12 1% resistor, 51.1 ohm R13 1% resistor, 51.1 ohm R14 1% resistor, 1.0K R15 1% resistor, 1.0K R16 2% resistor, 2.2 ohm 0.5 W R17 2% resistor, 2.2 ohm 0.5 W R18 2% resistor, 1.0 ohm 0.5 W R19 1% resistor, 10.0K R20 1% resistor, 20.0K R21 1% resistor, 20.0K R22 1% resistor, 100K R23 1% resistor, 100K R24 1% resistor, 1.00 M R25 1% resistor, 20.0K VR1 Trimmer, 2K VR2 Variable resistor, 5K L Inductor under test SW1 Six-way switch J1 Coax connector to PSU J2 BNC connector (X output) J3 BNC connector (Y output) 9 VAC 800 mA wall-transformer

PARTS LIST

Development Tools for PIC® MCUs

microEngineering Labs, Inc.Phone: (719) 520-5323

Fax: (719) 520-1867Box 60039

Colorado Springs, CO 80960

Order online at:

www.melabs.com

Pre-Assembled BoardAvailable for 8, 14, 18, 28, and 40-pin PIC® MCUs2-line, 20-char LCD Module9-pin Serial PortSample ProgramsFull Schematic Diagram

Pricing from $69.95 to $349.95

PICPROTO™ Prototyping BoardsDouble-Sided with Plate-Thru Holes

Circuitry for Power Supply and Clock

Large Prototype Area

Boards Available for Most PIC® MCUs

Documentation and Schematic

Pricing from $8.95 to $19.95

LAB-X Experimenter Boards BASIC Compilers for PICmicro®

PICBASIC PRO™ Compiler $249.95

Easy-To-Use BASIC CommandsWindows 9x/Me/2K/XP Interface

BASIC Stamp 1 CompatibleSupports most 14-bit Core PICsBuilt-In Serial Comm Commands

Supports All PICmicro® MCU FamiliesDirect Access to Internal RegistersSupports In-Line Assembly LanguageInterrupts in PICBASIC and AssemblyBuilt-In USB, I2C, RS-232 and MoreSource Level Debugging

See our full range of products, including

books, accessories, and components at:

www.melabs.com

EPIC™ ParallelPort Programmerstarting at $59.95

PICBASIC™ Compiler $99.95

USB Programmer for PIC® MCUs

Includes:Programmer, USB Cable,ZIF Programming Adapter for 8 to 40-pin DIP,Software for Windows 98/Me/NT/2K/XP

(with accessories)

$119.95

RoHSCompliant

Programs PICMCUs includinglow-voltage (3.3V)devices

50 June 2007

Napier.qxd 5/7/2007 11:15 AM Page 50

Log on towww.jaycar.com/catalog

for your FREE catalog!

1-800-784-0263(Monday - Friday 09.00 to 17.30 GMT + 10 hours only).

For those who want to write: 100 Silverwater RdSilverwater NSW 2128 Sydney AUSTRALIA

430+ Pages

Full Color

675+ New

Products

Voltage Regulator Kit KC-5446 $8.75 + post & packingThis handy voltage regulator can provide up to1,000mA at any voltage from 1.3 to 22VDC.Ideal for experimental projects or as a mini benchpower supply etc. Kit supplied with PCB and allelectronic components.

50MHz Frequency Meter MKII KitKC-5440 $40.75 + post & packingThis compact, low cost 50MHZ Frequency Meter isinvaluable for servicing and diagnostics. This upgradedversion, has a prescaler switch which changes the unitsfrom Mhz to GHz, kHz to MHz and Hz to kHz,and has 10kHz rounding to enable RCmodellers to measure more accurately. Kitincludes PCB with overlay,enclosure, LCD and allelectronic components. Other features include:• 8 digit reading (LCD) • Prescaler switch • Autoranging Hz, kHz or MHz• 3 resolution modes including 10kHz rounding,

0.1Hz up to 150Hz, 1Hz up to 16MHz and 10Hz upto 16MHz

Jacob’s Ladder High Voltage Display KitKC-5445 $23.25 + post & packingWith this kit and the purchase of a 12V ignition coil(available from auto stores and parts recyclers), createan awesome rising ladder of noisy sparks that emits thedistinct smell of ozone. This improved circuit is suited tomodern high power ignition coils and willdeliver a spectacular visual display. Kit includesPCB, pre-cut wire/ladder and all electroniccomponents.• 12V car battery or 5 Amp DC

power supply required

DC Relay SwitchKC-5434 $8.75 + post & packingAn extremely useful and versatile kit thatenables you to use a tiny trigger current - aslow as 400µA at 12V to switch up to 30A at50VDC. It has an isolated input, and is suitable fora variety of triggering options. The kit includes PCB with overlayand all electronic components with clear English instructions.

Battery Zapper MKII KC-5427 $58.00 + post & packingThis kit attacks a common cause of failure in wet leadacid cell batteries: sulfation. The circuit produces shortbursts of high level energy to reverse the damagingsulfation effect. This new improved unit features abattery health checker with LED indicator, new circuitprotection against badly sulfated batteries, test pointsfor a DMM and connection for a battery charger. Kitincludes case with screen printedlid, PCB with overlay, allelectronic components andclear English instructions.Suitable for 6, 12 and 24Vbatteries• Powered by the

battery itself

Powertool Battery ChargerController KC-5436 $23.25 + post & packingEnhance the performance of the chargersupplied with your power tool with thiscontroller. It incorporates charge timeout,min and max temperature monitoring, Deltacharge detection, power and charge LEDindicator, adjustable Delta V, temperaturesettings, and optional adjustable tricklecharge. Suits both Ni-Cd and Ni-MH cells.Kit includes PCBwith overlay, case,all electroniccomponents andclear English instructions.

Stereo VU and Peak Meter Kit KC-5447 $40.75 + post & packingAccurately monitor audio signals to prevent signalclipping and ensure optimum recording levels. Thisunit is very responsive and uses two 16-segmentbargraphs to display signal levels and transients peaksin real time. There are a number of display options toselect, and both the signal threshold and signal levelcalibration for each segment are adjustable. Kitsupplied with PCBs, LCD and all electroniccomponents. Accuracy within1dB for signals above -40dB. • Case not included use

HB-6082 $5.50Requires 9-12VDC Wall

adapter use Jameco#252751 $12.05 Short form kit

Programmable High Energy Ignition SystemIgnition SystemKC-5442 $52.25 + post & packingThis advanced and versatile ignition systemcan be used on both two & four strokeengines. The system can be used to modifythe factory ignition timing or as the basis fora stand-alone ignition system with variableignition timing, electronic coil control andanti-knock sensing.Features:• Timing retard & advance over a wide range• Suitable for single coil systems• Dwell adjustment• Single or dual

mapping ranges• Max & min RPM

adjustment• Optional knock sensing• Optional coil driver• Kit supplied with PCB, diecast case, and all

electronic components

Hand ControllerKC-5386 $37.95 + post & packingThis LCD hand controller isrequired during the initialsetting-up procedure. It plugsinto the main unit and can beused while the engine is eitherrunning or stopped. Using thisHand Controller, you can set allthe initial parameters and alsoprogram the ignitionadvance/retard curve. Kitsupplied with silk screened andmachined case, PCB, LCD, andall electronic components.

Ignition Coil DriverKC-5443 $26.00 + post & packingAdd this ignition coil driver tothe KC-5442 ProgrammableIgnition System and you have acomplete stand-alone ignitionsystem that will trigger from arange of sources includingpoints, Hall Effect sensors,optical sensors, or the 5 voltsignal from the car's ECU. Kitincludes PCB with overlay andall specified components.• Kit supplied with PCB, and all

electronic components

POST AND PACKING CHARGES:Order Value Cost$25 - $49.99 $7.50$50 - $99.99 $20$100 - $199.99 $40

Order Value Cost$200 - $499.99 $60$500+ $75

Max weight 12lb (5kg). Heavierparcels POA. Minimum order $25.Note: Products are dispatched from Australia,local customs duty and taxes may apply.

How to order:Phone: Call Australian Eastern Standard TimeMon-Fri on 1800 784 0263Email: [email protected]: PO BOX 6424, Silverwater NSW 1811.Expect 10-14 Days For Air parcel delivery

Visit us at www.jaycar.com/catalog and

obtain your free copy of our 430+ page, fullcolor catalog. We have an extensive range of

electronics kits and the best in innovative gadgets.

Improvedmodel for2007

430+ page

Catalog

All prices in

USD

w w w . j a y c a r . c o m

Full Page.qxd 5/9/2007 3:08 PM Page 51

The answer is not to abandon it,nor avoid using it. But rather, to

create a software serial port for it. Thisis not as daunting a task as you mightthink. It only takes some time to learnand try. You will find the results arevery interesting and rewarding.

I will present two practical exam-ples to show — from simple to complex— how easy (or how difficult) it is to doso. First, let’s review the serial port.

Serial Port Basics:9600 bps, 8N1

We’re all familiar with a PC seri-al port. Compared to a parallel port,the main difference is it transmitsdata one bit at a time. (That can savea bunch of wires!) So, there are onlytwo wires needed: TX (transmit) andRX (receive) for data transmission.Actually, a common ground (GND)wire is needed, as well.

The CPU of a microprocessordoes not handle data one bit at atime (it’s too inefficient!), so the taskof serial data transmission is relegat-ed to a special hardware part calleda UART (Universal AsynchronousReceiver/Transmitter).

The UART is the heart of a serial

port, where a mechanism is providedto convert a byte into a series of bitsfor transmission, and vice versa forreception. To make this happen, firstand foremost, the UART must have anaccurate bit rate (baud rate) genera-tor. The serial port speed is defined inbits per second (bps) and is governedby the baud rate generator.

Of course, the UART also has other hardware to check fortransmission status and errors, flowcontrol, etc. But the essential partsare the above-mentioned three inorder to get it up and running.

Each byte of data is transmitted inthis sequence: Bit 0 or the least signif-icant bit (LSB) first, then bit 1 throughbit 6, then finally bit 7 or the most significant bit (MSB) last. In order tosignify the beginning and end of eachbyte transmission, the RS-232 proto-col adds a start bit before the LSB, anda stop bit after the MSB. The start bitis a logic low (0); the stop bit is logichigh (1). Figure 1 shows how an ASCII“X” (0x58 hex or binary 01011000)character is transmitted; notice thesequence is reversed to 00011010.

In its simplest and most popularuse, the serial port is configured as9600 bps, 8N1. That means the baud

Microcontrollers(MCUs) can be

classified in many waysby different criteria.

But, for this article, wewill divide them intoonly two categories:

the ones thatalready have a

built-in serial portand the ones that

don’t.

We all know theimportance of serial

data communicationsto our daily life andthe convenience of

using microprocessorsin achieving this goal.

So, what do you doif you have a

microcontroller thatdoes not have a

built-in serial port?

52 June 2007

FIGURE 1. Transmit “X.”

CREATE YOUROWN SOFTWARE

SSEERRIIAALLPPOORRTTUsing Bit-Banging Techniques

Xu.qxd 5/9/2007 11:15 AM Page 52

rate is 9600 bits per second, data iseight bits in one transaction, there is noerror checking, and one start bit andone stop bit are attached to each trans-action. So, it actually transmits 10 bitsinstead of eight bits for a byte of data.

A Simple Hardwareand SoftwareImplementation

The Atmel ATtiny11 is an inexpen-sive MCU (only 52 cents each or$38/100). It’s an eight pin chip, without a built-in serial port. However,using the circuit shown in Figure 2 andthe simple assembly language programin Listing 1, we will show that a work-ing serial port had been created for it.

This circuit is simple enough tobuild it on a breadboard. The LED is notrequired; it only serves as a reminder if you forget to plug in the power supply and the circuit is not working.Furthermore, you can even dispensewith the 1 MHz crystal (XTAL) and usethe chip’s internal 1 MHz RC-oscillatorinstead. Either way, the demo still works.

Refer to both Figure 2 and Listing 1and notice that ATtiny11 pin 7 (PB2) isconfigured as RX, and pin 6 (PB1) is TX.The Dallas Semiconductor’s DS275 is avoltage level shifter which shifts the TTLlevel to an RS-232 level, and vice versa.

J1 is a female DB-9 connector.Only three wires are necessary to connect to the PC serial port andmatch its DB-9 male connector. Youcan use three longer wires startingfrom the breadboard and directly plugeach end of wire into the female connector’s corresponding pin holes.This facilitates the connectionbetween the DB-9 and breadboard.

Now let’s look at the software program in Listing 1. It contains four sec-tions. The first section starting at RESET isthe main program. The remaining sec-tions are three subroutines; their detailedexecutions will be analyzed later, butnote that each subroutine correspondsto an essential part of the UART: bit rategeneration, transmission, and reception.So, we have a software UART here.

To program the ATtiny11, you firstassemble the source code usingAtmel’s free assembler:

AVRASM -I UARTAVR.ASMUARTAVR.LST UARTAVR.HEX

Then you use an ATtiny11 programmer(such as the one published in theFebruary ‘06 issue of Nuts & Volts). Youcan download all UARTAVR files fromthe Nuts & Volts website (www.nutsvolts.com). Notice that the size of thisdemo program is quite small — it onlytakes 94 bytes of program memory.

By the way, if you don’t have anATtiny11 or its programmer, but youhave an AT90S1200 (which is a 20-pinFlash MCU and doesn’t have a built-inserial port), you can still use the sameprogram source code. The only changeyou need to make is in Figure 2;change component U2 to AT90S1200and the corresponding pin numbers.

Any Windows PC has a terminalemulation program called HyperTerminal,which is the one we will use to interact

with the demo circuit. From the WindowsStart button, go ahead to HyperTerminaland configure it as connected to:COM1(or COM2), 9600 bps, 8N1. Whenthe HyperTerminal window along with a“-“ cursor appears, it’s ready to go.

Power-up the demo circuit. You’llsee an “X” appear on the screen.Typing any character from the keyboard will be echoed on thescreen (that’s what the program isexpected to do). At this point, the soft-ware serial port is functioning okay.

Timing is Everything

First and foremost, the UART program must have a way to generatebit rates. This is done by calling the DLY49us routine, which delays 49 microseconds (µs).

Why go with a 1 MHz crystal?Because at a 1 MHz frequency, oneclock cycle = 1 µs, and for all AVRMCUs, most of their instructions takejust one clock cycle (or 1 µs) to execute. This makes the timing

June 2007 53

BY G.Y. XU

FIGURE 2.Software SerialPort Demo Circuit.

Xu.qxd 5/9/2007 11:16 AM Page 53

calculation much easier.Now take a closer look at

DLY49us. This routine uses only fourinstructions. From the AVR datasheet,you can find out how many clockcycles each instruction takes. (The calculation is listed there.) The totaldelay time is exactly 49 µs.

This routine is used to “waste” 49µs when it is needed by the UART. Fora baud rate of 9600 bps, a bit is1/9600 = 104 µs. We always want tosample the incoming bit in its middle(to minimuze any jitter error), so weneed to delay one half of this value, or52 µs. This is named the half_bitime.

Notice that 49 µs is not equal to,but a little less than half_bitime; wemay call it “almost half_bitime.” Thereason for keeping a differencebetween 49 µs and 52 µs will beexplained in the next section.

How Bit-Bangingis Done

Let’s look at the XMT_CHR routine which transmits a byte of dataloaded in register R18 or XMTREG tothe outside world, one bit at a time.Read the code line by line; it’s prettystraightforward.

At the beginning, it pulls the TX linelow and delays two 49 µs periods to signify a start bit. After that, registerR18 is shifted right one bit, with the LSBgoing into the carry flag. Depending onwhether the carry flag is now set orclear, the TX pin will be set or clearedaccordingly. Then we delay two for 49µs periods (one bit time). This effective-ly transmits a high or low bit out.

The above shifting process isrepeated eight times until countequals zero, handling the entire byte.The TX line is then set high for two 49µs periods to signify a stop bit — theend of transmission.

Because there are several instruc-tions executed between bits transmit-ted, each instruction takes 1 or 2 µs inthis routine, and the bit output logic isnot fixed (due to different bit values atdifferent times). In order to keep thebaud rate of 9600 bps or a bitime of104 µs, the delay routine must account

54 June 2007

LISTING 1. Software Serial Port Demo Program.; UARTavr.ASM: 1 MHz AVR BitBanging UART Demo Program (9600 bps, 8N1); Interact with PC software: HyperTerminal; 8/12/2006 Result: “X” echoed, and it works for both Tiny11/1200

.equ RX = 2 ; RX is PB2: pin7 of Tiny11, pin14 of 1200

.equ TX = 1 ; TX is PB1: pin6 of Tiny11, pin13 of 1200

.equ LED = 0 ; LED is PB0:pin5 of Tiny11, pin12 of 1200

.def RCVREG = R17

.def XMTREG = R18

.def COUNT = R19

.include “TN11def.inc” ; Port definitions for ATtiny11

.cseg

.org 0;—————————————————————————————————————————————————————————————————————————RESET:

cbi DDRB, RX ; config DDRB bit-2 as INputsbi DDRB, TX ; config DDRB bit-1 as OUTputsbi DDRB, LED ; config DDRB bit-0 as OUTputNOPcbi PORTB, LED ; LED=ON (active Low)sbi PORTB, RX ;\sbi PORTB, TX ;/ initialize RX/TX as High

ldi XMTREG, 0x58 ; this is ASCII “X”rcall XMT_CHR ; send “X” to PC at beginning

Main:rcall RCV_CHR ; recive Chr from Port RX linemov XMTREG, RCVREGrcall XMT_CHR ; transmit Chr to Port TX linerjmp Main

;—————————————————————————————————————————————————————————————————————————DLY49us: ; 49 us Delay (~Half_Bitime)

ldi R20, 14 ; 1usLOOP1:

dec R20 ; 14 * 1 = 14brne LOOP1 ; 13 * 2 + 1 = 27ret ; 4 + 3 = 7

;—————————————————————————————————————————————————————————————————————————XMT_CHR:

ldi COUNT, 8 ; 8-bit Datacbi PORTB, TX ; StartBit=’0’rcall DLY49us ; ~Half_Bitimercall DLY49us ; ~Half_Bitime

NEXTX:lsr XMTREG ; shift right LSB to Carrybrcc FORWARDsbi PORTB, TX ; set TX=’1’ if Carry=’1’rjmp F2

FORWARD:cbi PORTB, TX ; set TX=’0’ if Carry=’0’

F2:rcall DLY49us ; ~Half_Bitimercall DLY49us ; ~Half_Bitimedec COUNTbrne NEXTX

STOPBIT:sbi PORTB, TX ; StopBit = ‘1’rcall DLY49us ; ~Half_Bitimercall DLY49us ; ~Half_Bitimeret

;—————————————————————————————————————————————————————————————————————————RCV_CHR:

LDI COUNT, 8 ; 8-bit Datawait:

sbic PINB, RX ; wait for StartBit=’0’rjmp wait continued ...

Xu.qxd 5/9/2007 11:20 AM Page 54

for these instructions execution time.That’s why we created DLY49us.

Similarly, the RCV_CHR routinereceives a byte of data from the outsideworld and stores it in register R17 orRCVREG. The receiver keeps samplingits RX line until a logic low is detected;that is the beginning of start bit.

To find out the value of LSB, the rou-tine pauses for three DLY49us. By doingso, it samples the middle of the LSB. Thisis the best position for correct sampling.The incoming bit value is read and thecarry bit is set or cleared accordingly.The instruction ROR RCVREG rotatesthat bit into register RCVREG bit7 eachtime, until all eight bits are transmittedand count equals zero, so RCVREG hasconverted the bits into a byte.

The technique of converting a byteinto a series of bits for transmission, orconverting a series of bits into a byte forreception, is known as “bit-banging.”

A Full-fledgedApplication:WWLSEEP-1Programmer

You might think that even thoughthe above demo programworks in simple cases, it maynot work in more complexones. I had the same concern. I have not seen anyother product that’s builtusing a software serial port;all I’ve seen are just simpledemo circuits. I was determined to give it a try,however, I decided to makean I2C EEPROM programmer.

Atmel has two very sim-ilar MCUs: the AT90S1200and the AT90S2313. Bothare 20-pin chips; the differences are the 2313 has2K Flash memory and abuilt-in serial port; the 1200only has 1K Flash memoryand no serial port.

My strategy was two

steps: First, build an I2C EEPROM programmer using the 2313, then try tomigrate it to the 1200 using my software serial port. It took a few daysto complete the first step, however, themigration took much longer thanexpected. Originally, the 1200’s RX andTX pins were not assigned the same pinnumbers as the 2313’s RX (pin2) andTX (pin3). In experimenting I learnedthese pins could only get the EEPROMwritten correctly; reading was incorrect.

I still don’t know why it can’t readcorrectly, but I finally discovered that ifthe 1200 pin assignment was the sameas the 2313 (RX to pin2, TX to pin3),

then both reading and writing are cor-rect. The 1200-based programmer com-pletely works this way. The programmerschematic is shown in Figure 3.

Notice this serial EEPROM program-mer is wall-wart-less, meaning the powersupply is taken from the PC serial portitself. This is convenient to the user. It’spossible because the circuit containsonly three small chips; the total currentconsumption is much less than 10 mA.

To program the 24CXX I2C EEPROM, only two pins are needed: theserial clock pin SCL and the serial data pin SDA, which is bidirectional.The programming command or data is

Create Your Own Software Serial Port

June 2007 55

rcall DLY49us ; ~Half_BitimeNEXRX:

rcall DLY49us ; ~Half_Bitimercall DLY49us ; at the Middle of next bit

CLC ; clear CarryROR RCVREGsbic PINB, RX ; Test RX=’0’ or ‘1’?SBR RCVREG, $80 ; set bit7=’1’ if RX=’1’

; otherwise don’t changeDEC COUNTbrne NEXRXRET

;—————————————————————————————————————————————————————————————————————————

FIGURE 3. Schematic ofWall-wart-less Serial EEPROMProgrammer.

Listing 1 continued ...

Xu.qxd 5/9/2007 11:20 AM Page 55

applied to SDAfrom the 1200,and the SDA also outputs datato the 1200 whenrequested. Aclock signal gen-

erated by the 1200 is applied to synchronize I/O operation.The complete programmer development project includes

writing a Windows XP program to communicate with the programmer, and coding the 1200 firmware. Of course, inaddition to creating the software serial port and communi-cating with a PC, the firmware must perform all read/writeprogramming functions through SCL and SDA. The firmwareis 854 bytes total, including the software serial port overhead.

Photo 1 shows the WWLSEEP-1 programmer. Noticethat all the signals and power supply are provided throughthe DB-9 connector; there is no separate power supply.

Also note that if the PC is not running the programmersoftware but running the HyperTerminal program instead, itwill show the character echo effect as in the first example.

Summing Up

We’ve seen two examples where a software serial portis useful. It can save you money and it can (nearly) do thesame job as a hardware serial port. You’ll need some memory space, but the overhead is less than 100 bytes. Forthe 1K byte 1200, there is still a lot of program space left.

The timing requirement for the asynchronous commu-nication is very forgiving at the 9600 bps speed. Examine tosee what will happen if you change the DLY49us to 50 µs byadding an NOP (that’s equivalent to 1 µs) to the beginningof the routine. You’ll see it is still okay.

Of course, there are limitations. The 1 MHz frequency istoo low if you want to geta higher baud rate. At high-er speeds the half_bitimeis reduced and it will behard to keep sampling inthe middle of each bit.

We may not be chipmakers, but we can create a software serialport for any MCU whenwe need it. I have creat-ed a website containingthe software serial port program source code fordifferent MCUs — just goto www.geocities.com/microappnotes. NV

FOR YOUR INFO The following items areavailable from:G.Y. Xu, P.O.Box 14681Houston, TX 77021, USAPhone: (713) 741-3125

• Assembled and testedWWLSEEP-1 Programmer —$24.95 (with one free 24CXX)

• Printed Circuit Board andProgrammed AT90S1200 —$10.00

For more information, go towwwwww..ggeeoocciittiieess..ccoomm//xxuummiiccrroo.

56 June 2007

PHOTO 1. This isthe WWWLSEEP-1Programmer.

Xu.qxd 5/9/2007 1:03 PM Page 56

Interface a sharp LCD display to your BASIC Stamp® or othermicro-controller project with ease. No-solder wiring harnessesand easy mounting kits available too. See www.seetron.com today.

• 3.2 x 1.4 in. supertwist LCD• 2400/9600 baud serial• Low (≈2mA) current draw• Great with BASIC Stamps®

• 3.2 x 2 in. backlit LCD• 1200-9600 baud serial• Advanced protocol, 4 switch inputs• EEPROM for configuration settings• Favorite for OEM applications

• 3.2 x 1.4 in. graphics LCD• 2400/9600 baud serial• Font and 15 screens in EEPROM• Easily draw points, lines, screens

• 3 x 2 in. supertwist LCD• 1200-9600 baud serial• ESD-protected, 4x4 keypad input• Store up to 95 screens in EEPROM

ILM-216L

SGX-120L

TRM-425L

BPI-216N

1939 S. Frontage Rd. #F, Sierra Vista, AZ 85635phone 520-459-4802 • fax 520-459-0623www.seetron.com • [email protected]

58 June 2007

Page58.qxd 5/10/2007 10:18 AM Page 58

60 June 2007

Previously, it was noted that phasedistortion is an aspect to soundthat is not generally addressed.

This occurs when a sound containingmany frequencies is broken up andsent to two (or more) different driversin a speaker system. This results in two different physical sources for thesound: one for high frequencies andanother for low frequencies. This isclearly different from the originalinstrument or voice which came froma single source (and can usually betreated as a point source).

The major problem with multipledrivers is that sonic reflections fromthe ceiling, floor, and other largeobjects in the listening area destroythe phase information. This occursbecause of different path lengths forthe high frequency and low frequencysound reflections. These sonic reflec-tions can be nearly as loud as thedirect signal but do not contain thesame phase relationships between the

high and low frequencies.It was also previously noted that

the human sense of hearing is a verycomplicated system that is extremelysensitive to phase. Both binauralphase (ear-to-ear time difference) andmonaural phase (open space sound)variations have been shown to bedetectible with as little as 15 microsec-onds of change. Therefore, is seemsreasonable to suppose that a speakersystem that could better maintain thephase information regardless of roomreflections, would provide a muchmore realistic acoustical setting.

Phase CCoherentSpeakers

It is necessary to clarify the issuesstated here and the so-called PhaseCoherent Speaker systems that are currently available. Most of thesesystems contain multiple drivers andare designed to provide proper phase

information, but only if measured witha straight line from the speaker to theear. Any speaker system with multipleand separate drivers is physically incapable of providing proper phaserelationships from reflections. Quitesimply, if there are two separatesources of sound, phase distortionmust occur in any sonic reflection.

Basic PProblemFundamentally, in order to

reproduce the 10 octave range of human hearing (20 Hz to 20,000 Hz), multiple drivers are necessary.Woofers are hopeless when reproduc-ing high frequencies and tweeters simply cannot push enough air to create good bass response. This isespecially true when high power levelsare employed. (Earphones are notconsidered because the issue is free-space sound reproduction.)

The technique used is to acousti-

SONICREALISM

WWhhyy ddooeess rreeccoorrddeedd mmuussiicc ssoouunndd ddiiffffeerreenntt ffrroomm tthhee rreeaall tthhiinngg?? WWhheenn wwee wwaallkk iinnttoo aa rroooomm,, wwee iinnssttiinnccttiivveellyy kknnooww iiff tthhee mmuussiicc oorr ssppeeeecchh wweehheeaarr iiss lliivvee oorr aa rreepprroodduuccttiioonn.. TThhiiss sseeeemmss ttoo ccoonnfflliicctt wwiitthh tthhee ssppeecciiffiiccaattiioonnss ooff tthhee ssyysstteemm wwhheerree ddiissttoorrttiioonn aanndd ffrreeqquueennccyy rreessppoonnssee aarree nneeaarrllyy ppeerrffeecctt..SSoommeetthhiinngg iimmppoorrttaanntt iiss mmiissssiinngg ffrroomm tthhee rreeccoorrddiinnggss tthhaatt iiss pprreesseenntt iinn tthheelliivvee rreeccoorrddiinnggss.. TThhee mmiissssiinngg ccoommppoonneenntt aappppeeaarrss ttoo bbee pphhaassee iinnffoorrmmaattiioonn..

LLaasstt ttiimmee wwee eexxaammiinneedd tthhee tthheeoorryy,, tthhiiss ttiimmee wwee’’llll ppuutt tthhee tthheeoorryy iinnttoo pprraaccttiiccee..TTwwoo ddiiffffeerreenntt ssppeeaakkeerr ssyysstteemmss wwiillll bbee ddeessccrriibbeedd tthhaatt yyoouu ccaann bbuuiilldd..

PPAARRTT 22by Gerard Fonte

Fonte2.qxd 5/7/2007 9:32 AM Page 60

cally recombine the soundsfrom the multiple driversbefore it leaves the speakerenclosure. In this way, the highfrequency and low frequencysounds emanate from a singleopening. Thus, sonic reflec-tions from the ceiling will stillhave the same harmonic phaserelationships as the direct line.Note that this provides phaseconsistency rather than phaseaccuracy. Phase accuracy isdefined as reproducing soundswith the precise phase relation-ships as they were when theywere recorded. Phase consis-tency is defined as maintainingthe proper phase relationshipsregardless of sonic reflections. ThePhase Coherent speakers mentionedabove strive for phase accuracy ratherthan phase consistency. The speakersthat are presented here strive forphase consistency rather than accura-cy. (As a first step in research, it is reasonable to choose one aspect todetermine its relative importance.Designing a phase consistent andphase accurate speaker system is nota simple task.)

The BBuried TTweeterDesign

The basic design is shown inPhoto 1 (note that the wide-anglelens distorts the true shape somewhat). There are two isolated —but identical — rectangular enclosuresthat each hold a woofer. One wooferis pointed up and can be seen. Thesecond is pointing down and cannotbe easily seen. These enclosures areseparated with a 9.5 inch gap that isopen on three sides (the back isclosed). Centered in this gap is a horntweeter. Photo 2 shows the details ofthe tweeter assembly as it is partially

removed from the speaker enclosure.The cross-over network (2 kHz, four-pole) can be seen attached tothe left mounting piece. The black circle to the upper right is the terminal connector. (The hole behindthe tweeter was used when testing alonger tweeter.)

The general physical dimensionsare 17.25” wide, 15 inches deep, and51.5 inches tall (excluding feet) with aweight of over 80 pounds. ContinuousRMS power at any frequency is 400watts. However, the woofers are ratedat 350 watts each, so the low end is robust. The frequency responsecharacteristics cannot be measuredbecause I have no facilities to do so. Ican only state that the performance iscertainly acceptable and (to my ears)comparable to other hi-fi speakers Ihave heard.

Construction details and designrational are provided in the sidebar.There are certainly second-orderdetails that are not directly addressed(off-axis sound versus phase), however, as a first approximation, thisdesign appears to provide the properphysical characteristic that all the

different frequencies come out of asingle opening.

PerformanceThe speakers were placed about

seven feet to the right and left of thelistener. The initial results were not sig-nificantly different from conventionalspeakers. However, there was a subtledifference in some instruments. Theplacement of these seemed to local-ize inside the head, like headphones.This effect was not conspicuous.

Any speaker system with multiple and separate drivers is physically incapable of providing proper phase relationships

from reflections. Quite simply, if there are two separate sources of sound, phase distortion must occur in any sonic reflection.

PHOTO 11.. The buried tweeter speakerplaces the tweeter inside the enclosureso that all of the frequencies emergefrom a single point. This maintains the phase relationships regardless ofreflections. Note that the speaker grillcloth is removed.

PHOTO 22.. The tweeter sub-assembly is partiallyremoved to show the construction method.The crossover network is seen on the leftmounting member. The sub-assembly isscrewed to the back of the main enclosure.

June 2007 61

Fonte2.qxd 5/8/2007 1:17 PM Page 61

62 June 2007

SONIC REALISM

However, it was realized that the individual instruments were localizedon a line between the two speakers. Itwas also noted that it was easy to hearboth speakers even when standingclose to one of them. So while therewere some sonic differences from the conventional approach, they werenot significant.

Upon further consideration, it wasrealized that a third speaker placed infront of the listener might be useful.The idea was that since the humanhearing system uses both phase andamplitude for localization, a centerchannel could provide additionalamplitude cues. A “center” signal wasone that had an equal amplitude inboth stereo channels. Adding thechannel signals together meant thatthe center channel would providetwice the amplitude (+6 dB) as either

channel alone. This should be enoughto significantly assist in localization,which should also enhance the realityof the sound.

So, a third speaker was built.However, because of a number ofissues (including parts availability) thethird, center-channel speaker wasmuch more modest. It is shown inPhotos 3 and 4, and consists of athree-way automotive speaker withcoaxial drivers. The enclosure is a simple box and is also described inmore detail in the sidebar. This center speaker design is much easier,smaller, and much less expensive thanthe buried tweeter design. It probablywould be adequate for the left and right channels, but this has notbeen tested.

This speaker was driven by a separate amplifier that was just thesum of the left and right channels.(The left and right earphone outputsof the main amplifier were connectedtogether and used as the input for the center channel amplifier.) Thisspeaker was placed about seven feetdirectly in front of the listener. Notethat all the speakers had a direct “lineof sight” to the listener. (A rear channel using an out-of-phase left andright mixture has been considered,but not tested.)

The results of this additionwere stunning. Excellent soundlocalization through 180 degreesoccurred. When listening toorchestral or choral music, eachindividual instrument or voice

had a precise and separate location.There was also a depth that placed different instruments in front andbehind others. Curiously, all threespeakers acoustically disappear. Notethat the program material is ordinarystereo CDs and FM broadcasts.(Although some recordings are betterthan others. This is discussed in moredetail below.)

An A/B switch was incorporatedto disable the center channel. Thisprovided some interesting informa-tion. It appears that it sometimestakes a fraction of a second for thelocalization to appear and disappear.(Unlike turning a speaker on and off,where the sound is immediatelyheard or not.) This delay suggeststhat there is significant mental processing that occurs. This is precisely what was expected andsuggested in the previous article: The brain has an auto-correlationfunction (or its equivalent) that isused for phase analysis.

Speech reproduction is the mostimportant aspect of sonic reality.There are several reasons for this.First, speech is a fundamental aspectof human nature. It is important to us. Speech is also extremely common. We all spend a lot of time each day talking and listening.Finally, unlike most music, speech ismostly heard live. Even at “live”events, microphones and amplifiersare often used. Again, multiple drivers destroy the phase information. Thus, “live” events areactually electronically reproducedstage events. True “live” events arefairly limited. Professional orchestrasand amateur/school bands andchoirs are the most common. Evenjazz is being augmented with electronic amplification. In short, weall know when speech sounds real,but music is a different matter.

It is not surprising that the most dramatic results occur when reproducing voices. When a chorus isreproduced, each voice is distinct andhas a precise location. There is also aquality of realism that cannot be

PHOTO 33.. The center channel speaker usescoaxial speakers (seen as two smallcircles under the grill) to achievereasonable consistent phase output.This is a much simpler design and canprobably be used for the left and rightspeakers with good results. However,this was not tested. (Note that a trim piecewas used to cover the plywood edge.)

PHOTO 44.. The inside of the centerchannel speaker. This shows thestandard construction technique of using internal corner-framingmembers. Screws and glue areused for every joint (except theback panel) for a solid, air-tight box.

Fonte2.qxd 5/7/2007 9:34 AM Page 62

described. It simply sounds as if thechoir is in front of the listener. (It isalso useful to close your eyes becauseyour brain knows where the sound iscoming from. By closing your eyes,there is no conflict between what youreyes and ears are telling you.)

It is unfortunate that there doesnot seem to be an objective mannerin which to measure this effect.However, there are two subtle andunconscious physiological effectsthat have been noticed when listening to solo singing voices that donot occur with conventional speakersystems. The first is the listener’sbreathing tends to match the singer’s.The second is that the listener tendsto mouth the words to the song. Like tapping a foot in time with the music, these effects are variable,but the fact that they do not occurwith ordinary speaker systems seems significant.

The last piece of evidence issomewhat more objective. My wifeentered the room while I was workingat my computer with the stereo on to discuss an unrelated matter. Shewas not aware of the details of thespeakers. A song then started with thewords, “Hi. How are you?” Shewhirled around, clearly startled andsaid “What ...?” This spontaneousreflexive response is telling. It is, in

BUILDING THE SPEAKERSCost and performance were the

major issues that were consideredwhen designing the buried tweeterspeakers. A closed/sealed box (ratherthan ported) was required to ensurethat all the sounds came from oneopening. This required speakers suit-able for such an enclosure. The deter-mination of the Thiele/Small parame-ters necessary for the enclosure weredetermined with the aid of a modelingprogram included in the book GreatSound Stereo Speaker Manual (2nded.) by Weems and Koonce (McGraw-Hill, 2000). This is a very useful bookfor anyone building speaker systems.

After considerable effort, Sony 12inch Xplod (XS-L121P5) automotivespeakers were selected. These had theproper Thiele/Small parameters andwere very attractively priced at a localelectronics superstore as close-outitems (suggested retail about $199each; sale price of $35 each). These arerated at 350 watts RMS and 1,200 wattspeak. The voice coils are only four ohmseach, but using two in series providesthe standard eight ohm impedance.

The tweeter chosen was a piezohorn driver (Motorola/CTS KSN1142A)attached to a standard diffraction horn.This driver can handle 400 watts RMSand only cost about $12. Note thathorn tweeters generally have muchsmoother frequency response charac-teristics than the “Bullet” type circulartweeters. Round dome tweeters have a

smoother frequency responsethan the horn type but cannot

handle the power. It is difficult to findthese KSN1142A tweeters now. Highpower tweeters are not common.

The reason for the use of high-power speakers is the concernabout distortion at high output levels.Most home speaker systems are ratedat 50-100 watts RMS. However, theirdistortion increases significantly athalf-power or less. Often this is notenough power to provide realistic volume levels. Driving them at half-power makes the music sound ”loud”similar to a person’s voice when shouting. There is a sonic difference/distortion. With high-power speakers,the music gets louder but doesn’tsound as if the speakers are shouting.

The crossover network is techni-cally not required because the piezotweeter has a high impedance at lowfrequencies. However, it was desiredto keep as little sound of the same frequencies as possible from exitingfrom both the woofer and tweeter. Forthis reason a sharp-cutoff, four-pole, 2kHz crossover network was employed.This is shown in Figure 1.

The enclosure was built with 3/4inch thick, maple, cabinet-grade plywood. The standard method ofscrews and glue was employed. Allcorners used an internal corner-framing member and the screws weredriven from the inside (see Photo 4 foran example of the standard internalconstruction methods). No fastenersare visible from the outside. The topand bottom are mitered to the sides.This involves a three-way miter at eachcorner. Such a detail cannot be accom-plished without the careful use of atable saw. Other simpler methods canbe employed but minor changes to theenclosure will be required. Theabsolute dimensions of the enclosureare not critical and can be variedsomewhat. (Enclosure building tech-niques are presented in the Weems &Koonce book.) Some experience inwoodworking is suggested beforeattempting to build these, or any,speaker enclosures. Sound quality isdirectly related to construction quality.

The speaker panel was not glued inplace so that access was possible to theinternal blind screws. However, thispanel vibrated at high drive levels. Thisproblem was corrected by placing apiece of weather-seal foam tape betweenthe panel and the mounting members.

FIGURE 11.. The basic crossover network for the buried tweeter speaker system is a four-pole, 2,000 Hz low-pass filter. The piezotweeter series capacitor reduces the outputby about 4 dB for better balance.

SONIC REALISM

June 2007 63

Fonte2.qxd 5/7/2007 9:35 AM Page 63

64 June 2007

fact, the clearest example that, undercertain circumstances, sonic realitycan be achieved. It should be pointedout that the entire room was visible as she entered, so it was impossiblefor someone not to be seen.Additionally, the room was on the

second floor and she turned to looktowards the outside wall. There wasno speaker there.

Recording HHintsNot all recordings provide the

same realism. It seems that the simplerrecording techniques, the better.Voices generally sound best if they arenatural and free from electronicenhancement. Keeping the micro-phone about two feet away from thesinger helps to create a more naturalmix of high and low frequencies (lessobvious pops and hisses). If possible,record individual instruments andvoices with a single microphone orchannel. For multiple people andinstruments, use two closely spacedbut directional microphones; one forthe left and the other for the rightchannel. Multiple microphone mixingdoesn’t seem to work too well.

There are several current commercial recording concepts thatgenerally produce good results. Theseare “Binaural” recordings that use a facsimile of a human head withmicrophones buried in the ears. Theother is the “QsoundTM” from ArcherCommunications. There may be addi-tional techniques, as well. However, itis difficult to find recordings groupedby the engineering technique.

BURIED TWEETER SPEAKER PARTS LISTQty. Description 2 Woofer speakers: Sony Xplod XS-L121P5, 4 ohm

impedance, Rdc=3,2, Fs=26.4, Qts=0.42, Qes=0.44, Qms=5.86, Vas=1.96 cu. ft. Rated power=350 watts RMS, 1,200=watts peak, weight=20 pounds.

1 Tweeter driver: Motorola/CTS KSN1142A, 1.8 kHz-30 kHz. Rated power=400 watts RMS.

1 Diffraction horn: 10-5/8” x 3-7/8” x 7-1/4” with1-3/8” diameter threads @ 18/inch # 54-290 from MCM (wwwwww..mmccmmiinnoonnee..ccoomm)

1 Crossover network (see Figure 1) 4 Main vertical struts: 3/4” x 1.5” x 50.5” (actual) maple

AAllll ppaanneellss aarree mmaaddee ffrroomm 33//44”” tthhiicckk mmaappllee ppllyywwoooodd..MMeeaassuurreemmeennttss aarree oouuttssiiddee ddiimmeennssiioonnss.. AAllll ppaanneell eeddggeess((eexxcceepptt tthhoossee aatt ssppeeaakkeerr ooppeenniinngg aanndd tthhee wwooooffeerr mmoouunnttiinnggppaanneellss)) aarree ccuutt ttoo 4455 ddeeggrreeeess.. 4 Front/back panels: 17.25” x 21” 4 Side panels: 15” x 21” 2 Top/bottom panels: 15” x 17.25” 2 Woofer panel: 13.5” x 15.75” (with proper cutout

for woofer)

TTwweeeetteerr mmoouunnttiinngg ppiieecceess aarree mmaaddee ffrroomm 33//44”” tthhiicckkppllyywwoooodd,, ssqquuaarree ccuutt eeddggeess.. 1 Back panel: 9” x 17.25”

2 Side mounting arms: 9” x 4.5”

AAllll iinntteerrnnaall ccoorrnneerr mmeemmbbeerrss aarree mmaaddee ffrroomm 22”” xx 22””((nnoommiinnaall)) ppiinnee ((11..55”” aaccttuuaall)).. 8 Front/back members: 14.25” 8 Side members: 10.5” 1 Speaker terminal 100 2” drywall screws (approx.) 30 1.25” drywall screws (approx.) 20 Speaker mounting screws (approx.) 1 Wood glue 8 oz. (approx.) 10 ft. “Frost King” vinyl foam weather-seal self-stick

tape 3/8” wide, 3/16” thick (approx.) (see text) 1 Grill cloth: 9.25” x 60” (approx.) (optional) 4 Mounting feet

MMaatteerriiaallss//PPaarrttss CCeenntteerr CChhaannnneell SSppeeaakkeerrThe center channel speaker is a more conventional boxdesign (11.5” x 16” x 8”). It is much easier to build and costsmuch less. The speaker selection was more arbitrary thanfor the buried tweeter design. Photos 3 and 4 show thebasic design and construction method. A table saw is notrequired but it is helpful. Actual dimensions can be variedto some degree. Because the speaker has a four ohmimpedance, a four-ohm resistor was added in series toincrease the impedance to eight ohms. If your center channel amplifier can drive four ohms, then this resistor isnot needed.

SONIC REALISMCENTER CHANNEL SPEAKER PARTS LISTQty. Description 1 8” speaker three-way Pyle PLG8.3 (no Thiele/Small parameters

available) from MCM (#51-1157) about $46/pair, 200 watts RMS

AAllll ppaanneellss aarree 33//44”” mmaappllee ppllyywwoooodd,, mmeeaassuurreemmeennttss aarree oouuttssiiddee ddiimmeennssiioonnss,, TToopp,,bboottttoomm,, aanndd ssiiddee ppaanneellss hhaavvee 4455 ddeeggrreeee mmiitteerr ccuuttss oonn ttwwoo ssiiddeess ((sseeee PPhhoottoo 44)).. 2 Front/back panels: 10” x 14.5” (front panel has speaker cutout as required) 2 Side panels: 16” x 8” 2 Top/bottom panels: 8” x 11.5”

IInntteerrnnaall ccoorrnneerr mmeemmbbeerrss 4 6.5” long 2” x 2” (nominal) pine (1.5” actual) 4 1.5” x 11.5” x 3/4” plywood 4 1.5” x 7” x 3/4” plywood 50 1.25” drywall screws (approx.) 25 2” drywall screws (approx.) 4 Speaker mounting screws 1 Wood glue 4 Rubber feet 1 Speaker terminal

Fonte2.qxd 5/7/2007 9:35 AM Page 64

Some recordings provide goodseparation and others provide good realism. Generally, orchestral recordings exhibit good realism. Thisis especially true for choral works.Studio recordings generally providebetter separation (obviously it is easierfor them to control the crosstalkbetween channels). Often times, the music from a movie will provideexcellent results. The CD, “I Am Sam”is such an example (V2 Records/NewLine Cinema).

ConclusionSonic realism is possible, but

there are three factors that must beaddressed. The first is that consistentphase is a critical factor. There is alsothe requirement of a center channel.Lastly, the recording techniques canprovide a significant variation to thequality of the realism. One does not

have to spend thousands of dollars forrealistic stereo. However, one does

need to pay attention to the sonicdetails. NV

Locate shorted or leakycomponents or conditionsto the exact spot in-circuit

Available at your distributor, or call 561-487-6103

Electronic Design Specialists www.eds-inc.com

The Standard for checkingCapacitors in-circuit

Good enough to be the

choice of Panasonic,

Pioneer, NBC, ABC, Ford,

JVC, NASA and thousands

of independent service

technicians.

Still cutting up the pcb,

and unsoldering every

part trying to guess at

where the short is?

Your DVM shows the same shorted reading all

along the pcb trace. LeakSeeker 82B has the

resolution to find the defective component.

Touch pads along the trace, and LeakSeeker

beeps highest in pitch at the defect’s pad. Now

you can locate a shorted part only a quarter of

an inch away from a good part. Short can be

from 0 to 150 ohms

Inexpensive enough to pay for itself in just

And with a 60 day trial period, satisfaction

guaranteed or money-back policy, the only

thing you can lose is all the time you’re

currently spending on trying to repair all

those dogs you’ve given up on.

CapAnalyzer 88A LeakSeeker 82B

one day’s repairs. At $209, it’s affordable.

$209

June 2007 65

SONIC REALISM

Fonte2.qxd 5/11/2007 7:44 AM Page 65

> > > > g o t o w w w. n u t s v o l t s . c o m — c l i ck E l e c t r o - N e t < < < <

AM/FM Broadcasters • Hobby KitsLearnng Kits • Test Equipment...AND LOTS OF NEAT STUFF!

Standard Features:

• CAN, SPI, SCI

• RS232

• 10-bit A-to-D

• 32K or 128K Flash

• PWM

• Input Captures

• Output Compares

• 3V/5V Operation

P l u g i n t h e p o w e r o

f 9 S 1

2 ! Adapt9S12C

Helping you Adapt to new technology

www.technologicalarts.com

66 June 2007

ElectronetJun07.qxd 5/8/2007 1:14 PM Page 66

This month’s spotlight is onSchmartboard™, a Californiaorganization located in the city

of Fremont, situated north of San Jose.The principal product of the companyis a cleverly designed prototypingboard. Although electronic componen-try made a great leap forward in the21st century, prototype technologylagged far behind. Hence, the creationand marketing of the Schmartboard.

Two friends joined forces to pro-duce this new concept. Andrew Yaung,co-founder, President and CEO, beganby founding Intellect Lab, an electronicengineering service firm and, prior tothat, Shark Multimedia Inc. He holds aBS in Electrical Engineering from SanJose State University and an MS fromSanta Clara University.

Schmartboard was spun off in2005 from Intellect Lab where the con-cept of this high-tech prototyping boardwas invented in 2003. This privatelyowned corporation has five full-timeemployees in a manufacturing facilitythat they have outgrown. A search isunderway for a bigger building to houseand better serve their growth plans.

Andrew’s partner at Schmartboardis Neal Greenberg. Neal also cofound-ed the company and serves now asVice-President of Sales and Marketing.He is a graduate of William RaineyHarper College having obtained an AA degree in Applied Science.Additionally, he has a BS in Marketingfrom California Coast University.

In an interview with Neal, heresponded to our questions about the present and future plans for the company.

Marvin: Neal, what are your mostpopular products and when were theyintroduced?

Neal: The SchmartBoard|ez™ family ofproducts was released in September2005 at the Demofall show. Demo is ashow in which the most innovativeproducts are launched. Previous products launched at Demo include Java 1.0, Tivo, and Palm. The SchmartBoard|ez is innovativebecause for the first time, anyone canhand solder SMT (Surface MountTechnology) parts. Whether it is a partwith a tiny pitch such as 0.4 mm or has200 legs, SchmartBoard|ez has madeit possible for people to easily, quickly,and flawlessly hand solder the parts.

M: What gave rise to the creation ofthis line of products?N: With increasing time-to-market issuesand cost concerns in our fast movingworld, we knew that there had to be abetter way. We also realized that in thepast, a prototyping board could save theengineer valuable time and money byallowing changes to be made quicklyand inexpensively. But prototypingboards had not kept up with technology.Prototyping boards have existed for along time, but as surface mount compo-nents have become smaller and smaller,these boards have not kept up with thetechnology and have not remained apractical tool for most applications.

M: Is there a newly developed productready for release?N: We have a new product called thePower SchmartModule that wasreleased in mid-April. SchmartModulesare functional circuits (such as RS-232)that one can add to a SchmartBoardcircuit so that they don’t have to “reinvent the wheel.” The PowerSchmartModule will allow one to addpower in one of seven voltage optionsto a circuit. The suggested retail is $15.

Equally exciting is a contest to beannounced on June 1st. The SecondAnnual Schmartie Awards is a contestto create schematics with bills ofmaterial that include SchmartBoards.The first prize will be $1,000. In addition, the winning circuit will beturned into an SchmartModule andthe winner will receive a commissionon every unit sold worldwide. Nuts &Volts and SERVO Magazine are ourMedia Sponsors.

M: Finally, what are the principaladvantages of working with theSchmartboards?N: As more and more componentshave gone from through hole to sur-face mount, great advances have beenmade in the ability to make smaller and more advanced electronic devices.The problem though is while circuitassembly of these parts for robots iseasy, it has made hand soldering forprototypes and projects almost impos-sible. The SchmartBoard|ez haschanged this. We can put a solderingiron in the hands of a 10 year old whohas never even heard of a solderingiron ... in less than a minute the 10 yearold will hand solder a 0.5 mm QFP(Quad Flat Pack) device as good as anexperienced technician. SchmartBoard|ezhas made it possible for everyone from a rocket scientist to the weekendhobbyist to hand solder SMT parts.

Nuts & Volts readers can requesta free sample of SchmartBoard|eztechnology at our website at www.schmartboard.com. NV

by Marvin Mallon

June 2007 67

AAnn IInntteerrvviieeww wwiitthh NNeeaall GGrreeeennbbeerrgg

44081 Old Warm Springs Blvd.Fremont, CA 94538

Tel: 551100--665599--11554499 Fax: 551100--665599--11664444Email: iinnffoo@@sscchhmmaarrttbbooaarrdd..ccoommWeb: wwwwww..sscchhmmaarrttbbooaarrdd..ccoomm.

AAnnddrreeww YYaauunngg aannddNNeeaall GGrreeeennbbeerrgg..

InTheSpotlight.qxd 5/10/2007 2:59 PM Page 67

PART 3: NAND Gate and OR Gate CircuitsRRaayy ddeessccrriibbeess pprraaccttiiccaall ddiiggiittaall NNAANNDD ggaattee aanndd OORR ggaattee

llooggiicc IICCss iinn tthhiiss tthhiirrdd iinnssttaallllmmeenntt ooff tthhiiss ffiivvee--ppaarrtt mmiinnii sseerriieess..

The first two parts in thisseries explained modernTTL and CMOS logic

gate basics and gave practicaldescriptions of some of themost popular digital buffer,inverter, and AND gate logicICs that are available. Thismonth, we’ll expand on thisbasic theme and describes a

variety of popular NAND gate andOR gate ICs that are available fromeither your local supplier or fromspecialist dealers.

Practical NAND-Gate Digital ICCircuits

The output of a digital NANDgate goes low when all of its inputs(A and B, etc.) are high. Figure 1

lists basic details of 13 popular NAND-gate ICs; ofthese, the 74LS00, 74HC00,and 4011B (see Figures 2and 3) are standard quadtwo-input types, and the4093B, 74LS132, and74HC132 (see Figures 4 and5) are Schmitt quad two-input types. The 74LS10 and4023B (see Figures 6 and 7)are triple three-input stan-dard types; the 74LS20 and4012B (see Figures 8 and 9)are dual four-input standardtypes; the 74LS30 and4068B (see Figures 10 and11) are eight-input standardtypes; and the 74HC133 is a13-input standard type.

When using NANDgate ICs, each unwantedgate should be disabled byshorting all inputs together

Understanding DigitalBuffer, Gate, and Logic

IC Circuits

Understanding DigitalBuffer, Gate, and Logic

IC Circuits

FIGURE 1. Thirteen popularNAND gate ICs.

FIGURE 2. Functional diagram of the 74LS00or 74HC00 quad two-input NAND gate IC.

FIGURE 4. Functional diagram of the 4093Bquad two-input Schmitt NAND gate IC.

FIGURE 3. Functional diagram of the 4011Bquad two-input NAND gate IC.

FIGURE 5. Functional diagram of the 74LS132 or74HC132 quad two-input Schmitt NAND gate ICs.

b y R a y M a r s t o n

68 June 2007

Marston3.qxd 5/7/2007 10:40 AM Page 68

and tying them to one ofthe IC’s supply lines. InCMOS ICs, the shortedinputs can be wired direct-ly to either supply line, butin TTL ICs the inputs must(to give minimum quies-cent current consumptionwith good stability) be tieddirectly to the 0V rail, asshown in Figure 12.

Sometimes, whenusing NAND gate ICs, youmay not want to use all ofa gate’s input terminals. Inthis case, the unwantedinputs can be disabled byeither tying them high(directly in CMOS gates, orvia a 1K resistor in TTLtypes) or by simply short-ing them directly to a usedinput. Figure 13 showsexamples of a three-inputTTL NAND gate wired foruse as a two-input type.

Note that the fan-in of a TTL NAND gate is an almost constant ‘1,’ irrespective of the numberof inputs used. Thus,CMOS or TTL NAND gatescan be converted into simple inverters by simplyshorting all of their inputstogether. Figure 14 shows examples ofTTL NAND gates used as inverters.Also note that NAND gates are fairlyversatile elements, as demonstrated inFigure 15, which shows ways of usingtwo-input elements to make a two-input or three-input AND gate or athree-input NAND gate.

PracticalOR GateIC Circuits

The output of an OR gategoes high when any ofits inputs (A or B, etc.)go high. The simplestway to make an OR gate is via a number ofdiodes and a single

resistor, as shown (for example) in thethree-input OR gate of Figure 16. Thediode OR gate is reasonably fast, very cost-effective, and can readily beexpanded to accept any number of

inputs by simply adding one morediode to the circuit for each newinput.

Relatively few dedicated OR gateICs are available. Figure 17 lists basic

FIGURE 6. Functional diagram of the 74LS10triple three-input NAND gate IC.

FIGURE 7. Functional diagram of the 4023Btriple three-input NAND gate IC.

FIGURE 8. Functional diagram of the 74LS20dual four-input NAND gate IC.

FIGURE 9. Functional diagram of the 4012Bdual four-input NAND gate IC.

FIGURE 10. Functional diagram of the 74LS30eight-input NAND gate IC.

FIGURE 11. Functional diagram of the 4068Beight-input NAND gate IC.

FIGURE 14.Methods ofusing TTLNAND gatesas simpleinverters.

FIGURE 13. Basicmethod of disablingunwanted TTL NANDgate inputs.

FIGURE 12. Methods of disabling unwantedTTL NAND gates.

June 2007 69

Marston3.qxd 5/7/2007 10:41 AM Page 69

details of the six most popular ORgate ICs: the 74LS32, 74HC32, and

4071B (see

Figures 18 and 19) are quad two-inputtypes; the 4075B and 74HC4075 (seeFigure 20) are triple three-input types;and the 4072B (see Figure 21) is adual four-input type.

When using OR gate ICs, eachunwanted gate should be disabled byshorting all of its inputs together andtying them to one of the IC’s supplylines. In CMOS ICs, the shorted inputscan be wired directly to either supplyline, but in TTL ICs the inputs must (to give minimum quiescent current

consumption with goodstablity) be tied high via a1K resistor, as shown inFigure 22.

Note that the fan-in ofa TTL NOR gate is directlyproportional to the numberof inputs used — at a fan-inrate of one per input — andthat a TTL two-input ORgate can be made to act asa simple non-invertingbuffer by either tying oneinput to ground or by tyingboth inputs together, as shown in Figure 23. Just make sure the bufferhas a fan-in of one in the former case, and a fan-in of two in the latter.Also note that OR gatescan be directly cascaded tomake a compound ORgate with any desired number of inputs. Figure24, for example, showsways of cascading two-

input elements to make OR gates withthree, four, or five inputs, and Figure25 shows a three-input OR elementand a three-input diode OR gate cascaded to make a compound five-input OR gate. NV

70 June 2007

FIGURE 15. Ways of using two-inputNAND gates to make various AND andNAND gates.

FIGURE 16. Simple three input diode OR gate. FIGURE 17. Six popular OR gate ICs.

FIGURE 18. Functional diagram of the 74LS32or 74HC32 quad two-input OR gate IC.

FIGURE 19. Functional diagram of the 4071Bquad two-input OR gate IC.

FIGURE 20. Functional diagram of the 4075Bor 74HC4075 triple three-input OR gate IC.

FIGURE 21. Functional diagram of the 4072Bdual four-input OR gate IC.

FIGURE 23.Ways of usinga TTL OR gateas a simplebuffer.

FIGURE 24. Waysof cascadingtwo-input ORgates to get upto five inputs.

FIGURE 25. Example of a compoundfive-input OR gate circuit.

FIGURE 22. Method of disabling a TTL OR gate.

Marston3.qxd 5/7/2007 10:41 AM Page 70

MANUFACTURERS - We Purchase EXCESS INVENTORIES... Call, Write, E-MAIL or Fax YOUR LIST.

NO MINIMUM ORDER • All Orders Can Be Charged to Visa, Mastercard, American Express or Discover • Checks and Money Orders Accepted by Mail •Orders Delivered in the State of California must include California State Sales Tax • NO C.O.D • Shipping and Handling $7.00 for the 48 Continental UnitedStates - ALL OTHERS including Alaska, Hawaii, P.R. and Canada Must Pay Full Shipping • Quantities Limited • Prices Subject to change without notice.

MAIL ORDERS TO:ALL ELECTRONICS CORP.

14928 OXNARD ST., VAN NUYS, CA 91411-2610

FAX (818) 781-2653 • INFO (818) 904-0524

E-MAIL [email protected]

QUALITY Parts FAST Shipping

DISCOUNT PricingCALL, WRITE, FAX or E-MAILfor a FREE 96 page catalog.

Outside the U.S.A. send $3.00 postage.

ALLELECTRONICSALLELECTRONICSC O R P O R A T I O N

18 AMP SOLID-STATE RELAY, 3-15VDC CONTROLCrydom # EZ240D18. Control Voltage: 3-15 Vdc. Output: 18 Amps @ 240 Vac. SCR output, low leakage solid state relay. 1.72" x 1.5" x 1.02" high including0.25" QC/solder terminals. Mounting holes on2.2" centers. UL, CSA, CE. CAT# SRLY-18

10 for $9.25 each

MINIATURE 12VDC PUSH-TYPESOLENOIDLedex™. 0.5" diameter x 1" long tubular solenoid with 3/8" diameter threaded bushing for mounting. 1/16" diameterx 1/2" long plunger. 40 Ohm coil. Operates on12 Vdc. 1" wire leads. CAT# SOL-102 $325

each

$1050each

6-CHANNEL TRANSMITTER ANDRECEIVERVex # 276-2153. Transmitter and receiver for remote control of robotics servos. Designed as an add-on kit to allow two human operators to control different aspects of the same robot, it can also be used as the primary control (see note below). 6 channels (4 analog and 2 digital). Two joysticks, each with an X and Yaxis, control the analog channels 1-4.Momentary switches on the front and backoperate the two digital channels. Operates onChannel 89 (75.970MHz). Includes transmitterand receiver with crystals for Channel 89,receiver antenna and sleeve holder for anten-na and interconnect cable between RF receiv-er module and microcontroller. Transmitteroperates on eight AA batteries or one 9.6Vbattery pack. Batteries not included.

Note: We have been told recently that in orderto use this transmitter as a primary control, it isnecessary to use a micro controller module tosplit and amplify the received signal into sixindividual channels. CAT# JS-6 $2995

each

Shop ON-LINE www.allelectronics.comORDER TOLL FREE 1-800-826-5432

MINI-PIEZ0 SIREN, 12 VDC One of the loudest, most annoying piezo-electric sirens we have ever heard. High-pitched, 100 db warble tone strongly encourages intruders to leave. Operates on 6-12Vdc. Compact, only 2.27" long x 1.69" x 1.53." Metal mounting bracket. 6' wire leads. CAT# ES-9 $420

each

10 for $3.90 each • 100 for $3.70 each

10' MUSICAL INSTRUMENTCABLE, 1/4" PHONE PLUGSFlexible 10 foot musical instrument cable with 1/4" phone plugs on each end. Cable jacket labeled "Professional OFCNoiseless Instrument Cable." CAT# MCB-101 $350

each

Rifa #PEH532SAE3330M2330uF, +/-20%, 250V. -40/+ 105C deg.0.87” diameter x 1.63” long. 0.4” lead spacing.CAT# EC-3325

330 UF 250 VSNAP-IN CAPACITOR

$150each

Barber-Colman #CYQM23061-5-2.Permanent magnet. Rated 14 VDC @ 650 mA. Reversible. Sleeve bearing. 400 rpm, 325 mA no load speed. 350 rpm @ 7.5 oz in torque. 650 mA. Continuous duty. 34 oz-install torque@ 2.2 amps. Generator brushless AC output. 6VAC out @ 1800 rpm. Gearhead ratio 10:1.Dimensions: 2” dia. x 3-1/4” long. Offset shaft1/4” dia. x 1” long with flatted side. Face mount.Two tapped holes.CAT# DCM-314

GEARHEAD MOTOR/GENERATOR

$1200each

12VDC 300MASWITCHING POWER SUPPLYFriwo # SPA4UL. Input: 100-240V 50-60Hz. Output: 12Vdc 300mA. 6' cord with 2.1mm coax power plug, center +.CAT# PS-1236

$550each

15MM PIEZO DISC

75 10 for 65¢ each100 for 50¢ eacheach

¢

AVX # KBS-15DA-9C-31. 2" pigtail leads. CAT# PE-53

SOLAR CELLOutput: approximately 3 Volts @ 40 mA. 60mm square x 2.5mm thick epoxy-encapsulated silicon photovoltaic cell. Solid, almost-unbreakable module with solderable foilstrips on backside. Ideal for solar-powered bat-tery chargers and other projects.CAT#SPL-61 $375

each100 for $3.25 each

71 June 2007

Full Page.qxd 5/9/2007 3:10 PM Page 71

Given the popularity ofexergames and the successof the Wii interface, when I

was asked to review the Hydra GameSystem, I couldn’t resist exploring thefeasibility of developing an exergame.This article describes the develop-ment of a simple exergame using thelatest addition to the Parallax line of microcontrollers and a populardual-axis accelerometer.

Exergame Design

The design of an exergame, likethat of other serious games, starts withthe creation of a game design docu-ment that addresses a relevant subset ofthe issues outlined in Table 1. For exam-ple, every exergame should incorporate

fun elements, such as someform of escalating challenge,but not all exergames requiremusic. Of key importance in anexergame design document isidentifying the skill set thatshould be developed in players.This skill set drives the visual,physical, and logical compo-nents of the game design.

A useful construct in designingmost exergames is mapping skills togameplay and a reward system or scoring. For example, an exergamecould replicate the rehabilitation regimen required by a player with anankle injury. If rehabilitation involves

predominantly lateral or side-to-sideankle exercises, then a game thatincorporates left and right ankle flex-ion in gameplay may be appropriate.Moreover, just as an elastic band orother tool can be used to achieve avariety of rehabilitation goals, a singleexergame can often be used toenhance a variety of skills. A game thatemphasizes ankle movement could beused to improve the player’s balanceand body awareness, for example.

The exergame considered here isdesigned to encourage use of a common wobble board. As shown inFigure 1, a wobble board is simply a

Creating an EXERGAME With the

HYDRA GAMESYSTEMHYDRA GAMESYSTEM by Bryan Bergeron

SettingCharactersEffectorsGame FlowScreens & MenusControlsOptionsSounds & Music EnvironmentMapFun Elements

LogicEquipmentCamerasObjectives Introductory MaterialGameplayClosing MaterialScoringSkill SetMedia Assets

EXERGAME DESIGN ELEMENTS

EXERGAMES, typified by Dance Dance Revolution and the more recentWii Sports compilation for the Nintendo Wii, encourage whole body movementover mere thumb flexing. Whether players intend to shave a few extrapounds or to simply interact with a more engaging interface, exergames relyon non-traditional input devices and technologies for gameplay.

FIGURE 1. Wobble board, side(left) and top (right) views.

TABLE 1. Basic exergame design elements. Every element may not beapplicable to a given game.

72 June 2007

Bergeron.qxd 5/7/2007 10:52 AM Page 72

plastic or wooden disc, typically 18inches in diameter. A dome over apivot point in the center of the bottomside allows 15 to 20 degrees of tilt.OPTP is one of several vendors thatoffers affordable models starting atabout $40 (www.optp.com).

Physical therapists and sportstrainers use balance boards with theirclients to rehabilitate ankle injuries,enhance range of motion, and for gen-eral motor skill training. Many runnersand martial artists incorporate wobbleboards in their training programs toincrease flexibility and reduce incidence of injury. The downside ofworking with a wobble board is thatthere is no immediate feedback andthe routines quickly become boring —hence the motivation for an exergame.

The on-screen view of the wobbleboard-controlled exergame is shownin Figure 2. After a series of count-down screens, the player is presentedwith a constantly moving bull’s-eyetarget. While standing on the wobbleboard, the player attempts to adjustthe tilt of the board so that the whitedot constantly tracks the center of thebull’s-eye. The goal of gameplay is totrack the bull’s-eye target as long aspossible within 100 seconds. Contacttime translates directly to score.

To move the dot up on the TV display, the player tilts the wobbleboard forward by pressing her toesdown while simultaneously adjustingher body to maintain balance. Similarly,moving the dot to the left involves theplayer shifting her body weight, press-ing her left leg down, and flexing herankles to the right. Intermediate playerscan stand with their feet together.Advanced players can stand on onefoot while holding their free knee totheir chest or performing a similarlychallenging maneuver. Based on per-sonal use and feedback from severalusers, the game succeeds in transform-ing a typically boring series of exercisesinto a fun and slightly addictive activity.

The following sections describethe Hydra Game System, including thehardware and software, the character-istics of the Memsic 2125 accelerome-

ter, and the software andhardware required tointerface the accelerom-eter to the Hydra.

Hydra GameSystem

The Hydra GameSystem is aptly named,in that it isn’t simplyanother microcontroller board, but isa complete system for game develop-ment. In addition to the Hydra boardand peripherals, the system includes aCD-ROM filled with software and an800+ page book that provides an integrated explanation of the hard-ware environment in the context ofclassic or retro game development.

Working with the Hydra board (seeFigure 3) and library of games, gameengines, and demos — including titlesinspired by Breakout, PacMan, Lock NChase, Q-bert, and Centipede — is liketaking a step back in time to the days ofthe Atari and Commodore-64. AlthoughVGA is supported, most of the demosare written to composite NTSC video,which accounts for the low resolution,retro look of the exergame shown inFigure 2.

HardwareThe main Hydra

board is populated withan eight-core Propellerchip clocked at 80 MHz,a 128 KB EEPROM, and a10 MHz crystal. All threeof these core compo-

nents are socketed for future upgradesand experimentation. The Hydra alsosports a game card expansion port nearthe center of the board, and ports forRCA audio and video out, VGA out,PS/2 mouse and keyboard, RJ-11 serialnetwork, 9 VDC power in, mini-USB,four-pin USB2USER, and a pair ofNintendo NES gamepads.

The Hydra Game System includesa blank experimentation card and a128K EEPROM card, either of whichcan be plugged in to the game cardexpansion port. Additional cards canbe purchased from Parallax; 3V and 5Vpower, eight I/O ports, serial network,USB, and EEPROM lines are availablefrom the 20-pin game card expansionport, and on the EEPROM and experi-mental card solder pads. To facilitate

FIGURE 2. Game screen shots showingwobble board-controlled dot off target(left) and on target (right).

FIGURE 3. Hydra boardwith EEPROM card.

FIGURE 4. 128K EEPROMcard with 2 x 10 header pinssoldered to the I/O pads.

June 2007 73

Bergeron.qxd 5/7/2007 10:52 AM Page 73

74 June 2007

experimentation, I soldered 2 x 10 header pins to the 3 mmspacing, through-hole solder pads, as shown in Figure 4.

Because the I/O lines on the expansion bus are sharedby the VGA connector, VGA output must be disabled touse the expansion port I/O. In addition to the eight I/Olines on the expansion port, the serial network transmit andreceive lines routed to the RJ-11 jack are available for I/O.

Additional components of the Hydra Game System includea compact 9 VDC power brick, USB and RCA cables, a minia-ture keyboard, travel mouse, and a NES-compatible gamepad.The mouse and gamepad are useful for playing games, and thesmall but useable keyboard is primarily used for programmingthe Hydra without a PC using Hydra Basic. Although a rudimen-tary operating system may be downloaded from the onlineforums to facilitate use of Hydra Basic, the utility of the languageis limited by the 32K RAM available on the Propeller chip.

Propeller IDEMy sense of nostalgia evaporated as soon as I started

working with the numerous examples provided on the CD-ROM. Instead of linear Basic, FORTH, or assembler, gameson the Hydra are written using high-level SPIN and, for thetechnically endowed, low-level assembler. SPIN is unusualin that it borrows somewhat from object oriented languagesand supports multiple cores. The multi-core paradigm takessome getting used to, as does the colorful Parallax PropellerIDE, shown in Figure 5. The MS Windows-based IDE can befreely downloaded from the Parallax site.

A feature of the IDE is the optionto either quickly load a program intoRAM during development or load the

program into onboard or expansion card EEPROM. Thelater operation requires a few more seconds. When the128K EEPROM expansion card is inserted, the onboard EEP-ROM is automatically disconnected.

Following the spirit of the SPIN language, the exergamewas developed in about 200 lines of high-level SPIN —much of which was borrowed from or inspired by thedemos on the CD-ROM. The code is available for downloadfrom the Nuts & Volts website (www.nutsvolts.com). Theobjects — akin to include files in C — used in the exergameare TV and graphics drivers from the Hydra Game Systemand the Memsic 2125 driver from the Parallax library. Notethat unlike the Parallax objects, the sources included on theHydra CD-ROM may not be freely distributed.

Because SPIN uses white spaces to indicate block levels, it’s a good idea to use the IDE’s highlight function(Control-I) that shows block relationships. As an example of how white space is used within the IDE, consider the following SPIN code from the exergame:

if || (i_squared - t_squared) < 550 ‘absolute valueif (timeRemaining >0) ‘time variablegr.text(-120,-80,string(“Score!”)) ‘print “Score!”totalPoints := totalPoints +1 ‘add points

Although the IDE is very sophisticated for a microcon-troller system, version 1.05.2 lacks a true debugger. There isan on-board LED and it is possible to write values to thevideo out port, but both approaches are limited. Usingvideo consumes cycles and precious RAM. A traditionaltext-based debugger — such as the one available for theBASIC Stamp microcontrollers — would be more useful.

You’ll also find a small TV with composite video and audioinput — or a computer monitor with a composite video inputport — necessary for efficient game development. If you don’thave a dual monitor setup on your PC, Parallax offers a nice2.5” LCD monitor that supports composite video and audio.

Wobble Board InterfaceThere are several ways to interface a wobble board to

the Hydra to create an exergame. The simplest is to mountfour mercury switches on the wobble board oriented suchthat one switch is closed with the board tilted forward, back,right, and left. Wire each mercury switch in parallel with theappropriate button on the NES game controller and thewobble board becomes a proxy for the controller pad.

Unfortunately, mercury switches are inherently limitedbecause of their sluggish response time and binary output.Finer resolution in direction and degree of tilt requires moreswitches and I/O lines. A more flexible approach is to usean accelerometer that supports continuous sensing of tilt.

The two obvious options for this project are the Memsic2125 dual-axis accelerometer and the Hitachi H48C tri-axisaccelerometer. Both units are supported by Parallax, anddriver objects for each sensor can be freely downloadedfrom the Parallax site. Because only two-axis tilt is required,the less expensive Memsic 2125 is used here.

FIGURE 5. ParallaxPropeller IDE.

Bergeron.qxd 5/7/2007 11:05 AM Page 74

The Memsic 2125 thermalaccelerometer is an example of a microelectro-mechanical machine system(MEMS) based on IC manufacturingtechniques (hence the name MEMSIC).In operation, a heater within theMemsic 2125 warms a bubble of gasthat moves in response to gravity andacceleration of the device. Thermopilesnear the periphery of the bubble senseidentical temperatures when the accelerometer is level anddifferent temperatures if the device is tilted.

Temperature differences detected by the thermopiles areconverted into pulses by the onboard electronics accordingto the relationship illustrated in Figure 6. Acceleration at earthnormal gravity (9.8 m/s2) is considered 0, and the update frequency is approximately 100 Hz at room temperature.

The angle of tilt is calculated with elementary trigonom-etry, given the accelerometer signals from the x and y axes.For example, if the duty cycles of the x- and y-axis signalsincrease equally, then the angle of tilt is equidistantbetween the two positive x and y axes, or 45 degrees. Theamount of tilt in this direction is a function of the magnitudeof the positive shift in duty cycle, as described in Figure 6.Fortunately, the low-level magnitude and direction calcula-tions are handled by the Memsic 2125 driver from Parallax.

Figure 7 shows the dual axis recording of the Memsic2125 used in my exergame. Note the clean square waveoutput and a frequency of just over 100 Hz. There is an obvious difference between the x-axis (top) and y-axis(bottom) duty cycles. According to the formula in Figure 6,the accelerations along each axis are:

Ax = (T1/T2 – 0.5) / 0.125Ax = (4.7ms/10ms – 0.5)/0.125Ax = -0.03/0.125Ax = -0.24g

Ay = (T1/T2 – 0.5) / 0.125Ay = (5.2ms/10ms – 0.5)/0.125Ay = 0.2/0.125Ay = 0.16g

These calculations indicatenegative acceleration — andtherefore tilt — along the x-axis and positive accelerationalong the y-axis of the accelerometer.

Connecting the Memsic 2125 to the game card on theHydra requires four lines. As shown in Figure 8, theaccelerometer requires 5 VDC at 4 mA, ground, and accessto two I/O ports on the Hydra. I used 1/8 watt, 220 ohmresistors on the x- and y-axis output pins of the accelerom-eter and connected these to I/O pins 6 and 7 on the HydraEEPROM card, respectively.

The specifics of mounting a Memsic 2125 on a wobbleboard depend on the design of your particular board. Themount shown in Figures 9 and 10 are specific to the OPTPwobble board. Although not visible in Figure 9, the Memsic2125 is inserted into an eight-pin socket so that the sensorcan be used in other projects. Figure 10 shows the perfboard glued in place, along with the four-pin 0.10” connec-tor on the cable to the 128K EEPROM card on the Hydra.

Game Coding

The core algorithm in the exergame compares the dis-tance between the origin at the center of the screen to thedynamic bull’s-eye and the wobble board-controlled dot. Ifthe distances — the hypotenuses of the triangle incorporatingthe bull’s-eye and the triangle incorporating the dot — are notsignificantly different, then the assumption is that the dot ison target. As in the following SPIN

T1

T2

A = (T1 / T2 - 0.5) / 0.125f = 100 Hz

I/O 7 I/O 6

+5

FIGURE 6. Calculation of acceleration(A) for each axis of the Memsic 2125.

FIGURE 7. X- and y-axisoutput of a Memsic2125 showing differentx and y duty cycles.

FIGURE 8. Wiring ofMemsic 2125 to theHydra EEPROM card.

FIGURE 9. Memsic2125 mounted onsocketed perf board.

June 2007 75

Bergeron.qxd 5/7/2007 11:06 AM Page 75

code, the score is updated and the message “Score!” appearson the screen when the dot tracks the center of the target.

t_squared := (target_x * target_x) + (target_y *target_y)

i_squared := i*i

if || (i_squared - t_squared) < 550 if (timeRemaining >0)

gr.text(-120,-80,string(“Score!”))totalPoints := totalPoints +1

The downside of this simple test for target and dotoverlap is that there are multiple possible dot locations thatwill result in points. However, in practice, this simplificationworks well. A more complete and complex approach is touse a sine lookup table and compute the single point onthe screen where target and player-controlled dot overlapin real time. Readers interested in following this approachcan view several examples in the text accompanying the system.

The Memsic 2125, like every sensor, is imperfect. In addition to device-to-device differences in response and settling time, output from a stationary accelerometer varies

randomly over time.

Figure 11 shows the single-axis output of a Memsic 2125 mountedhorizontally on a stable surface. The5,000 consecutive readings were

collected at 10 Hz using a BASIC Stamp. The output of theaccelerometer is Gaussian, with a mean of 4,908 microsec-onds and a standard deviation of two microseconds.

This output variability is significant in the game, in thatthe position of the white dot visibly jitters even when thewobble board is held stationary. I handle this jitter inaccelerometer output with two simple filter routines writtenin SPIN. They take the form:

if || (acc2 – acc1) > 10 ‘compare acceleration valuesacc1 := acc2 ‘update values if different

acc2 := memsic_output ‘update acceleration valueacc1 := (acc + acc2)/2 ‘average acceleration

The filters are based on value differences instead ofconsecutive readings from the Memsic 2125 because thePropeller is operating at a significantly higher frequencythan the accelerometer.

A final note regarding coding the Hydra is that thisexergame relies on the Memsic 2125 object supplied by Parallax. This object or driver includes a self-calibrationroutine at startup that assumes the accelerometer is level.As such, the wobble board must be positioned close to horizontal at startup.

From Here

The exergame described here is a mere hint of what canbe accomplished with the Hydra Game System. Consideradding a colorful background from the extensive library ofimage files on the CD-ROM that accompanies the system.Sound effects are another obvious addition to the exergame.More importantly, the wobble board interface can be usedwith very little modification on many of the sample games onthe Hydra CD-ROM. Imagine playing a game similar to BreakOut using a wobble board instead of a controller pad.

According toAndre’ LaMothe,developer of theHydra and author ofthe text included withthe system, a 512Kexpansion card is inproduction. The cardwill enable develop-ment of games withbitmapped graphics,more media, and, ingeneral, greater com-plexity. Be sure to visitthe forums on Parallaxand XGameStation for any softwareupdates and hardwareextensions. NV

Co

un

t

0

200

400

600

800

49004895 4905Microseconds

4910 4915 4920

1000

1200

1400

FIGURE 10. Memsicmounted in base of anOPTP wobble board.

FIGURE 11. Single-axisoutput of a level, stationary Memsic 2125;5,000 consecutivesamples at 10 Hz.Ambient temperatureis 23°C.

Hydra Game DevelopmentKit, Memsic 2125

accelerometer, and softwareobjects available

from Parallax.wwwwww..ppaarraallllaaxx..ccoomm

Hydra Developer’s Forum.FFoorruummss..ppaarraallllaaxx..ccoomm//ffoorruummss

XGameStation.Andre’ LaMothe’s

website for the Hydra,documentation, and forums.

Bergeron, B., DevelopingSerious Games. 2006:

Thompson.

RESOURCES

76 June 2007

Bergeron.qxd 5/7/2007 11:06 AM Page 76

June 2007 77

Full Page.qxd 5/9/2007 3:38 PM Page 77

The Nuts & Volts Hobbyist BOOKSTORESelected T i t les for the E lectron ics Hobbyist and Technic ian

NNuuttss && VVoollttss ooff BBAASSIICCSSttaammppss —— VVoolluummee 77

by Jon WilliamsNuts & Volts of BASICStamps,Volume 7includes articles#129-140 from Nuts& Volts Magazine. Inthis 2006 collection,BASIC Stamp 1,BASIC Stamp 2,SX/B, and Propellerprogramming areexplored in a seriesof real-world applications.This book isuseful for the Nuts & Volts reader,newcomers to BASIC Stamp, SX, andPropeller microcontroller projects, andseasoned programmers looking for newideas. $$1144..9955

NNuuttss && VVoollttss ooff BBAASSIICCSSttaammppss —— VVoolluummee ##66

by Jon WilliamsNuts & Volts of BASICStamps — Volume 6includes articles #117-128, written for 2005.Article topics consistof RFID Readersand UltrasonicMeasurement, SX/Band the ProfessionalDevelopment Board,the advanced MIDIreceiver, programming the SX microcon-troller in BASIC, mastering the MC14489display driver, and more! The Nuts & Voltsof BASIC Stamps books are a favoriteParallax technical pick and are a tremen-dous technical resource for all PBASICprogramming projects. $$1144..9955

AAuuddiioo PPoowweerr AAmmpplliiffiieerr DDeessiiggnnHHaannddbbooookk —— FFoouurrtthh EEddiittiioonn

by Douglas SelfWhether you are adedicated audiophilewho wants to gain amore completeunderstanding of thedesign issues behind atruly great amp, or aprofessional electronicdesigner seeking tolearn more about theart of amplifierdesign, Douglas Self ’sHandbook is theessential guide to design principles andpractice.The fourth edition includes newmaterial on DC offset protection circuitry,the design of DC servos, and electricalsafety and safety standards. $$4444..9955

ELECTRONICS

IIff yyoouu ddoonn’’tt sseeee wwhhaatt yyoouu nneeeeddhheerree,, cchheecckk oouutt oouurr oonnlliinnee ssttoorree aattwwwwww..nnuuttssvvoollttss..ccoomm ffoorr aa ccoommpplleettee

lliissttiinngg ooff tthhee ttiittlleess aavvaaiillaabbllee..

PPrraaccttiiccaall EElleeccttrroonniiccss HHaannddbbooookk::SSiixxtthh EEddiittiioonn

by Ian Sinclair/John DuntonIan Sinclair’s PracticalElectronics Handbookcombines a wealth ofuseful day-to-day elec-tronics information,concise explanations,and practical guidanceessential to anyoneinvolved in electronicsdesign and construc-tion.The collection ofkey data, fundamentalprinciples, and circuitdesign basics provides an ideal referencefor a wide range of students, enthusiasts,technicians, and practitioners of electronicswho have progressed beyond the basics.The sixth edition is updated throughoutwith new material on microcontrollers andcomputer assistance, and a new chapter ondigital signal processing $$3399..9955

TTrroouubblleesshhoooottiinnggEElleeccttrroonniicc EEqquuiippmmeenntt

by R. S. KhandpurFrom cell phones tomedical instrumentsto digital and micro-processor basedequipment, thishands-on, heavilyillustrated guideclearly explains howto troubleshoot,maintain, and repairall types of electricalequipment.Theauthor covers all the essentials such asnecessary tools, soldering techniques, test-ing, fundamental procedures, and mechani-cal and electrical components. $$4499..9955

PPrraaccttiiccaall EElleeccttrroonniiccss ffoorr IInnvveennttoorrssby Paul Scherz

This intuitive, applica-tions-driven guide toelectronics for hobby-ists, engineers, and stu-dents doesn't overloadreaders with technicaldetail. Instead, it tellsyou — and shows you— what basic andadvanced electronicsparts and componentsdo, and how theywork. Chock-full of illustrations, PracticalElectronics for Inventors offers over 750hand-drawn images that provide clear,detailed instructions that can help turntheoretical ideas into real-life inventionsand gadgets. $$3399..9955

CClloosseedd CCiirrccuuiitt TTeelleevviissiioonn ——TThhiirrdd EEddiittiioonn

by Joe CieszynskiClosed CircuitTelevision (CCTV)surveillance remains agrowing industry inresponse to increasedsecurity threats,and while newdevelopments havebrought clearer images,digital recording, andhigh speed datatransmission, effectivesecurity systems stillrely upon proper specification andinstallation by engineers with an in-depthknowledge of CCTV principles andtechnology.The third edition of ClosedCircuit Television provides a thorough technical guide for all those involved inthe design, specification, installation, andmaintenance of CCTV systems. $$3399..9955

EElleeccttrroonniicc GGaammeess ffoorrtthhee EEvviill GGeenniiuuss

by Thomas PetruzzellisYou can have a wickedamount of fun on yourway to becoming agame master! InElectronic Games for theEvil Genius, popularhow-to author TomPetruzzellis gives youeverything you needto build 35 excitinggames and gadgets.Youget complete, easy-to-follow plans, with clear diagrams andschematics, so you know exactly what'sinvolved before you begin. Packed with funprojects that you'll love to build and playwith, this guide develops game expertiseone simple step and project at a time.$$2244..9955

EElleeccttrroonniicc CCiirrccuuiittss ——FFuunnddaammeennttaallss && AApppplliiccaattiioonnss::

TThhiirrdd EEddiittiioonn by Mike Tooley

In Electronic Circuits, MikeTooley provides all theessential informationrequired to get to gripswith the fundamentals ofelectronics, detailing theunderpinning knowledgenecessary to appreciatethe operation of a widerange of electroniccircuits, including ampli-fiers, logic circuits, power supplies, andoscillators.The third edition now offers aneven more extensive range of topics, withextended coverage of practical areas suchas circuit construction and fault finding, andnew topics including circuit simulation,electronic CAD, and a brand new chapterdevoted to the PIC microcontroller.$$3344..9955

NNEEW!W!

78 June 2007

NNEEW!W!

NNEEW!W!

BookstoreJun07.qxd 5/10/2007 3:32 PM Page 78

CALL 1-800-783-4624 today!Or Order online @ www.nutsvolts.com

2255 HHoommee AAuuttoommaattiioonn PPrroojjeeccttssffoorr tthhee EEvviill GGeenniiuuss

by Jerri LedfordComputer technologyhas caught up withhome automation, andit’s now easy and inex-pensive to automateeverything in a house— including lighting,security, appliances,entertainment, andenvironmental condi-tions — and here’show to do it! Thiswell-illustrated resource offers 25 com-plete home automation projects thatrequire only basic household tools and theinstructions found within its pages.$$2244..9955

PPCC MMooddss ffoorr tthhee EEvviill GGeenniiuussby Jim Aspinwall

If you yearn for thecoolest, most crazed‘puter around, PC Modsfor the Evil Genius is thekey to the kingdom!This book shows youhow to superchargeyour PC and create ajaw-dropping systemthat cannot be pur-chased off any shelf,anywhere! You getcomplete, easy-to-follow plans, clear dia-grams and schematics, and lists of parts andtools, so you know what's needed beforeyou begin. $$2244..9955

MICROCONTROLLERS110011 OOuutteerr SSppaaccee PPrroojjeeccttss ffoorr tthhee EEvviill GGeenniiuussby Dave Prochnow

The sky is not thelimit! If you yearn totouch the stars, 101Outer Space Projects for the Evil Genius haseverything you need to explore the universefrom the comfort ofyour own home.Whether you're abeginner stargazer ora more experiencedastronomer, you'll find an outstanding project to satisfy you, from model rocketsand celestial maps to space robots,GPS systems, and much, much more.Full of easy-to-follow plans and clearschematics for each project, as well as lists of materials and tools so you knowexactly what's involved before you begin.$$2244..9955

EElleeccttrroommeecchhaanniiccaall DDeevviicceess &&CCoommppoonneennttss IIlllluussttrraatteedd

SSoouurrcceebbooookkby Brian Elliott

Master the key elements of electromechanical components.Essential to thedesign, repair, oroperation of yourelectromechanicaldevices, this quick-find reference provides illustrations,descriptions, and relevant calculations for 2,000 time-testedelectromechanical components.$$8899..9955

TTaakkee TThhiiss SSttuuffff aanndd HHaacckk IItt!!by Dave Prochnow

Transform commonhousehold items intoreally cool stuff.Youdon't need to be anelectronics genius toget started turningeveryday items intohigh-performing won-ders.With how-toguru DaveProchnow's step-by-step directions andfully illustrated plans, even beginners canhack their way to a high-tech home, coolertoys, and less yard work. Certain to fireyour imagination and start you plottingnew, original, and even more creative won-ders you can make from ordinary house-hold items, Take This Stuff and Hack It! isthe perfect gift for your inner inventor.$$2277..9955

PPIICC BBaassiicc PPrroojjeeccttssby Dogan Ibrahim

Covering the PICBASIC and PICBASIC PRO compil-ers, PIC Basic Projectsprovides an easy-to-use toolkit fordeveloping applica-tions with PICBASIC. Numeroussimple projects giveclear and concreteexamples of howPIC BASIC can beused to develop electronics applications,while larger and more advanced projectsdescribe program operation in detail and giveuseful insights into developing more involvedmicrocontroller applications. $$2299..9955

PPrrooggrraammmmiinngg tthhee PPIICCMMiiccrrooccoonnttrroolllleerr wwiitthh MMBBAASSIICC

by Jack SmithNo microcontroller isof any use withoutsoftware to make itperform useful func-tions.This compre-hensive referencefocuses on designingwith Microchip’s mid-range PIC line usingMBASIC, a powerfulbut easy to learn pro-gramming language. Itillustrates MBASICs abilities through aseries of design examples, beginning withsimple PIC-based projects and proceedingthrough more advanced designs. $$5599..9955

NEW 2006 CD-ROMS!NNuuttss && VVoollttss CCDD--RROOMM

Here’s some goodnews for Nuts &Volts readers!Along with all 24issues of Nuts &Volts from the2004 and 2005calendar years,the 2006 issuesare now available,as well.TheseCDs include all of Volumes 25, 26, and 27,issues 1-12, for a total of 36 issues (12 oneach CD).These CD-ROMs are PC andMac compatible.They require AdobeAcrobat Reader version 6 or above.AdobeAcrobat Reader version 7 is included onthe discs. $$2244..9955 –– BBuuyy 22 oorr mmoorreeaatt $$1199..9955 eeaacchh

NNEEW!W!

June 2007 79

SSEERRVVOO CCDD--RROOMMAre you ready forsome good news?Along with thefirst 26 issues ofSERVO Magazine,all issues from the2006 calendaryear are nowavailable, as well.These CDsinclude all ofVolume 1, issues 11-12,Volume 2, issues1-12,Volume 3, issues 1-12, and Volume 4,issues 1-12, for a total of 23 issues alltogether.These CD-ROMs are PC and Maccompatible.They require Adobe AcrobatReader version 6 or above.Adobe AcrobatReader version 7 is included on the discs.$$2244..9955 –– BBuuyy 22 oorr mmoorree aatt$$1199..9955 eeaacchh

PROJECTS

WWEE AACCCCEEPPTT VVIISSAA,, MMCC,, AAMMEEXX,, aanndd DDIISSCCOOVVEERR PPrriicceess ddoo nnoott iinncclluuddee sshhiippppiinngg aannddmmaayy bbee ssuubbjjeecctt ttoo cchhaannggee.. AAsskk aabboouutt oouurr 1100%% ssuubbssccrriibbeerr ddiissccoouunntt oonn sseelleecctteedd ttiittlleess..

HOME COMPUTERS

NNEEW!W!

BookstoreJun07.qxd 5/10/2007 3:32 PM Page 79

Today, there is actually a fiber opticcable glut. Miles and miles of it

were laid in the early Internet boomdays of 1998-2002, then the crash.Lots of that cable is still unused or asthey say in the industry, it is “dark”fiber. With booming Internet activitygoing on today and the push towardTV over the Internet, lots of that fiberis being brought out of the darknessand even more new fiber is being laidfor special applications.

Fiber optic communications systems are not something we think ofevery day even though we all usethem. Don’t think so? Consider this.When you make a long distance call,the fiber network is used. In fact, inmaking any phone call today — wiredor wireless — somewhere in the telephone system your call is beingcarried at least part way by light wavesover fiber. Do you have cable TV?(Over 80% of the US population does

so you probably do, too.) Mostcable TV systems are what

we call hybrid fiber cable (HFC) systems meaning that a main fiberoptic backbone cable carries the TVsignals to a box in your neighborhoodwhere the connection continues fromthat box to your home over RG-6/U75-ohm coax. If you use email or the Internet, you use fiber because the backbone of the Internet is fiber.And most of that fiber is buried andinvisible.

Recently, I attended the OpticalFiber Conference (OFC) in Anaheim,CA. I have not been to that conferencein a few years as the early 2000’s werereally rough on the fiber industry.When the Internet bubble burst in2001, the fiber industry essentially collapsed. It did not go away, of course,but little new equipment was sold, lotsof R & D was abandoned or put onhold, start-up companies folded, andlots of other companies were boughtand/or merged. All that consolidationturned out to be good and business hasemerged even stronger today. The OFC

was booming again this year as theindustry renews its growth cycle. Hereis a look at some of the latest trendsand developments in this field whichaffect us all, even if you think it doesn’t.

REMEMBER HOW ITWORKS

Fiber optic communications is thetransmission of light over a glass or plastic fiber cable. The light is generatedby a laser in most cases, but in somesmaller, slower networks an LED is used.The light is infrared (IR) so you cannotsee it as it is lower in frequency than redlight. The light color or frequency is usually expressed in wavelengths (λ)and that is measured in nanometers(nm). A nanometer is one billionth of ameter. IR light extends from about 700to 1,600 nm. The most common IRoperational wavelengths are 780, 850,1,310, 1,490, and 1,550 nm. The 780nm wavelength is the common TVremote control frequency while 1550nm is the main long distance high speedoperating wavelength.

In any case, since most signals aredigital data today, the binary signalssimply modulate the light by turningthe laser light off and on creating pulses. This is called on-off keying(OOK) or amplitude shift keying

OPEN BY LOUIS E. FRENZEL W5LEF

COMMUNICATIONTHE LATEST IN NETWORKING AND WIRELESS TECHNOLOGIES

THE WORLD HAS BEEN REWIRED MANY TIMES over the decades. Telegraphand telephone wiring came first. Then electrical power. (Yes, electrical powerwiring actually came after the telegraph and telephone wiring. Doesn’t seemright does it?) Shortly after that came cable TV wiring. Computer networkwiring was next.Then fiber optic cable.There has been some overlap of those,of course, but that is the general sequence.

A typical optical transceiver or transponder, about the size of a package of gum. Mounts on the printed circuit boards

of networking equipment like routers. Contains the lasertransmitter and photo diode receiver and all the

related circuitry to perform optical to electricalconversions and vice versa. This one is called

a small form factor pluggable (SFP+) for short range (SR). It uses a 850 nm laser

and operates at 10 Gb/s. Photo courtesy of Picolight (now JDSR).

FIBER OPTICS — The InvisibleCommunications Network You Use Every Day

80 June 2007

OpenComm.qxd 5/9/2007 10:51 AM Page 80

(ASK). The light pulses travel down thefiber and eventually encounter a photodiode at the receiver that converts thelight back into a binary signal.

Data in the long distance andInternet back bones are usually sentwith a protocol standard known as theSynchronous Optical Network or Sonet.What it does is package data into blocksor frames of 810 bytes of data and sendit at one of several standard data rates;the slowest is 51.84 Mb/s and the fastestis 39.812 Gb/s. Most data exchange isdone at the 2.488 and 9.953 Gb/s rates.See Table 1 for the Sonet standard rates.

Sonet networks are either point-to-point or in rings. The long haul networks are known as wide area networks (WANs). When Sonet is usedin smaller city or town rings, it is calleda metropolitan area network (MAN).

Ethernet — the local area network-ing (LAN) standard — now sends dataover fiber (and copper) LANs at 1 Gb/sand 10 Gb/s. Data is by packets ratherthan synchronous frames so the formatis less complex. High speed Ethernet isalso being more widely used in MANsand in some cases, WANs like Sonet.The IEEE (Institute of Electrical andElectronics Engineers), who standardiz-es Ethernet, is working on a 100 Gb/sstandard for long haul fiber networks.

FASTER AND FARTHERIn the computer, electronics, and

communications fields, the ultimate andon-going goal is to make everything gofaster and at a longer distance. Thesame is true in fiber optics. For years,the average long distance data rate overthe backbone was 2.5 Gb/s (actually2.488 Gb/s Sonet rate). Today, that hasbeen increased to an average of 10Gb/s. Most long distance calls and virtually all Internet messages go at that10 Gb/s rate through the main routersin the system. The distance is roughly amaximum of several hundred kilometersbefore the light signals get too weak.They then need to be converted back to electrical signals where they areamplified, reshaped, and otherwise rejuvenated before being convertedback to light and sent on their way.

Now the push is on to boost datarates and extend the range of the light

signals. Before the technology crash in2001, there was an effort to boost thespeed to 40 Gb/s (39.812 Gb/s Sonetrate). That work has now beenrenewed and there are lots of newproducts to support that data rate.Network providers are beginning tooffer services at that speed. Verizonrecently announced that some of theirnetwork segments in the northeast UShave already been bumped up to the40 Gb/s rate. And work is on the wayto move that up to 100 Gb/s.

Besides the IEEE effort to build a100 Gb/s Ethernet, other efforts areunder way to boost the data rate to 100Gb/s and beyond. Some of these areSonet type systems while others are proprietary, but progress is being made.One of the easiest ways to get to 100Gb/s over a single fiber is to use what iscalled dense wavelength division multi-plexing (DWDM). This is a techniquewhere a very high speed data stream isdivided up into many slower streams.These streams are then transmittedsimultaneously down the same fiber, butwith each stream modulating a differentlight wavelength. The different “colors”of light travel down the fiber togetherand are separated out by filters at thereceiver where they are then recom-bined back into the fast single stream.

Most of the first 100 Gb/s systemsare using DWDM. But single wave-length 100 Gb/s is tough. One of themain reasons is that glass fiber greatlyattenuates and distorts the light. Theseproblems are called polarization modedistortion (PMD) and chromatic disper-sion. New types of fiber help to mitigatethe problems but mostly the problemsare dealt with by an equalization tech-nique implemented at the receiver. Thesignals are predistorted in a special wayand the receiver corrects for them usingfast digital signal processing techniques.

Another solution lies in using different modulation methods. Thestandard OOK or ASK is being replacedby more sophisticated modulationtechniques like differential phase shiftkeying (DPSK) and differential quadra-ture phase shift keying (DQPSK). Anold telephone system modulationmethod called duobinary has also beenapplied. All of these help overcome theattenuation and distortion allowing

faster data rates over longer distances.There are lots of demo 100+ Gb/s

systems. It will be a few more yearsbefore we see standards and equipmentfor those rates, but they are on the way.Why? Because of the greater load theInternet carries with the ever-increasingmusic downloads and the forthcomingInternet video. Companies will beginoffering movies-on-demand or video-on-demand, as well as Internet protocol television (IPTV) that is designed tocompete with the cable TV companies.The current Internet structure and bandwidth can handle some video now,but it will eventually be overwhelmed ifvideo becomes popular on the Internet.The new 100+ Gb/s technology is onthe way to solve this problem.

PASSIVE OPTICALNETWORKS

Another hot optical topic today isthe PON. Passive Optical Networks(PONs) are fiber optical networksdesigned so they do not use an activerepeater or other equipment betweenthe source central office and a home orbusiness. Right now, most individuals

O P E N C O M M U N I C A T I O N

TABLE 1. Sonet DataStandards and Rates

STS means synchronous transportsignal and OC means optical carrier.

Sonet Level Data Rate STS-1/OC-1 51.84 Mb/sSTS-3/OC-3 155.52 Mb/sSTS-12/OC-12 622.08 Mb/sSTS-48/OC-48 2.488 Gb/sSTS-192/OC-192 9.953 Gb/sSTS-768/OC-768 39.812 Gb/s

Splitter component.

June 2007 81

OpenComm.qxd 5/8/2007 1:28 PM Page 81

and businesses get their Internet servicevia the cable TV system or the phonecompany’s DSL lines. While both arefast, they are running out of steam,especially DSL. The ideal high speedservice is fiber but it is more expensiveat the moment. The ultimate goal is torun fiber to the home (FTTH) and use itto supply fast Internet access, phoneservice via voice over IP, and IPTV.

PONs make this possible becausethey are fast and reasonably inexpensive

due to their totally passive nature. Forlong haul fiber networks, the signals mustbe converted from optical to electricaland back to optical (OEO) to rejuvenatethem in case of fiber loss and/or distor-tion. Such OEO repeaters are expensive.By eliminating them and just running thecables only, costs are cut dramaticallymaking PONs a viable alternative to current methods like DSL and cable TV.

Asia (Japan and Korea, particular-ly) and some parts of Europe already

use EPON, a system based on theEthernet standard. Data is transmittedat 1 Gb/s downstream over the fiber tothe home on 1,490 nm where itencounters splitters that divide theoptical signal and send it off to multiplehomes or businesses. A splitter is just apassive light divider with no electron-ics. Splitters are available to divide thesignal by a ratio of 1:4, 1:8, 1:16, 1:32,or 1:64. A splitter is also a combinerwhere it can take multiple light signals,add them together, and send the combination back to a central office.The upstream data rate is also 1 Gb/s,but it rides on a 1,310 nm wavelength.

In the US, Verizon has initiated itsFiOS system using a PON in someparts of the country and selling theservice as the faster alternative to cableTV and DSL. AT&T is also testing a similar system for IPTV. Fiber is a bitmore expensive, but the basic daterates are in the 30 to 50 Mb/s; manytimes faster than conventional services.It can easily handle multiple HDTVchannels, as well as VoIP phone serv-ice and Internet access. Several millionhomes already use it and more arebeing rolled out over the coming years.

The technology is referred to asGPON or Gigabit PON. The basicdownstream data rate is 2.488 Gb/son 1,490 nm with a fast 1.244 Gb/supstream rate on 1,310 nm. A sepa-rate downstream wavelength of 1,550nm is reserved for TV. While each customer does not get the full 2.488Gb/s speed, the system divides the faststream among the customers who areserved by passive fiber and splitters.

Fiber is widely used in 1 Gb/s and10 Gb/s Ethernet LANs and in FibreChannel — a type of network widelyused in storage area networks, largearrays of hard disk storage systems.The fiber provides 1, 2, 4, 8, or 10Gb/s of speed so that servers canaccess data on the disk drives fast.

As prices continue to drop andthe pressure continues to build forIPTV and faster services, fiber will bemore widely adopted further reducingprices. Fiber truly is the fastest datacommunications medium availableand it will grow at an even faster rateas the demand for Internet speed andbandwidth continues. NV

82 June 2007

OpenComm.qxd 5/8/2007 1:29 PM Page 82

Silicon Valley’s Electronics Marketplace

Logon to our website for secure shopping cart, powerful

search engine, and latest news! www.halted.com

Call 1-800-4-HALTED (1-800-442-5833) to order... ...or use our web search! Search

Electro-Hobbyist Alert -- HSC is your source!

Three Retail Stores to serve you!Main Office - Mail Orders...3500 Ryder St., Santa Clara, CA 95051Santa Clara 1-408-732-1573Sacramento 1-916-338-2545Rohnert Park 1-707-585-7344

Since 1964!...

Order Toll-Free: 1-800-4-HALTED (442-5833)

or...ONLINE AT: www.halted.com

Silicon Valley’s BEST place to shop for Electronics!

Look for us on...

seller ID:hscelectronicsupply

HSC#21369 $2.50

12 VDC Hobby Motor1” dia., Qty Discounts!

USB Mini-Footprint Keyboard

HSC#20972 $19.95

“Backpack Bantam”Parallel-port external CD ROM

HSC#21154 $95.00

29.4 GHz Transceiverwith 12” dish -- Wow!

HSC#20999 $29.50

RF Transistor Engineering Kit54 different devices

HSC#19312 $12.50AC Adaptor, 12VDC, 3.4A

HSC#21061 $19.50

HSC#80849 $27.50Vicor 48VDC 2.1A Flatpac Supply

HSC# 20829 $12.50PCMCIA DVD/MPEG Video Card

HSC#21371 $4.95

HSC#21153 $12.50

Tripplite Outlet Strip, 5 ft. long

External 3.5” IDE Drive Case

Got excess electronic inventory? Send us your list or give us a call, we’d be happy to make an offer!

Deals @ HSC!

Peltier Module - Electrocooler!

HSC#19976 $19.95

HSC#80812 $12.95

Small DC Gearmotor6 - 12 VDC, 3 - 6 RPM

HSC#80822 $14.95USB 2.0 to IDE Drive Adaptor

♦ V

Cushcraft 710 - 750MHz Antenna

HSC#20794 $39.95Logitech QuickCam Express

HSC#80813 $24.95

HSC# 80797 $119.00

♦ Fujitsu PenCentra 130 computer♦ 131 MHz NEC VR4121 MIPS CPU♦ 32MB DRAM, 24MB ROM, 8MB Flash♦ Color DSTN Touch LCD 640 x 480♦ PCMCIA, VGA, PS2, USB, SIO ports♦ Win CE 2.11 Pro in PROM (no disks!)♦ Microsoft Pocket Office, Outlook, IE♦ “Radio Ready” for LAN/WAN PC Card♦ Internal microphone, speaker & jacks♦ Stylus, Mini Keyboard, Dock & PS♦ New, never used, 90-day warranty!

Fujitsu PenCentraTablet Computer -

Clearance!

♦ Toshiba MK6015MAP 6.0 GB Drive♦ 2.5” SATA Interface -- New!

HSC#21403 $14.95♦ Samsung MP0603H 60.0 GB Drive♦ 2.5” SATA Interface -- New!

HSC#21399 $59.95♦ External USB-interface 2.5” Case♦ Bundled Price with above -- reg 14.95!

HSC#80824 $12.50

700MHz TransceiverHobbyist Special!

HSC#21067 $19.95

Fujitsu Laptop Power Supply16VDC, 3.75 A, Fits many models

HSC#21183 $24.95

Solar Panel 4.7 - 5.0 VDC, .25W60 x 60 mm, CuInSe

HSC#80821 $4.95

Laptop Hard Drives!

Belden Blowout!

HSC#21379 $149.00

HSC#21381 $149.00

♦ Belden 8760 Twisted Pair Cable♦ Two 18 AWG stranded conductors♦ Beldfoil 100% shield w/ drain wire♦ 1000’ Easy Box Dispenser - list $405!

Genuine Belden Cable at super prices!♦ Belden 8240 RG-58/U Coax Cable♦ 20 AWG center cond., 95% shield♦ Black PVC jacket, .193” dia.♦ 1000’ Easy Box Dispenser- list $431!

HSC#80842 $12.50

HSC#21380 $149.00

♦ Belden 9502 2-Twisted Pair Cable♦ Four 24 AWG stranded conductors♦ Beldfoil 100% shield w/ drain wire♦ 1000’ Easy Box Dispenser- list $526!

Even before there was a place called “Silicon Valley”, HSC was the favorite stop of hardware hackers,techno-tinkerers, entrepreneurs and engineers on a budget! We have been buying and selling the Valley’sexcess inventory for 40 years now, and our collection is second-to-none! We are also factory-authorizeddistributors for many fine lines of parts, tools, equipment and accessories, so we feel we should be your firststop when shopping for electronic basics. Give our ever-expanding website a try and see what we mean!

12 VDC Hobby Motor1.25” dia Globe IM-13

Terms: Some quantities limited; all items are subject to prior sale. Minimum order: $10.00plus shipping. Orders under $20.00 subject to $5.00 handling fee, in addition to shipping.All orders shipped by UPS Surface unless otherwise specified. $9.00 UPS charge addedfor COD. Visit our website for detailed information on domestic and international shipping.

Have you signed up for our e-mail list yet? We aresending out special offers to our special customers!

Just log on to www.halted.com and sign up...You’ll be the first to know about our latest inventory,

sales promotions and limited-time pricing!We never sell or share our customer info, and mail only to registered customers.

June 2007 83

Full Page.qxd 5/9/2007 4:05 PM Page 83

If you’ve had the time and interest to take in our previousC8051F120 discussions, you have already been intro-

duced to many of the C8051F120’s on-chip peripherals. Thismonth’s collection of technical speak, C8051F120 C sourcecode, pictures, and graphics will cover the remainder of theC8051F120 peripherals that we have not yet examined.

Up to this point, everything hardware has been based onthe electronics you see in Photo 1. The collection of activeand passive electronic components surrounding theC8051F120 microcontroller in Photo 1 makes up a SiliconLaboratories C8051F120 Development Board, which is partof a Silicon Laboratories Development Kit. With the assistance of the Silicon Laboratories USB Debug Adapteryou see in Photo 2, I can use the C8051F120 DevelopmentBoard to exercise all of the C8051F120’s on-chip peripherals.All of the C8051F120’s analog-to-digital converter inputs,comparator inputs, comparator outputs, digital-to-analogconverter outputs, general-purpose I/O port pins, voltage reference inputs, voltage reference outputs, capture inputs,PWM outputs, general-purpose timer outputs, counter out-puts, and serial ports are available to us on the C8051F120

Development Board byway of pins, screw termi-nals, a D-shell connector,and a 96-pin expansion

I/O connector. This high accessibility of C8051F120 signalsallows me to use a Cleverscope to show you waveforms,logic levels, and voltages that are generated in response tostimuli introduced by the C programming language.

USB is the big thing in personal computers these days.However, as long as microcontroller hardware continues toinclude on-chip UARTs, RS-232 will live. So, let’s begin thismonth’s discussion by putting some frills into the UARTcode we discussed previously.

UART INTERRUPTEDWe initialized and activated the C8051F120’s UART0

in the previous Design Cycle column. However, we didn’tcare to listen for other intelligent electronic devices as wewere using UART0 to do all of the talking. So, this timearound, we’ll add some ears to our UART0 code.

If you’re just tuning in, we used the Configuration Wizard2 application to lay the groundwork for much of the UART0code we generated in previous Design Cycle discussions. Wewill continue to use the Configuration Wizard 2 applicationas we go about enabling and activating the remainder of theC8051F120 peripherals we are yet to encounter. However,there are some things the Configuration Wizard 2 cannot dofor us. For example, the Configuration Wizard 2 is not

designed to allocate UART0 transmit and receive buffers in the C8051F120’s SRAM area.Generating interrupt handler routines is another task that theConfiguration Wizard 2 is notsuited for. That leaves us to useour noggins to augment the basicUART0 code that was providedso graciously to us by the

WORKING WITH PERIPHERALS

DESIGN BY PETER BEST

CYCLE

PREVIOUS DESIGN CYCLE COLUMNS have focused on providing you with anin-depth technical view into the Silicon Laboratories C8051F120 microcontroller.All good things must come to an end and this month’s installment of DesignCycle will wrap up our look at the C8051F120 microcontroller.

THEADVANCED TECHNIQUES FOR DESIGN ENGINEERS

84 June 2007

PHOTO 1. Everything you needto get an understanding of howthe C8051F120 and its on-chipperipherals work can be foundon this board.

PHOTO 2. Couple this littlebugger with the Keil µVision3 8051 C Development Suite andtake a journey into the C8051F120’sinner spaces.

DesignCycle.qxd 5/8/2007 1:18 PM Page 84

Configuration Wizard 2 application.Our goal is to write some C code to implement an

interrupt driven RS-232 communications engine using theC8051F120’s UART0 as the central hardware component.The first order of business is to allocate transmit and receivebuffer space within the C8051F120’s SRAM. Here’s thecode behind the buffer allocation:

// size of serial transmission buffer#define TxBUFLEN 8#define TxBUFMASK (TxBUFLEN - 1)// transmission buffer start indexunsigned char TxHead;// transmission buffer end indexunsigned char TxTail;// storage for transmission bufferchar xdata TxBuf[TxBUFLEN]

// size of serial receiving buffer#define RxBUFLEN 16#define RxBUFMASK (RxBUFLEN -1)// receiving buffer start indexunsigned char RxHead;// receiving buffer end indexunsigned char RxTail;// storage for receiving bufferchar xdata RxBuf[RxBUFLEN];

The transmit and receive buffers have a few things incommon. They both must be allocated in powers of 2. Thatis, the least significant bit of the buffer length must alwaysbe zero. Thus, the transmit and receive buffers are allocated as 2, 4, 8, 16, 32, 64, 128, etc., bytes in length.The reason for this is that we want the transmit and receivebuffer mask values to contain a 1 for every buffer locationexcept buffer location zero. For instance, our transmitbuffer length (TxBUFLEN) is equal to 8 which is 0b1000(the 0b denotes binary just as 0x represents hexadecimal).The transmit buffer mask value (TxBUFMASK) is derived bysubtracting 1 from the TxBUFLEN value, which results in aTxBUFMASK value of 0b0111. Seven transmit buffer locations are represented by 0b0111 with the zero transmitbuffer location representing the eighth transmit buffer location. If we break down the creation of the receivebuffer mask (RxBUFMASK) value, we will end up with0b1111, which touches the 15 receive buffer locations following receive buffer location zero. You’ll get to see howthe transmit and receive buffer masks are used when weexamine the UART0interrupt handler code.

As long as we keepour transmit and receive buffer lengthsbelow 256 bytes, we can use eight-bit character pointers todelineate the transmitand receive buffers’beginning (Head) andend (Tail). By incorpo-rating the Head and Tail

in our buffer scheme, both of the transmit and receivebuffers can be considered to be circular. Incoming buffercharacters are stored in the buffer Tail address and outgoingbuffer characters are taken from the buffer Head address.Thus, the Head is always chasing the Tail and the buffer isconsidered empty when the Head address is equal to theTail address. Conversely, the buffer is full when the Tailaddress is one less than the Head address.

To give you a better picture of the receive buffermechanics, I initialized all of the C8051F120 on-chipperipherals, turned on the UART0 interrupts, and entered anever-ending loop to capture 16 characters I sent from apersonal computer running Tera Term Pro. The results areshown in the µVision3 Watch Window I captured for you inScreen Shot 1. By declaring the buffer areas using “char xdata,” both of the transmit and receive buffers areallocated in the C8051F120’s on-chip 8K XRAM memoryarea. Since the transmit and receive buffers are so small, we could have also allocated them into the C8051F120’s256-byte SRAM area using “char idata” in the buffer declaration statements.

With the UART initialized to run in eight-bit mode withits interrupts active and the transmit and receive buffersallocated, our next step entails writing the receive interrupthandler. No sweat. Coding the receive interrupt handler is awalk in the park. Here’s the receive interrupt handler code:

static void com_isr (void) interrupt 4// RECEIVE INTERRUPT HANDLERunsigned char c;if (RI0)

c = SBUF0; //read characterRI0 = 0; //clear interrupt request flag

//check for end of receive bufferif (RxHead + RxBUFLEN != RxTail)

//put character into bufferRxBuf[RxTail++ & RxBUFMASK] = c;

T H E D E S I G N C Y C L E

June 2007 85

SCREEN SHOT 1. The 16 characters I keyed into the TeraTerm Pro window are shown in the hex dump areabeginning at address 0x00000 and ending at address0x0000F. Note that the debug window points out thebeginning address (X:000000) of the receive buffer, which,according to the “X:” is located in the C8051F120’s internalXRAM memory.

DesignCycle.qxd 5/8/2007 1:18 PM Page 85

The com_isr interrupt handler is called when a transmitor receive event occurs. In the case of the receive interrupthandler code, the first thing we do is check the RI0 receive interrupt flag. If the RI0 flag is set, we simply pull theincoming character from the UART0 buffer, reset the RI0 flag, check for a full receive buffer, and if the buffer isavailable, we stash the incoming character into the nextavailable receive buffer slot. If the receive buffer is full, thecharacter is tossed into the bit bucket.

The transmit interrupt handler code is just as simple:

// TRANSMIT INTERRUPT HANDLERif (TI0)

TI0 = 0; // clear interrupt request flagif (TxHead != TxTail) // if characters in buffer // transmit a character

SBUF0 = TxBuf[TxHead++ & TxBUFMASK];CharInTxBuf = 0; // clear ‘CharInTxBuf’ flag

else

// if all chars tx’dSendChar = 0; // clear ‘SendChar’ flag

If the transmit interrupt flag (TI0) is set, we immediatelyclear it and check to see if the transmit buffer is empty. If thetransmit buffer contains a character to be transmitted, we

extract the character from theHead of the transmit bufferand transmit the character byloading it into UART0’s SBUF0.

Now is a good time to lookat the job that the buffer masksdo. Note that we are not

performing any error checking and thus the buffer mask bits arenot used to their full potential. Basically, the buffer mask bits areused to make sure that the buffer addressing never leaves theextents of the allocated buffer. In other words, a 16-byte bufferwill never correctly recognize a buffer address greater than 15.Remember that address zero completes the 16 bytes.

I’ve augmented the UART0 interrupt handler routineswith some utility routines that pull incoming charactersfrom the receive buffer and push outgoing characters intothe transmit buffer. I’ve provided a complete µVision3 project based on the C8051F120’s UART0 as a downloadfrom the Nuts & Volts website (www.nutsvolts.com).

CIPHERING WITH THE C8051F120That’s what Jethro Bodine would call what the

C8051F120’s MAC (Multiply and Accumulate) unit does. TheC8051F120 MAC unit is most useful when the C8051F120 isinvolved in math-intensive operations such as digital filtering.However, the C8051F120’s MAC unit can be used to perform less complicated mathematical operations, as well.Many of the mathematical tasks that a microcontroller getsinvolved in use signed fractional numbers, as well as integers.The MAC unit can easily handle both.

The C8051F120’s MAC unit is very easy to understandand use. The bulk of the MAC unit consists of a pair of 16-bitregisters (MAC0AH/MAC0AL and MAC0BH/MAC0BL) inwhich the values to be multiplied are loaded. The result ofthe multiplication is pushed into the MAC’s 40-bit accumu-lator. The accumulator can be instructed to sum the incom-ing multiplication results or clear itself to hold only a singlemultiplication result. Upon command, the result held in theMAC’s accumulator can be shifted left or right by one bit.

Let’s do some cipherin’ with the C8051F120 MAC.First, we will load the MAC “A” 16-bit register pair with

86 June 2007

FIGURE 1. When you comparemy 0x4000 to the bit patternshere, it becomes pretty obviousas to how the fractional-to-hexstuff works. Want to loadup MAC0A with -0.25? Noproblem! The hex equivalent is0xE0. That’s -1.0 + 0.5 + 0.25(0b11100000). Piece of cake.

SCREEN SHOT 2. If you match up the MAC source codewith the µVision3 debug window variables, variable “f”represents the MAC0STA (status) register. The zero contentsof MAC0STA indicate that no hard overflow out of the 40-bitaccumulator occurred, there was no overflow into thesign bit, the result in the accumulator is not zero, and theaccumulator does not contain a negative number.

DesignCycle.qxd 5/8/2007 1:19 PM Page 86

+0.50. We’ll then multiply the value in MAC0A by +0.50.The multiplication is done following the loading of MAC0BL.The fractional values entered into the MAC0A and MAC0Bregisters are translated in Figure 1. The code for our littleMAC fractional multiply operation looks like this:

void main()

unsigned int a,b,c,d,e,f,g,h;

Init_Device();SFRPAGE = MAC0_PAGE;MAC0CF = 0x0A; // clear accum-fractional modeMAC0AH = 0x40; // load +0.50MAC0AL = 0x00; // 0x4000 = +0.50MAC0BH = 0x40; // load +0.50MAC0BL = 0x00; // kicks off multiply operationNOP; // multiply happening hereNOP; // accumulator updatedNOP; // rounding register updated

a = MAC0ACC3; // accumulator registersb = MAC0ACC2;c = MAC0ACC1;d = MAC0ACC0;e = MAC0OVR; // accumulator overflow registerf = MAC0STA; // status registerg = MAC0RNDH; // rounding registersh = MAC0RNDL;

while(1);

According to Screen Shot 2, the accumulator contains0x2000. Using Figure 1 as our guide, 0x2000 is equivalentto +0.25. It’s really easy to do integers with theC8051F120’s MAC unit, too. All we have to do is clear thefractional/integer bit in the MAC0CF register and treat ournumbers just like we’re used to in the MAC0A, MAC0B, andaccumulator registers. Keep in mind that the most significant bits of these registers is the sign bit in integermode. Here’s what MAC integer operation code looks like:

void main()

unsigned int a,b,c,d,e,f,g,h;

Init_Device();SFRPAGE = MAC0_PAGE;MAC0CF = 0x08; // clear accum-integer modeMAC0AH = 0x00; // load +2MAC0AL = 0x02; // 0x0002 = +2MAC0BH = 0x00; // load +2MAC0BL = 0x02; NOP;NOP; // accumulator updatedNOP; // rounding register updated

a = MAC0ACC3; // accumulator registersb = MAC0ACC2;c = MAC0ACC1;d = MAC0ACC0;e = MAC0OVR; // accumulator overflow registerf = MAC0STA; // status registerg = MAC0RNDH; // rounding registersh = MAC0RNDL;

while(1);

We all know what the answer is. However, the answer(4) will be situated in the accumulator’s MAC0ACC0 register with the remaining MAC0ACCX registers holdingzero values (0x0004). I’ve included both the fractional and integer code we just looked at in the source codedownload package so you can get hands-on with theC8051F120’s MAC unit.

MAKING WAVE(FORM)S WITH THEC8051F120 DAC

The C8051F120 contains a pair of on-chip digital-to-analog converters and before we’re done, we’ll put them both to use. I could exercise the C8051F120’s DAC by entering some values into the DAC registers andreading out the resultant voltages. That would be boring asheck. So, let’s create some waveforms using theC8051F120’s DAC0.

The very first thought that came to my mind was tosimply sweep DAC0 from 0.00 to it maximum voltagevalue. The C8051F120 has an on-chip +1.2V voltage reference that can be used to feed the comparators, the analog-to-digital converters, and the digital-to-analog converters. An x2 buffer/amplifier boosts theC8051F120’s on-chip reference voltage to +2.4V. Thus, I can sweep the 12-bit digital-to-analog convertersbetween 0.0V (0x000) and +2.4V (0xFFF) by simplysweep loading the DAC data registers. It then occurred to me that if I performed this sweep with reference to a timebase, I could create a sawtooth waveform. Let’s write some DAC code to see if I can indeed create a crude sawtooth waveform by sweeping DAC0 withsome rhythm.

I used the Configuration Wizard 2 application to help

T H E D E S I G N C Y C L E

June 2007 87

SCREEN SHOT 3. I wasn’t in “scientific mode” when Icoded up the sawtooth code. So, the frequency of thewaveform is solely SWAG and was chosen to make a goodpicture to show you.

DesignCycle.qxd 5/8/2007 1:20 PM Page 87

me get started with the DAC0 by having it generate theDAC0 initialization code you see here:

void DAC_Init()

SFRPAGE = DAC0_PAGE;// update DAC on Timer2 overflow-enable DACDAC0CN = 0x98;

I have the option of updating the DAC0 data registerswith a write to DAC0H or on an overflow of Timers 2, 3,or 4. Random chance has worked in our favor as I am ableto load my DAC0 sweep values into the DAC0 data registers on every overflow of what is now our timebase,Timer 2. I won’t have time to poll for a Timer 2 overflowas I will compromise the resultant waveform. So, I’ll turnon the Timer 2 interrupt mechanism and trip the interruptmechanism on every Timer 2 overflow. Once tripped, I’llexecute the code contained within the tmr_isr interrupthandler:

static void tmr_isr (void) interrupt 5

//Sawtooth Code

if(++low_counter == 0)

if(++high_counter == 0x10)high_counter = 0x00;

DAC0L = low_counter;DAC0H = high_counter;

The Sawtooth Code simply increments thelow_counter variable until it overflows from 0xFF to 0x00.On every low_counter overflow, the high_counter variable is incremented until it overflows from 0x00 to0x10. Thus, the maximum count that the low_counter and high_counter register pair can contain is 0xFFF, which is the maximum value we can push into the DAC0data registers.

I used the SWAG method of choosing the Timer 2 overflow value. I just kept adjusting the Timer 2 reload value until I got a nice trace on the Cleverscope. The Timer 2 code that you’ll get in the download package isshown here:

SFRPAGE = TMR2_PAGE;TMR2CN = 0x04; //enable Timer 2TMR2CF = 0x08; //SYSCLK is timer source clock//reload Timer 2 on overflow to 0xFF4CRCAP2L = 0x4C;RCAP2H = 0xFF;

With all of the DAC0 and Timer 2 initialization and interrupt code in place, all that’s needed to generate asawtooth wave is this:

void main()

Init_Device(); // init the chip peripheralslow_counter = 0x00; // init the waveform countershigh_counter = 0x00;while(1); // saw logs

While I was tinkering with the sawtooth wave you seein Screen Shot 3, I figured I could just as easily put a triangle waveform on the Cleverscope graph window. All I

88 June 2007

SCREEN SHOT 5. This is an example of how to modulate asquare wave using a sawtooth wave and a comparator. All ofthis is done by the C8051F120 peripherals. DAC0provides the sawtooth waveform and DAC1 is acting as a reference voltage for Comparator 1. The base referencevoltage is provided by the C8051F120’s on-chip reference voltage generator.

SCREEN SHOT 4. To get this triangle waveform, I simplyadded a phase variable that ramps the sawtooth DAC0 dataregister values up and down.

DesignCycle.qxd 5/8/2007 1:20 PM Page 88

have to do is count down when the DAC0 data registers get loaded with 0xFFF instead of resetting the DAC0 dataregisters to 0x000 at that point. As it turned out, to get a triangle wave to appear on the Cleverscope graph window,I only had to add some triangle code to the Timer 2 interrupt handler:

static void tmr_isr (void) interrupt 5

//Triangleif(phase == 0)

if(++low_counter == 0)

if(++high_counter == 0x10)

phase = ~phase;high_counter = 0x0F;low_counter = 0xFF;

else

if(—low_counter == 0xFF)

if(—high_counter == 0xFF)

phase = ~phase;high_counter = 0x00;low_counter = 0x00;

DAC0L = low_counter;DAC0H = high_counter;

The triangle interrupt handler code depends on thevalue of the phase variable to determine whether it needsto increment or decrement the value being fed to theDAC0 data registers. This country boy guessed right againas you can see in the Cleverscope display shown inScreen Shot 4. We’re not done with DACs yet. I’ve gotanother idea.

DARE TO COMPAREWhat if I fired up DAC1 and set it to generate +1.2V

by writing 0x7FF to the DAC1 data registers, used theDAC1 voltage as a reference voltage for Comparator 1,and fed Comparator 1 with the sawtooth wave fromDAC0? I should get a square waveform that is modulatedby the Comparator 1 reference voltage versus the voltageof the sawtooth waveform. Let’s code it up and see if I’m right.

Once again, I let the Configuration Wizard 2 applica-tion do the dirty work of initializing Comparator 1:

void Comparator_Init()

unsigned int i;SFRPAGE = CPT1_PAGE;CPT1CN = 0x80; // enable Comparator 1for (i=0;i<60;i++) // Wait 20us for init

;CPT1CN &= ~0x30; // clear the interrupt flagsCPT1MD = 0x30; // set mode to fastest

DAC1 does not need to do anything fancy. So, I simplyenabled it and it will only update its data registers on a writeto DAC1H (done by loading DAC1CN (DAC1 ControlRegister with 0x80). Now all I need to do is turn the sawtooth waveform loose and write the +1.2V voltage valueto the DAC1 data registers:

void main()

Init_Device();low_counter = 0x00;high_counter = 0x00;SFRPAGE = DAC1_PAGE;DAC1L = 0xFF;DAC1H = 0x07;while(1);

Take a look at Screen Shot 5. The modulated squarewave is actually the output of Comparator 1. As the sawtooth wave voltage passes through +1.2V, theComparator 1 output trips from low to high and remainshigh as long as the sawtooth wave voltage is above+1.2V, which is what we dialed into Comparator 1 as itsreference voltage. If I load DAC1’s data registers with alarger value, Comparator 1’s reference voltage will also

T H E D E S I G N C Y C L E

June 2007 89

SCREEN SHOT 6. You can see that as I increase Comparator1’s reference voltage, the high portion time of theComparator 1 output square waveform grows smaller. Bysweeping DAC1, we can create a PWM signal at the outputof Comparator 1.

DesignCycle.qxd 5/8/2007 1:21 PM Page 89

increase accordingly. The result is the square waveformyou see in Screen Shot 6. The DAC1 data registers are loaded with 0xBFF, which forces Comparator 1 to tripat 1.80V.

If you’re wondering why the Comparator 1 output islarger in voltage magnitude than the sawtooth waveform,

the answer is simple. Comparator 1 can swing its output from 0.00V to just a bit below +3.3V as its output is referenced to the C8051F120’s VDD, whichhappens to be +3.3V. DAC0, which is supplying the sawtooth waveform, is referenced to the C8051F120’s+2.4V on-chip voltage reference, which is being

90 June 2007

DesignCycle.qxd 5/8/2007 1:21 PM Page 90

supplied to DAC0 via the x2 buffer/amplifier.

CHECKED OUTYou’re ready to roll with

your own C8051F120 applications as you’re now “checked out” on the C8051F120 and its on-chip peripherals. If you’re wondering aboutthe absence of analog-to-digital converter coverage, here it is courtesyof the Configuration Wizard 2 application:

void ADC_Init()

SFRPAGE = ADC0_PAGE;ADC0CN = 0x80; // enable ADC0

Use the Configuration Wizard 2application to choose your analog-to-digital converter trigger method andwrite some simple code to poll for and fetch the analog-to-digital converter result. That’s all you need toread voltages at the C8051F120’sAN0 input. Using the C8051F120’sanalog-to-digital converter in basicmode is no different than using anyother microcontroller’s analog-to-digital converter.

The key to C8051F120 applicationsuccess lies with the ConfigurationWizard 2 application and the Keil µVision3/Silicon Laboratoriesdevelopment suite. If you have controlover the aforementioned items, youcan easily add the C8051F120 to yourDesign Cycle. NV

USB - XBeeDongle

USB - XBeeDongle

www.newmicros.com Tel:214-339-2204

Wireless serial links are easy now. The

USB to XBee Dongle shown above hosts an XBee Pro 2.4GHz RF transceiver. It allows USB to remote XBee Pro ttl output serial communications at standard baud rates up to 115200 and ranges up to a mile. Dongle $39. Kit with Dongle and 2 XBee Pro modules for $111. Visit/call for details.

CONTACT THE AUTHOR Peter Best can be reached viaemail at [email protected].

SOURCES Silicon Laboratories (wwwwww..ssiillaabbss..ccoomm) — C8051F120,C8051F120 Development Board

Keil (wwwwww..kkeeiill..ccoomm) — KeiluVison3 C Compiler

Saelig (wwwwww..ssaaeelliigg..ccoomm) —Cleverscope

June 2007 91

DesignCycle.qxd 5/8/2007 1:22 PM Page 91

>>> QUESTIONSWhat technology is used in the

customer sensors above the grocerystore doors to detect an approachingcustomer? Are these units availablenew or surplus anywhere?#06071 Bert Henscheid

via email

I need to interface a GPS engineserial data out to two different devices.I would also like to isolate the threeunits from each other. Can the serialdata output from a GPS engine drivetwo opto-isolators directly, and if so,would the output of the GPS beconected directly to the isolator input?Next, are there opto-isolators that haveone input and two or more outputs?#06072 Charlie Willwerth

Saint Augustine, FL

I would like to do some kerneldebugging and the software I am usingrequires the use of one PC to monitoranother PC. In the past, this would bedone using a null modem cablebetween the two serial ports. Now withonly USB ports, I am wondering how tocreate a null modem cable. Onethought would be to get two USB toserial port adapters and hook a nullmodem cable between them. I’m not sure that would work, and even if it did, a more direct approach and

explanation would be much appreciated.#06073 John Huseby

via email

How can I vary the 60 Hz line voltage frequency by very smallamounts? I have an expensive electricclock that keeps very bad time. I'mthinking if I could adjust the frequencygoing to the clock, I could correct this problem. Either a commercial pieceof equipment or a schematic would be useful.#06074 Richard Flaws

Oswego, IL

I need a simple circuit that wouldsupply a two second on pulse and beoff for 10 to 12 minutes. It shouldrepeat this cycle over and over again.The on pulse would drive a 3 VDCrelay. This would be powered from a 5 VDC power supply. Any ideas? #06075 John

via email

Is the new Microsoft operating system Vista back compatible? I havemany programs on Astronomy fromWindows 98 vintage, on floppies, thatcannot be duplicated. #06076 Lyle A. Nelson

Devils Lake, ND

How hard would it be to make myAPC UPS more usable during extendedpower outages by using 12 volt Optima

This is a READER-TO-READER Column. All questions AND answers are submitted by Nuts & Volts readers and are intended to promote the exchange of ideas and provide assistancefor solving problems of a technical nature. Questions are subject to editing and will be published on a space available basis if deemed suitableby the publisher. Answers are submitted by readers and NNOO GGUUAARRAANNTTEEEESS WWHHAATTSSOOEEVVEERR are made by the publisher. The implementation ofany answer printed in this column may require varying degrees of technical experience and should only be attempted by qualified individuals.Always use common sense and good judgement!

All questions and answers shouldbe sent by email to [email protected] All diagrams should be computer generated and sent with yoursubmission as an attachment.

QUESTIONSTo be considered, all questions should relateto one or more of the following:

❶ Circuit Design❷ Electronic Theory❸ Problem Solving❹ Other Similar Topics

Be brief but include all pertinent informa-tion. If no one knows what you're asking, youwon't get any response (and we probablywon't print it either). Include your Name, Address, Phone Num-ber, and email. Only your Name, City, andState will be published with the question,but we may need to contact you. No questions will be accepted that offerequipment for sale or equipment wanted tobuy. Selected questions will be printed onetime on a space available basis. Questions are subject to editing.

ANSWERS Include in the subject line of your email,the question number that appears directlybelow the question you are responding to. Payment of $25.00 will be sent if your answer is printed. Be sure to include yourmailing address or we cannot send payment. Only your Name, City, and State, will beprinted, unless you say otherwise. If youwant your email address included, indicateto that effect. Comments regarding answers printed inthis column may be printed in the ReaderFeedback section if space allows.

TECHFORUM

94 June 2007

TechForum.qxd 5/10/2007 4:29 PM Page 94

batteries? Would the charge controllerbe over tasked? Or, would it be betterto just buy a much bigger unit? I wantscalability dependent on me, not whatthe company offers. #06077 via email

[#3072 - March 2007]

I built an ATMEL-based steppercontroller that sent the step commandsthrough four power MOSFETs that connected directly to the coils of a"four volt, 1.2 amp/phase" unipolarstepper. It was an inexpensive motorbut it worked great — good torque andspeed and started right back if stalled.I bought more of the "same" motor — ithad a different label and didn't work atall — stalled, shook, and no torque. Igot several different motors from differ-ent companies, all with a rating of 4-5volts at 1-1.2 amps (I'm using a switch-ing supply rated five volts, 3.5 amps)and they all respond differently. Nonework as well as the first (and cheapest)motor. The MOSFETs have protection

diodes and I tried adding diodes to thepower lines — no change. I bought acommercial controller with a motorrated 12 volts, .4 amps, which turnedout to be a 12-volt version of my original motor, and it worked very well.

The other motors run better withthat controller, which has variable current, but still vary in performance. I can't (nor can the motor company)figure out why there is so much variation in output with motors withthe same ratings. Is there some way Ican get the rated power out of thesemotors without spending a fortune? Isthere another motor rating or spec thatI can use to judge these motors?

Stepper motors are rated by volts/amps per phase, phase inductance,steps per revolution, number of phases, detent, and holding torque. Aquick way to tell motor performanceat given current and voltage per phaseis to compare the holding torque sinceit is the maximum torque the motorcan develop at low speeds and the highest load. Another important

parameter is winding inductance; thelower, the better for high speed performance, since a low inductanceallows winding current to build upfaster. From what you are describing,you may have an incorrect phasingsequence or system resonance.

Another possibility is a differencein phase inductance or not enoughcurrent, or demagnetized (overheat-ed) motors or winding shorts, just togive you the starting points. Keep inmind that torque is roughly propor-tional to current in the linear region.

Excellent references are SteppingMotor Basics at EAD Motors (www.eadmotors.com), and the best one Ihave seen is Jones on Stepping Motorsat University of Iowa (www.cs.uiowa.edu/~jones/step). There are also other resources at Camtronics, Inc.(dynamometer testing). If you need toget into the more sophisticated five-phase systems, there is OrientalMotors at (www.orientalmotor.com/products/ac-dc-step-motors/).

Walter HeissenbergerHancock, NH

>>> ANSWERS

June 2007 95

> > > R E A D E R - T O - R E A D E R Q U E S T I O N S A N D A N S W E R S

[#2075 - February 2007]

I need an alternator circuit thatwill allow me to charge an eight-voltlead-acid battery in a WWII army vehicle using a standard automobilealternator.

#1 Newer automotive alternatorshave built-in regulators, so you willhave to either remove the internal regulator or find an older one that requires an external regulator.On Delco alternators, you can tell ifthe regulator is internal or external by the connector. If the blades areparallel, the regulator is internal. On

alternators that use an external regulator, the two blades are at rightangles. As I recall, the blade on theright connects to the field; the other isfor the idiot light. This circuit is similarto one I sent in earlier. The LM2594 isa PWM regulator operating at 150kHz. The diode is a three ampSchottky to catch the backswing ofthe inductance of the field winding.The TIP41C is a TO-220 transistor andshould not need a heatsink because itis used as a switch. The eight volt battery is actually 8.4 volts and needs9.2 volts to charge.

Russell KincaidMilford, NH

#2 Most alterna-tors have a built-inregulator, which mustbe removed andreplaced with onedesigned for eightvolts to charge youreight volt battery.The regulator con-trols the current tothe field winding ofthe alternator which,

in turn, controls the alternator output.This URL provides details and aschematic for building your own simple adjustable regulator: www.amsterdamhouseboats.nl/voltage_regulator.htm

A modification to the circuit isneeded to operate with an eight voltbattery. The 6.2 volt zener diode andthe 3.3K resistor in series with it needto be changed to a 3.9 volt zener anda 2.2K resistor. The 3.3K resistors inseries with the 1K pot also need to be changed to 2.2K — see theschematic below which includes themodifications.

Ed SchickHarrison, NY

TechForum.qxd 5/10/2007 4:30 PM Page 95

96 June 2007

[#3074 - March 2007]

I have been told by someonewhose judgement and knowledge Inormally trust that malware exists thatwill write itself into the EEPROM on ahard drive, normally accessible only by the drive manufacturer, used tostore such things as a bad sector map,natural-tological translation tables, etc. If this is true, are there third-partyutilities that can detect and delete such malware? Otherwise, must it be returned to the manufacturer to be "cleaned?"

The data sheets for severalEEPROMs — especially the Flash variety — show a serious possibilitythat any malware that gets into theEEPROM can set a protection flag thatmakes it irreversible and uneraseable.

An obvious clue to such malwarewould be a pop-up message saying "aFlash update is available for your(brand) computer."

In this situation, if it ain't broke,don't break it. The message soundslike a good idea without giving anyclue as to why it would be, when it is

certainly a dangerous procedure to do a Flash update with a high likelihood of failure; the consequencewill certainly render the updateddevice DEAD.

A less obvious source of Flashmalware is DRM, and the DMCA forbids testing DRM for anythingincluding viruses. Sure enough, inNovember 2005, a major record labelwas caught putting a dangerous viruson their retail music CDs which killsthe CD drive. A dead burner, or onethat often burns "coasters" may havebeen infected. I've seen a burner godead right out of the box with a "Flashupdate." I've also seen one noisily grindscratches into a CD with its laser lens.

Flash updates and DRM are avoid-able. If by some other means the Flashis corrupted, since it is irreversable,there is no software solution. In thecase of a hard drive, it either kills the drive dead or infects it with a permanent virus, and in the worst case the virus does nothing harmfulexcept undetectably spy on you, otherwise it becomes an obviouslybad drive. Spyware may create a

"tumor partition" (I don't know exactlywhat this is called) which cannot beremoved and may be indistinguishablefrom many megabytes of bad sectors.I'd assume it contains a record ofeverything you do on the computer.

There is really no softwaredefense against any kind of malwarebut there is one surefire hardwaredefense since the beginnings of homecomputers: write protected media.

In the past, this was a hole in afloppy or tape which could be covered to switch off the possibility ofunauthorized writing to the media.This is notably absent from muchmodern media, such as hard drives.Non-burning CD-ROM drives are wellprotected, and SD Flash cards are reasonably protected. Protecting EEPROM or Flash firmware may require significant hardware modification, the simplest of whichmay be replacing the firmware in anon-eraseable ROM. Perhaps only thedesign engineer of your drive knowsthe full details.

William ComoBethpage, NY

> > > R E A D E R - T O - R E A D E R Q U E S T I O N S A N D A N S W E R S

Get partsFREE

:// .

@ .

Http COMSales COM

EzPCB

EzPCB

Resistors Diodes

CapacitorsTransistors Connectors

Order PCB

FREEWith first order

O " "

!

nly for 5pcs 4 x4 2L

Free Solder mask and silkscreen

$50

TechForum.qxd 5/10/2007 4:30 PM Page 96

1-WIREHobby Boards ......................................56

AMATEURRADIO AND TVPolarisUSA Video, Inc...........................21Ramsey Electronics, Inc. ................14-15

BATTERIES/CHARGERSA & A Engineering ................................44Cunard Associates ...............................44Ocean Server Technology, Inc. ............44NiCd Lady Company.............................23

BUSINESSOPPORTUNITIESEZ PCB ................................................96

BUYING ELECTRONICSURPLUSEarth Computer Technologies ..............44Jaycar Electronics.................................51

CCD CAMERAS/VIDEOCircuit Specialists, Inc. ....................98-99Matco, Inc. ...........................................44PCB Fab Express ................................59PolarisUSA Video, Inc...........................21Ramsey Electronics, Inc. ................14-15

CIRCUIT BOARDSAP Circuits ...........................................45Blink Manufacturing .............................45Cunard Associates ...............................44Dimension Engineering.........................59ExpressPCB .........................................29EZ PCB ................................................96IMET Corporation .................................57Maxstream ...........................................26PCB Cart ..............................................91PCB Pool .............................................57PCB Fab Express ................................59Pulsar, Inc. ...........................................44R4Systems, Inc. ....................................59Schmart Board ...............................44, 77

COMMMUNICATIONAvcom Tec, LLC ..................................26

COMPONENTSFront Panel Express LLC......................57Jameco ................................................37Lemos International Co., Inc. ...............96Linx Technologies ................................20Maxstream ...........................................26Pulsar, Inc. ...........................................44Super Bright LEDs .................................8

COMPUTERHardwareActiveWire, Inc. ....................................44Earth Computer Technologies ..............44Halted Specialties Co. ..........................83

Microcontrollers / I/O BoardsAbacom Technologies .........................56Avcom Tec, LLC ..................................26EMAC, Inc. ...........................................58HobbyLab .............................................44Microchip ..............................................13microEngineering Labs .........................50MVS .....................................................27

Net Media ...............................................2New Micros ......................................6, 91Parallax, Inc. ..........................Back CoverPololu Robotics & Electronics ..............90R4Systems, Inc. ....................................59Scott Edwards Electronics, Inc. .............58Trace Systems, Inc. .............................45XGameStation ......................................44

DESIGN/ENGINEERING/REPAIR SERVICESBlink Manufacturing .............................45ExpressPCB .........................................29EZ PCB ................................................96Front Panel Express LLC......................57IMET Corporation .................................57NiCd Lady Company.............................23PCB Cart ..............................................91PCB Pool .............................................57Pulsar, Inc. ...........................................44R4Systems, Inc. ....................................59Trace Systems, Inc. .............................45

EDUCATIONAvcom Tec, LLC ..................................26Command Productions ........................43EMAC, Inc. ...........................................58Hobby Engineering ..............................82RMD3/Spring Circuits ............................9Schmart Board ...............................44, 77XGameStation ......................................44

EMBEDDED TOOLSNetBurner ...............................................7

ENCLOSURESIntegrated Ideas & Tech. ......................58

IP HOMEAUTOMATIONMicroAutomata .....................................82

KEYBOARDEMULATORSHagstrom Electronics ...........................45

KITS & PLANSDesignNotes.com, Inc. ..........................57Earth Computer Technologies ..............44Electronics 123 ....................................44EMAC, Inc. ...........................................58Hobby Engineering ..............................82Hobby Boards ......................................56Information Unlimited ...........................20Jaycar Electronics.................................51MicroAutomata .....................................82NetBurner ...............................................7QKITS ...................................................44RABBIT Semiconductor ..........................3Ramsey Electronics, Inc. ................14-15RMD3/Spring Circuits ............................9Scott Edwards Electronics, Inc. ..............58XGameStation ......................................44

LASERSInformation Unlimited ...........................20

LSI (micon)Renesas Technology Corp. .................25

MISC./SURPLUSAll Electronics Corp. .............................71Front Panel Express LLC......................57Halted Specialties Co. ..........................83MCM ....................................................12

Ocean Server Technology, Inc. ............44

MOTORSJameco ................................................37

OPTICSMadell Technology ...............................90

PROGRAMMERSElectronics 123 ....................................44microEngineering Labs .........................50

PUBLICATIONSLakeview Research ..............................45Mouser Electronics ..............................19

RF TRANSMITTERS/RECEIVERSAbacom Technologies .........................56Linx Technologies ................................20Matco, Inc. ...........................................44

ROBOTICSCrustCrawler ........................................24Hobby Engineering ..............................82HobbyLab .............................................44Jameco ................................................37LabJack ................................................27Lemos International Co., Inc. ...............96Lynxmotion, Inc. ...................................28Net Media ...............................................2New Micros ......................................6, 91Ocean Server Technology, Inc. ............44Pololu Robotics & Electronics ..............90Robot Power ..........................................9

SATELLITELemos International Co., Inc. ...............96

SECURITYInformation Unlimited ...........................20Linx Technologies ................................20Matco, Inc. ...........................................44PolarisUSA Video, Inc...........................21

TEST EQUIPMENTCircuit Specialists, Inc. ....................98-99DesignNotes.com, Inc. ..........................57Dimension Engineering.........................59Electronic Design Specialists ...............65HobbyLab .............................................44Jaycar Electronics.................................51LabJack ................................................27Link Instruments .....................................5Madell Technology ...............................90Pico Technology Ltd. UK .....................65Trace Systems, Inc. .............................45

TOOLSMadell Technology ...............................90NetBurner ...............................................7RMD3/Spring Circuits ............................9

WEATHERMONITORINGHobby Boards ......................................56

WIRE, CABLEAND CONNECTORSDesignNotes.com, Inc. ..........................57Jameco ................................................37

WIRELESSPRODUCTSMicroAutomata .....................................82

June 2007 97

A & A Engineering .....................44

Abacom Technologies ...............56

ActiveWire, Inc. .........................44

All Electronics Corp. ..................71

AP Circuits ................................45

Blink Manufacturing ...................45

Avcom Tec, LLC ........................26

Circuit Specialists, Inc. .........98-99

Command Productions ..............43

CrustCrawler .............................24

Cunard Associates ....................44

DesignNotes.com, Inc. ...............57

Dimension Engineering ..............59

Earth Computer Technologies ...44

Electronic Design Specialists ....65

Electronics 123 ..........................44

EMAC, Inc. ................................58

ExpressPCB ..............................29

EZ PCB .....................................96

Front Panel Express LLC ...........57

Hagstrom Electronics ................45

Halted Specialties Co. ...............83

Hobby Engineering ....................82

Hobby Boards ...........................56

HobbyLab ..................................44

IMET Corporation ......................57

Information Unlimited ................20

Integrated Ideas & Tech. ...........58

Jameco ......................................37

Jaycar Electronics ......................51

LabJack .....................................27

Lakeview Research ...................45

Lemos International Co., Inc. ....96

Link Instruments ..........................5

Linx Technologies .....................20

Lynxmotion, Inc. ........................28

Madell Technology ....................90

Matco, Inc. .................................44

Maxstream ................................26

MCM ..........................................12

MicroAutomata ..........................82

Microchip ...................................13

microEngineering Labs ..............50

Mouser Electronics ....................19

MVS ..........................................27

NetBurner ....................................7

Net Media ....................................2

New Micros ...........................6, 91

NiCd Lady Company ..................23

Ocean Server Technology, Inc. ..44

Parallax, Inc. ...............Back Cover

PCB Cart ...................................91

PCB Pool ...................................57

PCB Fab Express ......................59

Pico Technology Ltd. UK ...........65

PolarisUSA Video, Inc................21

Pololu Robotics & Electronics ...90

Pulsar, Inc. ................................44

QKITS ........................................44

R4Systems, Inc. .........................59

RABBIT Semiconductor ...............3

Ramsey Electronics, Inc. .....14-15

Renesas Technology Corp. .......25

RMD3/Spring Circuits ..................9

Robot Power ...............................9

Schmart Board ....................44, 77

Scott Edwards Electronics, Inc. ..58

Super Bright LEDs ......................8

Trace Systems, Inc. ..................45

XGameStation ...........................44

AD INDEX L O O K F O R S E A R C H F O R F I N D

Find your favorite advertisers here!

IndexJune07.qxd 5/10/2007 5:26 PM Page 97

CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm

•Ceramic heating element for moreaccurate temp control

•Temp control knob in F(392° to 896°) &C(200° to 489°)

•3-prong grounded power cord/static safe tip•Seperate heavy duty iron stand•Replaceable iron/easy disconnect•Extra tips etc. shown at web site

Item#CSI-STCSI-STAATION1ATION1A

Details at Details at WWeb Siteeb Site

TTriple Output Bench Powerriple Output Bench Power SuppliesSupplieswith Large LCD Displayswith Large LCD Displays

•Output: 0-30VDC x 2 @ 3 or 5 Amps& 1ea. fixed output @ 5VDC@3A•Source Effect: 5x10-4=2mV•Load Effect: 5x10-4=2mV•Ripple Coefficient: <250uV•Stepped Current: 30mA +/- 1mA•Input Voltage: 110VAC

Dual OutputDual Output DC Bench PowerDC Bench Power SuppliesSupplies

CirCircuit Specialists Soldering Scuit Specialists Soldering Stationtationw/Ceramic Element & Seperatew/Ceramic Element & Seperate

SolderSolder SStandtand

Rapid Heat Up!Rapid Heat Up!

$34.95!$34.95!

$49.95$49.95

AlsoAlso AAvailable w/Digital Displayvailable w/Digital Display

& Micr& MicroProProcessorocessor ContrControllerollerSMD Hot SMD Hot TTweezerweezerAdaptor Fits Adaptor Fits CSICSISStations 1Atations 1A & & 2A2A,,and and CSI906CSI906

1-4: $105.95$105.95 5+: $99.50$99.50

As Low As Low AsAs$99.50!$99.50!

HOTHOTITEM!ITEM!

High stability digital read-out bench power suppliesfeaturing constant voltage and current outputs. Short-circuit and current limiting protection is provided. SMTPC boards and a built-in cooling fan help ensure reli-able performance and long life.

•Source Effect: 5x10-4=2mV•Load Effect: 5x10-4=2mV•Ripple Coefficient:: <250uV•Stepped Current: 30mA +/- 1mA

1-4: $1$114.9514.95 5+: $109.00$109.00CSI5003X5CSI5003X5: 0-50v/0-3amp

1-4: $1$119.0019.00 5+: $1$114.0014.00CSI3005X5CSI3005X5: 0-30v/0-5amp

wwwwww.Cir.CircuitSpecialists.comcuitSpecialists.com

In BusinessIn Business

Since 1971Since 1971

CCCiii rrrcccuuuiiittt SSSpppeeeccciiiaaalll iiissstttsss,,, IIInnnccc... 222222000 SSS... CCCooouuunnntttrrr yyy CCCllluuubbb DDDrrr... ,,, MMMeeesssaaa,,, AAAZZZ 888555222111000888000000--555222888--111444111777 /// 444888000--444666444--222444888555 /// FFFAAAXXX::: 444888000--444666444--555888222444

Item#CSI-STCSI-STAATION2ATION2A

>> Test Equipment >> Power SuppliesDetails at Web SiteDetails at Web Site

Details at Details at WWeb Siteeb Site

Item#CSITWZ-STCSITWZ-STAATIONTION

$29.00$29.00

CSI3003X3CSI3003X3: 0-30VDCx2 @3A $188.00$188.00 5+: $183.00$183.00

CSI3005XIIICSI3005XIII: 0-30VDCx2 @5A $239.00$239.00 5+: $229.00$229.00

*All 3 Models have a *All 3 Models have a 1A/5VDC Fixed Output1A/5VDC Fixed Output on the rear panel*on the rear panel*

OurOur PrPremium emium All in One Repairing SystemAll in One Repairing System PrProgrammable DC Powerogrammable DC Power SuppliesSupplies

PrProgrammable DC Electrogrammable DC Electronic Loadsonic Loads

The CSI 3600 Series

Programmable DC Power

Supplies are equipped with a

back-lit LCD display, number

keypad and a rotary code switch

for ease of use & quick program-

ming. Voltage, Current & Power can all be displayed on the LCD or com-

puter screen (with optional RS-232 interface module). It can be operated at

constant current mode, constant voltage mode & constant power mode. It

also can be set with maximum limits for current & power output. Ideal

instruments for scientific research, educational labs or any application

requiring a sophisticated DC-power source.

Model CSI3644A CSI3645A CSI3646A

DC Voltage 0-18V 0-36V 0-72V

DC Current 5A 3A 1.5A

Power (max) 90W 108W 108W

Only $199.00 Each!Only $199.00 Each!

The CSI 3700 series electronic

loads are single input program-

mable DC electronic loads that

provide a convenient way to test

batteries and DC power sup-

plies. It offers constant current mode, constant resistance

mode and constant power mode. The backlight LCD,

numerical keypad and rotary knob make it much easier to

use. Up to 10 steps of program can be stored.

Model CSI3710A CSI3711A

Input Voltage 0-360V DC 0-360V DC

Input Current 0-30A DC 0-30A DC

Input Power 0-150W 0-300W

CSI3710A: $349.00CSI3710A: $349.00 CSI371CSI3711A: $499.001A: $499.00

CSI3003X-5CSI3003X-5: 0-30v/0-3amp

>> Test Equipment >> Power Supplies

Details at Details at WWeb Siteeb Site

100,000 Count Pr100,000 Count Programmable Data Logging DMMogrammable Data Logging DMM

>> Test Equipment >> DIGITAL MULTIMETERS

A power house DMM with 100,000 count accuracy and abuilt-in data logger that will help you find intermittant prob-lems and monitor equipment while you are busy working onother jobs. The D620 can record and store in it's own internalmemory up to 37,300 time stamped data values in all func-tions by simply pressing a button. •True RMS measurements for AC•RS-232C interface with personal computer.

Item# PROTEK D620PROTEK D620

SpecialSpecial

$169.00!$169.00!

>> Soldering Equipment & Supplies >> Soldering Stations

>> Soldering Equipment & Supplies >> Soldering Stations

•All in One system. Combines the function of a Hot Air Gun, a Soldering Iron anda Desoldering Gun.

•Microprocessor controlled ESD safe unit. All digital display of hot air temperature,soldering iron temperature, desolderinggun temperature and air pressure withtouch type panel controls.

•The desoldering tool comes with zerocrossing circuitry preventing electricalsurges and is equipped with air cylindertype strong suction vacuum pump.

•The 24V soldering iron is compatible withthe compound tip design by connecting theceramic heater, sensor, control unit and tipas one. Designed for efficiency.Replacement of tips with easy slip in/outmethod.

•Compatible with various type of air nozzles.•Compatible with different kinds of tips.•Full compliment of nozzles & tips are available. NEWNEW

ITEM!ITEM!Item#CSI-9000CSI-9000

Only $249.00Only $249.00

ESD Safe CPU ContrESD Safe CPU Controlled SMD olled SMD

Hot Hot AirAir Rework SRework Stationtation

The heater and air control system are built-in andadjusted by the simple touch of the front keypadfor precise settings.Temperature range isfrom 100°C to 480°C /212°F to 896°F, andthe entire unit willenter a temperaturedrop state after 15minutes of non-use forsafety and to elimi-nate excessive wear.

Details at Details at WWeb Siteeb Site

•CPU Controlled •Built-in Vacuum System•Temperature Range:100°C to 480°C / 212°F to 896°F•15-Minute Stand-By temperature "sleep" mode•Power:110/120 VAC, 320 W maximum

Item# CSI825A++CSI825A++

>> Soldering Equipment & Supplies

SaleSale$149.00!$149.00!

Full Page.qxd 5/9/2007 4:41 PM Page 98

CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm CCCiii rrrcccuuuiiitttSSSpppeeeccciiiaaalll iiissstttsss...cccooommm

CCCiii rrrcccuuuiiittt SSSpppeeeccciiiaaalll iiissstttsss,,, IIInnnccc... 222222000 SSS... CCCooouuunnntttrrr yyy CCCllluuubbb DDDrrr... ,,, MMMeeesssaaa,,, AAAZZZ 888555222111000888000000--555222888--111444111777 /// 444888000--444666444--222444888555 /// FFFAAAXXX::: 444888000--444666444--555888222444

Visit our website for a complete listing of our offers. We have over 8,000 electronic items on line @ www.CircuitSpecialists.com. PC based data acquisition,industrial computers, loads of test equipment, optics, I.C’s, transistors, diodes, resistors, potentiometers, motion control products, capacitors,miniature observationcameras, panel meters, chemicals for electronics, do it yourself printed circuit supplies for PCB fabrication, educational D.I.Y. kits, cooling fans, heat shrink, cableties & other wire handleing items, hand tools for electronics, breadboards, trainers, programmers & much much more! Some Deals you won’t believe!

Digital SDigital Storage Oscilloscope Moduletorage Oscilloscope Module

PC based Digital Storage Oscilloscope,

200MHz 5GS/s equiv. sampling USB

interface

Convert any PC with USB interface to a highperformance Digital Storage Oscilloscope. Thisis a sophisticated PC basedscope adaptor pro-viding performance compatible to mid/highlevel stand alone products costing much more!Comes with two probes.

Details & SoftwareDetails & SoftwareDownload at Download at WWeb Siteeb Site

>> Test Equipment >> Oscilloscopes/Outstanding Prices

Item# 200DSO200DSO Only$819.00$819.00

Details at Details at WWeb Siteeb Site >> Miniature Cameras(Board,Bullet,Mini’s, B/W, Color)

SONYSONY SuperSuper HAD CCD ColorHAD CCD Color

WWeatherpreatherproof IR Camerasoof IR Cameras

•Day & Night Auto Switch•Signal System: NTSC•Image Sensor:1/3" SONY Super HAD CCD•Horizontal Resolution: 480TV lines•Min. Illumination: 0Lux

SONYSONY SuperSuper HAD CCD B/WHAD CCD B/W

WWeatherpreatherproof IR Cameraoof IR Camera

•Day & Night Auto Switch•Signal System: EIA•Image Sensor: 1/3" SONY Super HAD CCD•Horizontal Resolution: 420TV lines•Min. Illumination: 0Lux

Item# VC-317D:VC-317D:

SONYSONY SuperSuper HADHAD

CCD ColorCCD Color CameraCamera

Item# VC-805:VC-805:

•Weather Proof•Signal System: NTSC•Image Sensor: 1/4" SONY Super HAD CCD•Horizontal Resolution: 420TV lines•Min. Illumination: 1Lux/F1.2

SONYSONY SuperSuper HAD CCD ColorHAD CCD ColorWWeatherpreatherproof IR Cameraoof IR Camera

Item# VC-819D:VC-819D:

•Day & Night Auto Switch•Signal System: NTSC•Image Sensor: 1/4" SONY SuperHAD CCD

•Horizontal Resolution: 420TV lines•Min. Illumination: 0Lux

480480

TV LinesTV Lines

Resolution

Resolution

PricePriceBreakthrough!Breakthrough!

PrProtek 2.0 & 2.9GHz Field Sotek 2.0 & 2.9GHz Field Strtrength ength AnalyzersAnalyzers

>> Test Equipment >> RF Test Equipment

•Frequency Range : 100KHz ~ 2900MHz(2060MHz for 3201N)

•WFM/NFM/AM/SSB modulated signalsmay be measured.

•Sweep Trigger Mode: Free Run, SingleRun, Continuous Wave, Squelch Run

•Sweep Speed: 500 to 2000msec•PLL tuning system for precise frequencymeasurement and tuning

•Built-in Frequency Counter•RS232 interface

Item#’s 3290N & 3201N3290N & 3201N

3290N 3290N

SpecialSpecial$1750.00 (for$1750.00 (for 3290N)3290N)

$1329.00 (for$1329.00 (for 3201N)3201N)Details at Details at WWeb Siteeb Site

SONYSONYSuper HADSuper HAD

CCD™CCD™ equippedcamera’s feature dra-matically improved

light sensitivity

$59.50$59.50 $53.95$53.95$62.50$62.50

SSteppertepper MotorsMotorsPart #: Motor Frame

Size:Holding Torque: Price:

42BYGH404 NEMA 17 3.4kg.cm/47oz.in $17.95

57BYGH207 NEMA 23 8kg.cm/111oz.in $24.95

57BYGH303 NEMA 23 15kg.cm/208oz.in $29.95

57BYGH405 NEMA 23 20kg.cm/277oz.in $34.95

85BYGH350B-03 NEMA 34 48kg.in/665oz.in $79.95

85BYGH350C-03 NEMA 34 63kg.cm/874oz.in $119.95

Part #: Dimensions: MicroStep: Price:

XCW220 100mm x 61mm x 19mm

1(200), 1/2(400), 1/4(800),

1/8(1600)$39.95

CW220 99mm x 65mm x 30mm

1/2(400), 1/8(1600) $49.95

CW230 115mm x 72mm x 32mm

1(200), 1/2(400), 1/4(800),

1/8(1600), 1/16(3200),

1/32(6400), 1/64(12800)

$59.95

CW250 140mm x 94mm x 45mm

1(200), 1/2(400), 1/8(1600) $69.95

CW860 147mm x 97mm x 30mm

1(200), 1/2(400), 1/4(800),

1/8(1600), 1/16(3200),

1/32(6400), 1/64(12800),

128(25600), 1/5(1000),

1/10(2000), 1/25(5000),

1/50(10000), 1/125(25000),

1/250(50000)

$119.95

SSteppertepper MotorMotor ContrControllers ollers 2 Phase Micr2 Phase Microsteppingostepping

SSteppertepper MotorMotor DriverDriver (Bi-polar(Bi-polar & Unipolar& Unipolar Motors)Motors)

$132.00$132.00Item# VC-827D:VC-827D:

NewNew

RevRev. Now. Now

AAvailablevailable

OutdoorOutdoor ColorColor Speed Dome CameraSpeed Dome Camera

•1/4” SONY Exview CCD•768(H) x 494(V) effective pixels•Horizontal Resolution: 480TV lines•Up to 80 preset points•Line scanning•Continuous 360° horizontal rotation•Vertical rotation: 0-100°•RS485 control interface•Min. Illumination: 0.1Lux (color) / 0.001Lux (B&W)

Details at Details at WWeb Siteeb Site

>> Miniature Cameras(Board,Bullet,Mini’s, B/W, Color)

Item# VC-EX861VC-EX861

$899.00$899.00

Shown with optional wall mountShown with optional wall mount

CNC9000 Motion ContrCNC9000 Motion Control Machineol Machine

•Z, X and Y Axis. •Motor Type: Steppers, Nema 23 size motor mounts on allaxes. 277 Oz/in torque.

•Travel: X-22" Y-24" Z-4.5"•Footprint (overall size notincluding motors): 34" x34.75" x 21.75"

•Table top size: 32" x 26" •ABBA Brand Ball screwsand linear rails and truckson all axis

•5mm per turn pitch lead screws.•Direct drive motor coupling on all axis

•Using 3 each CW230 StepperMotor controllers and a300watt power supply at 36 Volts.

•Tested Tolerance on 6061 aluminum plate with .125 carbideendmil (0.001) 2"x2"x.025" Using a Porter Cable router.

•Standard (Feed rate of 50 inch per minute with stepper motors)•Made of 6061 Aluminum except rails, trucks, ball screws and fasteners.Steel and other materials.

Our Custom Designed and Manufactured CNC Machine comescomplete with all Stepper Motors, Controllers and Power Supply.

Features NOT found on the competition!

Item# CNC9000CNC9000

$2995.00$2995.00

Details at Details at WWeb Siteeb Site >> Motion Control >> Linear Motion

HOTHOTNEWNEW

ITEM!ITEM!

CoverInside.qxd 5/9/2007 2:22 PM Page 2

Vo

l.28 No.6

NU

TS

& V

OLT

SE

XE

RG

AM

E •

FIBE

R O

PT

ICS

•S

ER

IAL P

OR

T •

MO

RE

WE

AT

HE

R S

TAT

ION

Ju

ne 2007

0 374470 89295

06>U.S. $5.50 CANADA $7.00

Cover.qxd 5/10/2007 4:08 PM Page 108