cover1.qxp 9/5/2007 11:55 AM Page 1

#207 October 2007 w w w . i r c u i t c

e CIRCUIT® l l a r . c o m

CELLARTHE MAGAZINE FOR COMPUTER APPLICATIONS SIGNAL PROCESSING Signal Recovery & Restoration

Speech Synthesis

FIR Filter Basics

New Sensor Technology WWW.GiURUMELE.Hi2.RO

10>

7925274 75349 $4.95 U.S. ($5.95 Canada) C2.qxp 5/31/2007 9:02 AM Page 1

Announcing a complete hardware and software solution from NetBurner The NetBurner MOD5234 ETHERNET CORE MODULE with eTPU

Only$99 Qty. 100

NetBurner MOD5234 Ethernet Core Module Features INDUSTRIAL TEMPERATURE RANGE | –40°C to +85°C PERFORMANCE AND MEMORY | 32-Bit CPU | Freescale ColdFire MCF5234 147 Mhz | 2MB Flash Memory | 8MB SDRAM DEVICE CONNECTIVITY 2 | 10/100 Ethernet | 3 UARTs | 16-channel eTPU | I C | SPI | CAN 2.95” | 47 Digital I/O | 16-bit Data Bus | SD/MMC Flash Card Support

Customize with NetBurner’s Royalty- Suite DEVELOPMENT SOFTWARE | NB Eclipse IDE | Graphical Debugger | Deployment Tools | Examples COMMUNICATION SOFTWARE | TCP/IP Stack | HTTP Web Server | FTP | E-Mail | PPP | Flash File System 2.0”

All hardware and software is included with the NetBurner MOD5234 Development Kit for only $299! WWW.GiURUMELE.Hi2.ROThe Development Kit features NetBurner’s Eclipse, an enterprise level professional IDE that provides editing, downloading and debugging in one environment. Order the MOD5234 Development Kit: Product No. NNDK-MOD5234-KIT

Product No. | MOD5234-100IR Information and Sales | [email protected] Web | www.netburner.com Telephone | 1-800-695-6828 M 1.qxp 1 than skin than deep. Bea CapSense. inputs inyourproduct.CapSenseenables: replaces buttons,switches,slidersandothermechanical CapSense PSoC solutiontocreateastylish,durableinterface. Maximize thedesignflexibilityandintegrationofCypress’s PSoC / 30 design toolsallowingcustomized,system-leveldesign. visualembedded Quick time-to-marketwithpowerful, etc. –allwiththesameCapSensechip. monitoring,motorcontrol,ambientlightsensing, battery Unique integrationofadditionalfunctions–LEDcontrol, detectors –onavarietyofconductivesubstrates. buttons, sliders,touchscreens,touchpadsandproximity – multipleinterfaces Single-chip implementationsupporting or module;youareincontrolofyourdesignatalltimes. through production.CapSenseisnotafixed-functionASIC Fast changestoyourdesignatanystagefromconcept / ® 2007 4:30PMPage1 -based CapacitiveTouch Sensing Cypress, theCypress logoandPSoCareregistered trademarksofCypress SemiconductorCorporation. Allothertrademarksarepro WWW.GiURUMELE.Hi2.RO ismore uty www.cypress.com/capseminar Register foraCapSenseNetSeminar: www.cypress.com/capexpress Download freePSoCExpress www.cypress.com/capchips Request freePSoCCapSenseICsamples: www.cypress.com/capkit Order adiscountedCapSenseDevelopmentKit: GET ST Applications enabledbyPSoC perties oftheir respectiveowners.©2007 CypressSemiconductorCorporation. Allrightsreserved. perties ARTED WITHCAPSENSENOW www.cypress.com/gocapsense Streamline yournextdesignwithCapSense: ® CapSense. ™ visualembeddedsoftware: 2.qxp 5/31/2007 9:59 AM Page 1

Link Instruments PC-Based Test Equipment Digital Oscilloscopes • 2 Channel Digital Oscilloscope • 500 MSa/s max single shot rate • 1Mpt sample memory 250 MSa/S (Dual channel) 512 Kpts 500 MSa/S (Single channel) 1 Mpts • Only 9 oz and 7” x 3.5” x 1.5” • Portable and Battery powered • USB 2.0 • FFT Spectrum Analyzer DSO-8202 (200MSa,128K) $799 DSO-8502 (500MSa,1MPt) $950

500MSa/s 1Mpts

Logic Analyzer & Port 3.2” x 3” xable 0.65” NEW! Pattern Generator USB 2.0 Powered • Logic Analyzer (32 channels) • Pattern Generator (up to 32 channels) • up to 400 MSa/s • Variable Threshold • 2 External Clocks • SPI output and disassembly • I2C output and disassembly WWW.GiURUMELE.Hi2.RO•up to 2Msamples/ch IO-3208A $750 IO-3232A $899 IO-3232B $1399

Link Instruments (973) 808-8990 www.Linkins4.com 3.qxp 8/27/2007 4:42 PM Page 1

WWW.GiURUMELE.Hi2.RO 207_Task_Masthead.qxp 9/4/2007 10:10 AM Page 4

TASK MANAGER

Mark Your Calendars FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia

ime sure flies when you’re marking your life according to an editorial cal- MANAGING EDITOR MEDIA CONSULTANT T C. J. Abate Dan Rodrigues endar. I can’t believe it’s already October. Since we’re only two months away from the New Year, I’d like to touch on a few important topics to ensure that WEST COAST EDITOR CUSTOMER SERVICE Tom Cantrell Debbie Lavoie we are all moving in the same direction as we approach 2008. CONTRIBUTING EDITORS CONTROLLER *** Jeff Bachiochi Jeff Yanco Ingo Cyliax 2007 READER SURVEY Robert Lacoste ART DIRECTOR KC Prescott I’d like to thank everyone who took the time to fill out Circuit Cellar’s 2007 George Martin Ed Nisley reader survey. We value reader feedback because this magazine has been GRAPHIC DESIGNER Mary (Turek) Sobuta reader-driven since Day 1. As you know, we use the information that we get NEW PRODUCTS EDITOR John Gorsky from our surveys when making decisions about the magazine’s editorial STAFF ENGINEER John Gorsky content, issue themes, advertising, and more. This year was no different. PROJECT EDITORS Steve Bedford Congratulations to John Hopprich of San Francisco, California. John Ken Davidson took the time to fill out the survey and was awarded an NEMA 4x/IP65 David Tweed enclosed operator interface 4" diagonal TFT from Reach Technology. As ASSOCIATE EDITOR John knows, it pays in more ways than one to keep active in the Circuit Jesse Smolin Cellar community. Thanks, John! *** ADVERTISING 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise PROGRAMMABLE LOGIC PUBLISHER Based on information that we gathered from the survey, we made an Sean Donnelly important change to our 2008 editorial calendar. (To view the calendar, go Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] to www.circuitcellar.com/submissions/editorialcalendar.html.) We found that ADVERTISING REPRESENTATIVE many of you have a serious interest in projects that use FPGAs, PLDs, and Shannon Barraclough Direct: 860.872.3064, E-mail: [email protected] other programmable logic chips. So, in December 2008, we will launch a ADVERTISING COORDINATOR new issue: Programmable Logic. Valerie Luster If you would like to propose an article for the new issue, consider writing E-mail: [email protected] about any of the following topics: design tips and tricks, innovative solutions to traditional design challenges (e.g., initialization, dynamic reconfiguration, Cover photography by Chris Rakoczy—Rakoczy Photography and security), or the spectrum of hardware and software tools that come www.rakoczyphoto.com into play when working on programmable logic applications. As usual, you PRINTED IN THE UNITED STATES should e-mail your article proposals to [email protected]. CONTACTS SUBSCRIPTIONS *** Information: www.circuitcellar.com/subscribe, E-mail: [email protected] Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, MICROCHIP CONTEST DEADLINE Hanover, NH 03755-5650 Address Changes/Problems: E-mail: [email protected] The submission deadline for the Microchip 16-Bit Embedded Control GENERAL INFORMATION Design Contest is 1:00 PM EST on October 16. It’s a good idea to submit 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] your entry a few business days prior to the deadline. This will give us a New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] chance to check for missing material and corrupt files. AUTHORIZED REPRINTS INFORMATION 860.875.2199, E-mail: [email protected] E-mail your entries to [email protected]. Be sure to include the AUTHORS following: Authors’ e-mail addresses (when available) are included at the end of each article. - Abstract WWW.GiURUMELE.Hi2.ROCIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar - Complete documentation Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional mailing offices. One-year (12 issues) subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95. Two-year - Code (24 issues) subscription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct sub- scription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 When you submit your entry, make sure that you label all of your project or call 800.269.6301.

materials with your assigned registration number. Good luck! Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

*** Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or As usual, send me an e-mail if you have any questions about article sub- from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to missions, contests, or the magazine. I look forward to hearing from you. build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction. The reader assumes any risk of infringement liability for constructing or operating such devices. Entire contents copyright © 2007 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. [email protected] Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 13.qxp 8/6/2007 4:36 PM Page 1

Put your creativity to the test!

Join the Ethernet Revolution!

Circuit Cellar magazine is pleased to bring you the WIZnet iEthernet Design Contest 2007. Now you can easily add Ethernet capability to your embedded project and win fame and fortune in the process. WIZnet’s W5100 hardwired TCP/IP Ethernet controller will be the key to your contest success. This 3-in-1 chip solution brings TCP/IP implementation without an OS. Both MAC and PHY are embedded.

Show us how you use the impressive W5100 to usher your embedded project into the Ethernet revolution. Your creativity and design skills could win you a share of $15,000 in cash prizes and recognition in Circuit Cellar magazine.

WWW.GiURUMELE.Hi2.ROFor details, visit www.circuitcellar.com/wiznet. 207_toc.qxp 9/4/2007 10:19 AM Page 6

October 2007: Signal Processing FEATURES

10 Signal Recovery 35 Resilience in Embedded Designs (Part 2) Restore the Attenuated Portion of an AC-Coupled Signal RS-485, Voltage Supervisors, Watchdogs, & Outputs Brian Felder Aubrey Kagan 18 Wireless Thermostat System 40 Simple Ethernet Darryl Uchitil Ken Merk 26 The Monarch Butterfly 46 Embedded Speech Build a Barometric Altimeter for Small Applications Thomas Black Nicusor Birsan & Ionut Tarsa

Build a Wireless Thermostat System (p. 18)

Signal Restoration (p. 10) The Monarch (p. 26)

COLUMNS

55 ABOVE THE GROUND PLANE Hearing Clearly Hardware Ed Nisley Gaming 60 FROM THE BENCH RoboGrowth Jeff Bachiochi 70 THE DARKER SIDE No Fear with FIR Put a FIR Filter to Work Robert Lacoste

80 SILICON UPDATE New Robotics Technology (p. 60) I Sense, Therefore I Am Tom Cantrell DEPARTMENTSWWW.GiURUMELE.Hi2.RO

4 TASK MANAGER 94 INDEX OF ADVERTISERS Mark Your Calendars November Preview C. J. Abate 96 PRIORITY INTERRUPT 8 NEW PRODUCT NEWS The Law of Unintended Consequences edited by John Gorsky Steve Ciarcia 93 CROSSWORD

6 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 7/27/2007 4:16 PM Page 1

WWW.GiURUMELE.Hi2.RO npn.qxp 9/4/2007 10:21 AM Page 8

Edited by John Gorsky Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. 96-CHANNEL PCI EXPRESS ANALOG INPUT DAQ CARD The DAQe-2208 is a 96-channel, 12-bit, 3-Msps, ultra-high- for the simplified expansion of testing capabilities, density analog input data acquisition card that combines high autocalibration that adjusts the gain and offset to density with high bandwidth via an x1 PCI Express bus. This within specified parameters to ensure testing accu- high-end card is capable of sampling up to 96 single-ended chan- racy regardless of the uncertainty of the environ- nels with different gain settings and scan sequences. It also ment, and scatter-gather bus mastering to enable offers differential modes to the acquisition of large enable 48 channels to provide amounts of data at a high optimal noise elimination, speed by transferring data making it compatible with directly to and from the mem- ultra-high-density analog sig- ory through the DMA con- nals with various input ranges troller. The DAQe-2208 sup- and sampling speeds. The ports , DAQe-2208 is ideal for data including Windows Vista and logging and signal analysis operating systems, and applications requiring large also comes with software sup- amounts of input channels port for LabVIEW, MATLAB, and data transferring. The .NET, Visual C++, and Visual DAQe-2208’s features also Basic. include analog and digital The DAQe-2208 is available triggering and 24 programma- now and is competitively priced ble digital I/O lines. starting at $1,095 and is avail- The DAQe-2208 offers a able with discounts in volume. system synchronization inter- face (SSI) bus to allow up to ADLINK Technology, Inc. four cards to be synchronized www.adlinktech.com

WWW.GiURUMELE.Hi2.RO

8 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com npn.qxp 9/4/2007 10:21 AM Page 9

NEW PRODUCT NEWS LOW-FREQUENCY FILTER BASED ON dpASP TECHNOLOGY The AnadigmFilter1 is the first in a family of chipsets to use a dynamically programmable dpASP and a state machine. This dpASP incorporates a univer- sal analog filter architecture that provides the designer with frequency options from DC to 600 kHz, using a sixth-order filter. Low-pass, band-pass, high-pass, or band-stop circuits can be quickly implemented without the usual D/A conversions or writing DSP or microprocessor programming code. The designer simply selects from the comprehensive library of presets avail- able within the AnadigmFilter1. The onboard filters can be selected to emu- late Butterworth, Bessel, Chebyshev, and inverse Chebyshev filter approxima- tions. This is the first low-frequency filter to provide the designer with break- through design simplicity—enabling the selection of one of four types of fil- ters—frequency and gain control using a simple 16-bit control interface, DIP switches, or hardwired pull-up and pull-down resistors. The chipset input consists of a choice of one or two fixed input stages (which can be summed), each of which can be configured using external resistors and capacitors to provide gain or attenuation, level shifting, single-ended-to-differential conver- sion, and first-order, low-pass, and high-pass filtering. Gain and stop- band frequency can be dynamically controlled in real time without interruption to the signal, allowing filter gain and frequency to be swept across one full octave of the frequency spectrum. The cost for U.S. delivery in 1,000-piece quantities is $11.28 each. In addition, the AN236K04- EVAL2 AnadigmFilter1 evaluation board, which includes the AN236K04 chipset costs $199.

Anadigm, Inc. www.anadigm.com

TWO-LINE EMC FILTERS FOR MEDICAL APPLICATIONS Compact two-line filters of the SIFI-F (B84111FM*) series are now available in a medical version. Not only do they offer all the advantages of the standard SIFI-F version, they also boast an extremely low maximum leakage current of 2 µA. With its compact dimensions, the SIFI series is well suited for medical applications such as ultrasound devices, X-ray systems, or other medical diag- nostic devices where low leakage current is a critical factor. Despite the compact design, it offers very good suppression of symmetrical and asymmetrical interference. The SIFI-F, along with the larger SIFI-G and SIFI- H, is designed for the climate category of –25° up to 100°C. UL, cUL, and ENEC approvals are in process and are anticipated soon.WWW.GiURUMELE.Hi2.RO Filters for current levels from 3 up to 36 A are available from stock as samples. For production quantity requirements, lead time is six weeks at costs ranging from $11.50 to $25 each through EPCOS distributors, based on the type selected and quantity level.

EPCOS, Inc. www.epcos.com www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 9 2710019 felder.qxp 9/4/2007 10:39 AM Page 10

FEATURE ARTICLE by Brian Felder Signal Recovery Restore the Attenuated Portion of an AC-Coupled Signal

Brian developed an algorithm for a digital filter that restores the attenuated portion of an AC- coupled signal. A digital storage oscilloscope captures the waveform and data is passed through the digital filter. The result is the original signal without the DC portion.

There are many instances in which blocked could be 2 or 3 V for an RTD needs constant tweaking. Also, most AC measurements are hampered by the setup to measure small temperature sensors lack the low output imped- coexistence of high DC voltages. Sup- variations to possibly hundreds of volts ance and power necessary to drive the pose you wanted to measure an AC-rip- for the likes of photomultiplier tubes. relatively low input impedance of an ple component riding on the output of a Piezoelectric pressure, force, and adder without significant error. DC power supply with an oscillo- accelerometer sensors are biased with a For applications that required AC cou- scope. If you DC-couple the signal, the constant current. The charge induced pling, I wanted to find a way to recover DC output voltage will saturate the when the piezoelectric material is the data thought to be lost. An Internet vertical amplifiers long before reaching stressed is amplified and again passed search (with different variations of the the gains necessary to view a low-level through a DC-blocking capacitor to a words DC, signal, AC-coupled, correc- ripple. And, if you AC-couple the signal measuring device of very high imped- tion, and recovery) turned up little infor- to block the DC voltage, you are pass- ance and gain. In addition to the loss mation except examples and definitions ing the signal through a high-pass filter through AC coupling, the piezoelectric of high-pass filters and their losses, along attenuating the low-frequency detail sensor’s charge will leak and dissipate with college course outlines and notes. you were interested in observing. through its internal and load resistances. The closest thing I found was something A typical oscilloscope in AC-coupled A time constant can be specified when called sag correction, which is built into mode has an input resembling what you ordering the sensor that may satisfy cer- some video amplifiers. But this was an see in Figure 1, a high-pass filter with a tain applications, but infinity is not an analog circuitry solution to video signal cut-off frequency around 10 Hz. (I meas- option. The output will always droop, distortion not suited to this problem. ured mine at around 8 Hz.) To illustrate which must be taken into account for It looked like I was on my own. I how this affects low-frequency response, low-frequency measurements. spent hours comparing distorted wave- refer to the waveform in Figure 2 result- In some cases, the output of the sen- forms with their original counterparts, ing from a 60-Hz square wave captured sor may be DC-coupled to an amplifier attempting to see a strategy to reverse by a capacitive-coupled storage oscillo- configured as an adder and summed the effect. I tried several avenues, from scope. The missing DC and attenuated with an adjustable voltage with a polari- different summing schemes to a mix- low frequencies are evident in the ty opposite the static voltage. That ture of differentiation and integration distortion of the waveform where both zeroes the amplifier while the sensor is schemes without much success. Then the top and bottom decay toward zero. at rest. But, this would require a circuit a simple solution presented itself. In the world of instrumentation where with a low static voltage, low gain, little I developed an algorithm for a digital I spend much ofWWW.GiURUMELE.Hi2.RO my time, there are drift, and a zeroing potentiometer that filter that restores the attenuated por- many sensors that are required to be tion of an AC-coupled signal. Using a capacitive coupled for the same reason digital storage oscilloscope or data acqui-

as the power supply example, a static VC sition system to capture the waveform, voltage that carries the desired signal. the data is passed through the digital fil-

VIN R To ver tical amplifiers The sensors are usually driven with a VR ter, giving you the original signal constant current. The voltage change without the DC portion. Essentially, induced when a stimulus is applied is the algorithm’s result is what you passed through a DC-blocking capacitor would expect to see from a theoretically to a high-impedance and high-gain Figure 1—This is a representative circuit of a typical perfect DC blocking capacitor. However, measuring device. The DC being AC-coupled oscilloscope input. this assumes that all of the system’s

10 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710019 felder.qxp 9/4/2007 10:39 AM Page 11

components remain linear and unsatu- rated. I include this caveat because measurement systems, especially those with high gains or containing piezoelec- tric components, can be saturated easily.

THE EPIPHANY While comparing printouts of an AC- and DC-coupled version of a 5-Hz square wave captured with a storage oscillo- scope, I recognized the obvious exponen- tial decay everyone is familiar with in RC circuits. I visualized what I would need to add to the AC-coupled wave- Figure 2—This is a 60-Hz square wave distorted by AC coupling. form to make it match the source wave- form with the result shown in Figure 3. I AC waveform across the capacitor. the delta of the voltage rise or fall of recognized the missing portion as the Since the AC voltage across the the capacitor is calculated by multi- voltage change of a capacitance respond- capacitor is not readily available, it plying each of the instantaneous volt- ing to a step function and finally realized has to be derived. This turns out to be age values by a constant, k, which that the missing signal is not lost. It’s easy because the instantaneous out- embodies all the variables of the cir- stored across the DC-blocking capacitor. put voltage of the high-pass filter is cuit’s time constant and time between The DC-blocking capacitor will charge directly related to the instantaneous samples: up to the static voltage being blocked. value of the slope of the voltage dT When the AC signal is applied, the change across the capacitor. The delta k = RC capacitor will charge and discharge above of the voltage can then be calculated: [2] dV = kV and below this value, the magnitude of CR

the voltage dependent on the value of the VRC = IR For better accuracy, the endpoints of circuit’s resistance. The AC-coupled sig- C dV the delta segments should coincide I = C nal is the original waveform, minus the C dT with the data points. Therefore, I aver- RC dV static DC voltage, and without the AC V = C age two data points to estimate the voltage induced across the capacitor. R dT [1] capacitor’s voltage delta between VdT So, it would be a simple matter to obtain dV = R them. The phase difference added for C RC the unmolested waveform of the desired half of a data clock cycle probably signal without the DC voltage by revers- won’t add significant error provided ing the process and adding the output THE ALGORITHM the sample rate is fast enough for the

waveform of the high-pass filter to the Using the quantized values of VR, frequency content. But, given the ease of calculation, I use the average. It’s then just a matter of keeping a run- ning sum of the individual voltage delta segments to derive the capaci- tor’s AC voltage and adding it to the output voltage to determine the desired voltage as illustrated in the derivation of Equation 3:

V =+ V V INnnn OUT C ⎡k n ⎤ VC =+ ⎢ ∑ V OUT V OUT ⎥ + VCC nmm2 –1 0 WWW.GiURUMELE.Hi2.RO⎣ m = 1 ⎦ [3] ⎡k n ⎤ V =+ V ∑ V + V + V INnn OUT⎢ OUT mm OUT –10⎥ C ⎣ 2 m = 1 ⎦ Equation 3 includes two user-pro-

vided variables. Note that VC (0)—cov- ered momentarily with the assump- tions—is the initial value of the AC

waveform across the capacitor. VOUT(0) is needed to support an initial average Figure 3—The top waveform is a 5-Hz square wave distorted by AC coupling. The bottom waveform would have to for the first delta calculation. In a data be added to reverse the distortion. set with a baseline, I normally set

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 11 2710019 felder.qxp 9/4/2007 10:39 AM Page 12

without a baseline. I usu- ally have a baseline at the end of the datastream, making it easy to see the waveform settle back to zero while fine-tuning the values of k and the DC offset. Figure 4—These waveforms show the distorted 60-Hz waveform presented earlier along with the results of it being passed through the algorithm. For processing repeti- tive or arbitrary wave- forms, a known waveform

VOUT(0) equal to VOUT(1) so the aver- can be captured and adjusted to cali- age ends up being the first data point, brate a k value for the system. Then,

VOUT(1). If the data begins with a slope, with k known, the values of the DC

the value of VOUT(0) is interpolated offset and VC(0) can be adjusted to

through the values of VOUT(1) and obtain a satisfactory result for the

VOUT(2), with VOUT(0) = 2VOUT(1) – VOUT(2). unknown waveform. There are a few assumptions made for implementing this simple equa- EXAMPLES tion. First, there is no DC leakage I took the oscilloscope-generated through the high-pass filter or any comma-separated values (CSV) file of the sampling system error adding DC off- 60-Hz square wave presented earlier and set into the data. Any offset must be opened it in a spreadsheet revealing two removed prior to using the algorithm, columns containing time and voltage. I or the calculated results will grow due then added a third column for the volt- to the summation. age value added to an offset value to Second, at the start of acquisition, remove any DC offset. A fourth col- the starting value of the blocking umn was created to hold the running capacitor’s AC waveform is known. An sum of the voltage values multiplied by accurate construction of the unknown k. Finally, a fifth column holds the waveform is the key to the algorithm. sum of the third and fourth, the inter-

With a good baseline, the initial value polated VIN or the desired voltage. I of the AC waveform will be zero. If the then opened an XY scatter chart of data represents a repetitive or arbitrary time and the desired voltage (columns waveform, an educated guess will have 1 and 5) inside the sheet so I could to be made for the initial voltage value observe the waveform while adjusting

and specified in VC(0). the values of the DC offset and k. Finally, the blocking capacitor has I roughly calculate the value of k charged to the full value of the static DC voltage. If the blocking capacitor has not fully charged before data is taken, the changing average value of the capacitor’s AC waveform will have to be accounted for with the introduction of another variable, something I have not yet needed to attempt. WWW.GiURUMELE.Hi2.ROI usually deal with singular events with lead times long enough to estab- lish a baseline and I am assured that the blocking capacitor is charged and has an AC voltage of zero. I then take an average of the baseline to deter- mine the DC offset and adjust the data accordingly before passing it through the algorithm. But, as you will see in Photo 1—This is a PCB Piezotronics 201A piezoelec- the following examples, it’s not diffi- tric load cell with a 484B ICP power unit that is used to cult to adjust for a DC offset even generate the load-cell waveform.

12 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 29.qxp 8/6/2007 5:07 PM Page 1

Fully Loaded, Small Form Factor MCUs Silicon Laboratories’ mixed-signal MCUs combine a high-speed 8051 32 kB

CPU, Flash memory and best-in-class analog peripherals in ultra-small 16 kB

packages allowing designers to reduce component count while improving Flash 8 kB system performance. These highly-integrated, feature-rich devices are

optimized for space-constrained, low-power, cost-sensitive applications. 9 mm22216 mm 25 mm Size Low-Cost, Professional Tools Complete development kits (including in- Highest Functional Density system debug and integrated development • 8–24 Bit ADC environment) WWW.GiURUMELE.Hi2.ROmake development quick and • 2–32 kB Flash Memory easy. Low-cost evaluation kits and reference • 25–100 MIPS 8051 CPU designs simplify evaluation and accelerate time-to-market.

Product details: www.silabs.com/SmallMCU

MCUs TIMING POWER BROADCAST WIRELINE WIRELESS www.silabs.com 2710019 felder.qxp 9/4/2007 10:39 AM Page 14

just to have a starting point. My because the equivalent circuit oscilloscope’s cut-off frequency of the internal quartz crystal to is around 8 Hz. That gives me an the sensor is essentially an RC RC time constant of 0.01989 s. circuit. The internal charge The sample rate is 100 kHz, or a amplifier that converts the sample every 10 μs. So, for a crystal’s charge to a voltage is starting value of k: an integrator where the feed- back capacitor forms yet dT 0.00001 = = 0.00050 RC 0.01989 another RC. The distributed [4] RCs can be combined into an equivalent RC time constant The beauty of a spreadsheet for the algorithm. is the ability to play a game of Photo 1 shows a PCB high-low with any of the val- Piezotronics 201A05 piezoelec- ues to compare many possible tric load cell with a 484B ICP results. The empirical route power unit that was sequen- avoids the tedium of measur- tially loaded and unloaded with ing or estimating the values of three 25-lb weights. The result- all the stray capacitances and ing raw and recovered wave- resistances to try and obtain forms are shown in Figure 6. the exact value. I obtain a good The 201A05’s specification waveform at k = 0.00048 (see sheet gives a 1-mV output per Figure 4). (From this value, I pound load. The recovered Figure 5—This is an arbitrary waveform distorted by AC coupling (top). The back out an RC value of original arbitrary waveform is DC-coupled compared to the AC-coupled version waveform’s accuracy was very 0.02083 to use as the starting restored by the algorithm (bottom). good considering I was only value for my next waveform using 1.5% of the 5,000-lb taken with the oscilloscope. It capacity of the load cell. I took also gives a value of 7.64 Hz for the arbitrary waveform that, although my time with the weight changes to cut-off of the oscilloscope’s filter.) quite simple, I don’t think anyone show the deep decay of the output I then adjust the DC offset value could argue would be difficult to ana- voltage over time. Note that during that is added to each output voltage lyze as filtered (see Figure 5, top). I the first removal, the weight got stuck value to fine-tune the waveform. opened the data in a spreadsheet, and was manhandled a bit, but the Again, even a small DC error will adjusted for DC offset, and determined adjusted waveform still returned to cause the calculated value to grow a value for k at 0.042. (This was a dif- the 50-mV level indicating the positive or negative due to the sum- ferent scope than the last example, so remaining 50-lb load. mation. The capture of the repetitive I took the sample interval of 0.001 s For the spreadsheet, I estimated the 60-Hz square wave happened to start and divided by RC = 0.01592, from the time constant by observing how long at the DC average level of the AC typical cut-off of 10 Hz for a starting k it took for the highest voltage in the waveform, so the entry of an initial = 0.063. Backing out from k = 0.042 raw data to decay 37% from the step

value other than zero for VC was not gives the oscilloscope’s true cut-off of input (i.e., t = 1/e). Using the pop-up required. 6.7 Hz.) I have to admit to cheating a windows showing the point values on bit on this one. I had the DC-coupled the chart when you mouse-over the ARBITRARY WAVEFORM version of the waveform on the chart trace in Excel, I calculated about 11.24 s To demonstrate the accuracy of the while adjusting values because I want- for the droop from 0.0370 to 0.0138 V. algorithm, I captured an AC-coupled ed to show how the adjusted waveform Dividing the sample time (0.040 s) by fell directly onto the the estimated RC (11.24 s) gave me a DC-coupled waveform starting value of 0.0036. This was very WWW.GiURUMELE.Hi2.RO(see Figure 5, bottom). close to the final selection of k = 0.0034. PIEZO SENSORS As I mentioned earli- FIRST PROFESSIONAL USE er, piezoelectric sen- I was drawn into a problem some of sors not only have a my colleagues were having while blocking capacitor, investigating the spectral signature of they also have internal a solid propellant. Due to its designa- leakage. The internal tion as an explosive, the facility’s safe- Figure 6—This is a piezoelectric load cell’s distorted output waveform of three leakage also follows an ty procedures for such materials had increasing loads and three decreasing loads, compared to the restored version. exponential decay to be adhered to for the protection of

14 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 15.qxp 8/23/2007 11:13 AM Page 1

Look at the Peripherals You Can Map to I/O Pins USA and in other countries. All trademarks mentioned herein are property of their respective Now you have the flexibility to customize your microcontroller with Microchip’s Peripheral Pin Select feature.

Get up to 64 KB of Flash and 8 KB of RAM Purchase and program your microchip in as few as 28 pins with a peripheral set 16-bit PIC24 devices and DIRECT that can be dynamically customized for your related development tools at... www.microchipdirect.com application with Microchip’s 16-bit PIC24 RAM Flash microcontrollers! Device Pins (KB) (KB) Features include up to: companies. ©2007, Microchip Technology Inc. All rights reserved. Microchip Technology companies. ©2007, GET STARTED IN 3 EASY STEPS PIC24FJ16GA002 28 4 16 5x 16-bit Timers at www.microchip.com/PPS PIC24FJ16GA004 44 4 16 5x Output Compare/PWM 1. FREE 16-bit web seminars PIC24FJ32GA002 28 8 32 5x Input Capture 2. FREE product samples PIC24FJ32GA004 44 8 32 Real Time Clock Calendar 3. Exclusive development tool discounts PIC24FJ48GA002 28 8 48 2x UART PIC24FJ48GA004 44 8 48 2x SPI Check out our web PIC24FJ64GA002 28 8 64 2x I²C™ site for special pricing WWW.GiURUMELE.Hi2.ROon the 16-bit 28-pin PIC24FJ64GA004 44 8 64 Parallel Master Port Development Kit and MPLAB® ICD 2 PIC24HJ12GP201 18 1 12 2x Analog Comparators In-Circuit Debugger! PIC24HJ12GP202 28 1 12 10/12-bit ADC

The Microchip name and logo, the Microchip logo and MPLAB are registered trademarks of Microchip Technology Incorporated in the the Microchip logo and MPLAB are registered trademarks of Microchip Technology The Microchip name and logo, www.microchip.com/PPS

Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs

PIC24 PPS ad for Circuit Cellar.1 1 8/8/2007 1:19:43 PM 2710019 felder.qxp 9/4/2007 10:39 AM Page 16

return to zero. The results were to interpret the data. They did, howev- impressive. Figure 7 shows some rep- er, describe the mathematical founda- resentative data to illustrate the out- tion behind the technique. Even come. though I didn’t use the papers for this For the relatively short time periods article, I had to recognize the men and of capture in which I’ve used the algo- women who were here before me. rithm so far, the results of every case Needless to say, I wish they would have been excellent. For long-term have turned up in my first search data collection, it is inevitable that attempt. But, all in all, this was a drifting, noise, round-off error, and well-thought exercise with a refresher Photo 2—This is the “meandering” liquid nitrogen-cooled more will cause errors. The longest in the basics. I mercury-cadmium-telluride infrared detector. data set I’ve attempted was the load cell example at around 90 s. The max- Brian Felder is an electrical engineer personnel and of course for the protec- imum time the algorithm will yield with CUBRC’s Aerothermal/Aero- tion of the facility itself. Unfortunate- accurate results depends on the accu- Optic Evaluation Center, an affiliate ly, the time involved in securing the racy and stability of the systems gen- of The Research Foundation of the facility for the test allowed one of the erating and acquiring the data. State University of New York. His sensors to drift to a point where the Through the examples, I tried to interests include analog and digital signal amplifier saturated. show that there are many applications circuit design, software programming, The liquid nitrogen-cooled mercury- with obvious advantages. The greatest and photography. He holds an A.A.S. cadmium-telluride detector used to advantage, of course, is avoiding high- in Electrical Engineering Technology, measure the infrared portion of the ly complex circuitry with intensive a B.S. in Mathematics, and has over spectrum would “meander” (as my calibration requirements for short data 30 years of experience in electronics. colleague put it) to the point of being sets by using a simple blocking capaci- You may contact Brian at bfelder_1@ unusable by the time the experiment tor, the value of which was made yahoo.com. was ready to commence (see Photo 2). almost irrelevant by the algorithm. I Reentering the secured test area to believe in keeping things simple. It rezero the amplifier was not an option, usually saves quite a bit of time and PROJECT FILES nor was adjusting the zero remotely. It money. was a last resort, but the output had to To download the load cell example, go to ftp://ftp.circuitcellar.com/pub/Circuit be AC coupled. The test was a success, MORE RESEARCH _Cellar/2007/207. but the droop in the recorded AC-cou- While writing this article, I revisited pled data rendered it unacceptable. my Internet search to obtain a few A capacitor large enough to hold the examples of the hits I received. Buried RESOURCES signal up to an acceptable level for, in in the noise of a Google search was an some cases, almost a full minute of interesting 2002 paper by C.A. Joyce T. Elbert and B. Rockstroh, “Some test time was definitely impractical. et al entitled “Variability in AC Amplifi- Remarks on the Development of a There was no choice but to use the er Distortions: Estimation and Correc- Standardized Time Constant,” algorithm to adjust the data. Thank- tion” (Psychophysiology, Issue 39). It Psychophysiology, 17, 1980. fully, there was plenty of lead time to turns out that this technique has been C. A. Joyce, I. F. Gorodnitsky, W. A. establish a baseline level and guaran- used in the physiology field for many Teder-Salejarvi, J. W. King, and M. tee that the blocking capacitor was years to reduce data taken by elec- Kutas, “Variability in AC Amplifier fully charged. There was also plenty of troencephalographs (EEG). The paper Distortions: Estimation and Correc- post time, enabling variable adjust- goes on to refer to another titled “AC-to- tion,” Psychophysiology, 39, 2002. ments to be made for a very accurate DC Inverse Filtering of Event-Related potentials” by D. S. Ruchkin, “AC to DC Inverse Fil- Daniel S. tering of Event-Related Potentials,” in WWW.GiURUMELE.Hi2.RORuchkin. Hmm. W. C. McCallum and S. H. Curry (edi- AC-to-DC tors), Slow Potential Changes In The ... I Human Brain, Plenum Press, New like the sound of York, 1993. that. Other works were cited too, but the SOURCE papers did not 201A05 Piezoelectric load cell and illustrate any 484B ICP power unit Figure 7—This is an illustrated test result waveform of an AC-coupled infrared detector actual physical PCB Piezotronics, Inc. compared to its restored version. procedure used www.pcb.com

16 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 17.qxp 8/23/2007 11:17 AM Page 1

WWW.GiURUMELE.Hi2.RO 2710017 uchitil-test.qxp 9/4/2007 11:05 AM Page 18

FEATURE ARTICLE by Darryl Uchitil Wireless Thermostat System

Darryl designed a wireless zone thermostat system that can remotely read the temperature, calculate the dew point, and force a setback. This easy-to-implement design is perfect for the home or office.

Your home’s thermostat plays an stat. This required more power than article about ZigBee (Ethan Leland et important role in providing a com- the internal batteries could provide, so al, “Robot Localization and Con- fortable temperature range and pro- I added a DC/DC converter. The inter- trol,” Circuit Cellar 188), I discov- tecting your house from freezing. It face needed a microprocessor with ered that I might be able to solve also impacts heating and cooling serial communication to a central some of my interface problems. So, I costs. When I moved into my house in location. But, voltage transients on the contacted my local Freescale Semi- 2000, it had a conventional mercury serial interface could lock up the ther- conductor representative and got a bulb thermostat. I wanted a network- mostat, so I changed it to optically 13192DSK-BDM development kit able thermostat, but I couldn’t find isolated serial with an isolated with two sensor application reference one. I found little more than a human DC/DC converter. The power con- design (SARD) boards, a USB debug- machine interface (HMI) that required sumption of tens of milliwatts inside ger, and some sample code (see Photo an expensive controller to provide the the thermostat could invalidate the 1). I then checked around for inexpen- intelligence. I considered building my readings unless I had some remote sive ZigBee modules and found that own, but I decided that the time power-down feature. The project kept DigiKey carried a $27 Panasonic involved would be too great and any growing in scope, so it never got fur- PAN802154HAR00 module that was potential failure could cause the house ther than a series of schematics. software-compatible with a SARD and to freeze, which was too big a risk. A Fortunately, while reading a 2006 had an idle current as low as 3 μA. few years later, when my HVAC sys- tem was converted to three zones, I needed two more thermostats, so I started searching again for a network- able thermostat. Although there were numerous systems to choose from, the thermostats were in the $200 range and they still needed a controller. There was no way three of these would have fit my budget. While researching on the Internet, I found some information about using Dallas SemiconductorWWW.GiURUMELE.Hi2.RO 1-Wire devices to communicate with a Lux Products thermostat. I learned how to read vari- ous values from an internal serial con- nector on a Lux TX9000LC thermo- stat. This got my attention because the thermostat costs less than $30 (on sale). Unfortunately, I could not write any data to this thermostat, so I drew Photo 1—The Freescale Semiconductor SARD board includes a three-axis accelerometer, an 802.15.4 radio, and up a design that used three optocou- a user-programmable Freescale MC9S08GT60 microprocessor. The Freescale 13192DSK is available with or with- plers to drive buttons on the thermo- out the P&E Microcomputer Systems USB programmer/debugger.

18 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710017 uchitil-test.qxp 9/4/2007 11:05 AM Page 19

Careful measurements showed that a) b) the TX9000 idle current was around 12 μA, so it looked like the module would be able to run on the existing thermostat’s batteries. My original design used a PIC microprocessor running at 5 V with Honeywell humidity sensors. But, the Panasonic module runs on 3.3 V and the Honeywell sensors are rated for 4 to 5.5 V. I learned that a Sensirion Photo 2—From the front, the original Lux Products TX9000LC is indistinguishable from the Lux TX9000RF (a). A four- SHT11 would run from 2.4 to 5.5 V pin serial connector is inside the older version (b). Note the temperature sensor (small black dot) at the very top near and consume less than 1 μA in stand- the right edge of the board. by and only 550 μA when measuring. The SHT11 was a little more expen- new version. I recently discovered one. you want to circulate air through the sive, but it provided a more precise Lux sells the TX9000RF thermostat entire house, you have to turn the fan temperature reading. The demo appli- with a hand-held remote control. The on at each individual thermostat. It cation on the web site also provided a newer versions of the TX9000LC at seemed logical to add a fan relay to dew point calculation and had a low- my local store are labeled TX9000RF the design. There was no fan connec- battery indication at 2.47 V. on the PCB (see Photo 2). The inter- tor on the thermostat, so I used a two- I contacted Lux and found that there nal serial connector has an additional pin header on the interface board. A is another version of the thermostat, pin, VSS, which makes interfacing short pigtail (not shown) is wired to which has a slightly different serial easier. That is the version I used for the thermostat’s fan terminals to protocol but supports reading a wider my project. enable the board to be removed easily. range of data, including the entire The circuit includes wiring to con- thermostat programming data. It also nect the Panasonic module to the THERMOSTAT COMMUNICATION supports writing, so I figured I could thermostat and the humidity sensor, The TX9000 uses a four-wire serial do a remote temperature hold, a tem- and a little glue to drive the fan relay communication scheme that’s similar perature setback, or perhaps copy the (see Figure 1). To connect to the ther- to an SPI. Read data is clocked in at programming from one thermostat to mostat, I had to disassemble it and the same time write data is clocked another. install a five-pin header in the holes out (see Figure 2). The first response My two TX9000 thermostats already on the board (see Photo 3). byte is discarded. The second indicates responded to the older protocol, but There was no VDD pin, so I added one the command was accepted. The third not to the newer one. The Lux repre- to the positive battery contact. response byte contains the read data. sentative swore that the newer proto- In a zone heating system, when you Between each byte, you have to wait col had been out for several years, so I manually turn on the fan at one ther- for the thermostat to respond. It often kept checking my local store for the mostat, all the other zones close up. If takes 1 to 1.5 ms. Communication begins with a wait for SIOF to go high. The Lux documenta- tion describes neither the minimum bit time nor the minimum delay between bytes (SIOF low). Apparently, it periodically does some internal housekeeping, dur- ing which the SIOF will be WWW.GiURUMELE.Hi2.ROlow. The Lux documentation does not mention how long or how frequently this hap- pens. On my reference unit, the interval was about 60 s and lasted 150 to 680 ms. Because this occurs asyn- chronously to the serial communication, any given thermostat read cycle could Figure 1—The electrical part of the project was mostly wiring. The magic is in the application software. be extended by this amount.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 19 2710017 uchitil-test.qxp 9/4/2007 11:05 AM Page 20

a) b) There was also no information on the maximum speed of the SCLK line. The fastest reliable communica- tion that I was able to achieve was 30 μs per bit. This seems quick, but when you add the inter-byte delays, reading a single byte value takes sev- eral milliseconds.

SAVING ENERGY The TX9000’s power consumption is Photo 3a—The newer Lux TX9000RF board has a position for a five-pin header with the signals labeled. Note the around 12 to 15 μA idle. About once a “TX9000RF” designation on the board. b—The Panasonic 802.15.4 module fits neatly inside the case. minute, it rises to 1.5 mA for 150 ms and then frequently goes to 7 mA for 680 ms depending on the internal activity (see Photo 4). There was no obvious pattern to this longer, higher current. After a power cycle, the TX9000 would be busy for 680 ms once a minute, but after 5 to 6 min., it dropped to the lower current once a minute. This is likely dictated by the 5th International System-on-Chip heat/cool activity and the recent tem- perature rate of change. (SoC) If you assume that 20% of the time it used the higher power figure, then the Conference & Exhibit thermostat consumes the following: 14. 5 µA (idle current) 1 4 µ A =×× 1.5 mA 0.150 ()low cuurrent every minute November 7 & 8, 2007 60 s 0.20 Radisson Hotel Newport Beach, California 16 µ A =×× 7 mA 0.680 ()high current some minutes 60 s −−−−−−− CPU/DSP Cores, Multicore, Embedded Memory, 34.5 µA average current Semiconductor Advances, Low-Power Issues, Chip/System Architectures, New Design & Development Typical AA batteries are rated at 2 Tools, EDA-related Issues, Multimedia IPs, High-Speed to 2.5 Ah (0.9 V), which would be over Interfaces, NoC, Challenges with Analog Design, 60,000 h, or well over six years. Note SoC/ASIC/ASSP Design issues, FPGA & Foundry, and that this is a rough estimate and does Much, Much More . . . not include the power used to back- light the display or change the state of the latching relay (your mileage may www.SoCconference.com vary). The Panasonic module is rated to consume as little as 3 μA in standby. The Most Targeted & Informative This figure applies when the radio is System-on-Chip (SoC) off, the low-voltage detect is off, and Conference & Exhibit all the port pins are set to outputs and Event of the Year! at a zero state. In real life, you cannot WWW.GiURUMELE.Hi2.ROset all pins low, or more current Don’t Miss Out! would be consumed from the thermo- For Information and Questions, stat serial lines, and indeed, the ther- Please Contact SoC Conference Organizing Committee: mostat may not function properly. By [email protected] taking those steps, with the exception 949-851-1714 of the thermostat serial communica- tion lines, I was able to keep the idle current below 5 μA. www.SavantCompany.com I used a Parallax USB oscilloscope to measure the current consumption. I ran the board from a 3-V bench sup-

20 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710017 uchitil-test.qxp 9/4/2007 11:50 AM Page 21

ply and measured the volt- rupting other data until I age across a 22-Ω 5% car- SCLK checked with Freescale. I bon-composition resistor. SIOF found that the log10f() The Freescale microproces- SOUT B0 B1 B2 B3 B4 B5 B6 B7 function required 0x9c bytes sor used about 3.5 mA while of stack. Fortunately, the B0 B1 B2 B3 B4 B5 B6 B7 reading thermostat or humid- SIN Freescale MC9S08GT60 has ity data (see Photo 5). Because Figure 2—The thermostat uses four wires for serial communication. The data is 4 KB of RAM and I was using some of the data did not need latched at the falling edge of the clock. about 1 KB, so changing to a to be read as often, I estab- larger stack size was not a lished a priority counter for each data several floating-point operations, problem. To compensate for the long item. As a result, the time spent reading which are expensive in execution time execution time, the humidity is read the data varied from 76 to over 530 ms. and in memory. I had some problems every 5 min., and the dew point is cal- The average for 50 reads was 174 ms. with the dew point calculation cor- culated every 15 min. The radio (and microprocessor) con- sumed about 43 mA when powered up. The figure also included 6 mA for the LED. I turned on the LED during transmission because I felt that having an activity indicator was worth the power penalty. The radio datasheet specifies 35 mA (maximum) during transmission and 42 mA (maximum) during reception. The total transmis- sion time was approximately 1.8 ms. My thermostat data packet consisted of 43 bytes. The Freescale stack adds a 2-byte frame control. The Freescale MC13192 transceiver adds a 6-byte header and appends a 2-byte CRC. When the thermostat receives a com- mand, it responds with an ACK/NAK message. I measured the 7-byte ACK message from the thermostat at 670 μs (see Photo 6). At the 250-kbps maxi- mum rate, (43 + 10) × 8 bits should take 1.7 ms, and the ACK message should take 544 μs, which is well within my measurement accuracy. If the ZigBee module transmits once per minute and responds to a com- mand once an hour, then the average power consumption of the module in this application works out to:

5 µA ()idle 174 ms 10 µ A =× 3.5 mA ()measurement 60 2.9 ms 21. µA ==× 43 mA ()transmit time 60 6 msWWW.GiURUMELE.Hi2.RO 43. µ A =× 43 mA ()listen time 600 0.001 s 012. µ A =× 43 mA (assume ACK happens one/hour) 3,600 s −−−−−−− 21. 3 µA average current

The idle power consumption of the SHT11 is 1 μA (maximum), and up to 550 μA when measuring. This is dwarfed by the 3.5 mA that the micro- processor consumes while reading it. The scaling and correction requires

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 21 2710017 uchitil-test.qxp 9/4/2007 11:50 AM Page 22

all-pins-outputs, all-pins-low, dropped it to 80 μA. The Panasonic FAE warned me that the low-voltage detect (brownout) circuit consumes around 70 μA. Disabling this brought it down to less than 5 μA at 3 V (including the SHT11 idle current).

IS IT ZigBee? Using a full ZigBee stack creates compatibility advantages over other sensors and with routers, but the downside is up to 21 bytes of addition- al data per packet and a somewhat Photo 4—When the thermostat performs a measurement or calculation, it consumes more power. This is one of longer development and testing cycle. about four different power signatures that were observed. Achieving compatibility means more rules to follow and some sort of con- The Freescale MC13192 radio chip states and the internal registers. In formance check before you are done. handles most of the chores involved this mode, the on-chip oscillator is But the biggest reason I did not use with sending and receiving a data disabled until an interrupt occurs. Pos- ZigBee is that Freescale did not offer a packet, including appending a 16-bit sible sources are the RS-232, the radio, stack until recently. CRC to the data on transmit and or an internal RC oscillator (approxi- Freescale originally distributed the checking the CRC on receive. Unfor- mately 1 kHz). The datasheet Figure 8 Wireless ZigBee stack, but tunately, this means that it will describes what happens to the various Figure 8 Wireless was purchased by a receive virtually any 802.15.4 packet, stop modes when the BDM is in use. competitor in 2005. This motivated regardless of the source. The Freescale It implies that the oscillator would the development of their own ZigBee simple MAC stack adds a 16-bit frame run in STOP3 with the BDM debugger stack, the initial release of which was control to the packet corresponding to connected. I struggled with this for scheduled for mid-2006. After some a ZigBee frame control. It sets this quite a few hours until I came across a development and conformance testing word to 0x7eff, which identifies the comment in the Freescale PWRLIB delays, it was released last February. message as not part of the ZigBee pro- code, which stated that the oscillator When I wrote this article, Freescale tocol. I added two pattern bytes to the will not run if the BDM is in use. In had a collection of examples that ran beginning of my thermostat data pack- the file thermostat.h, I added a user with its 802.15.4 simple MAC et, and an 8-bit checksum to the end to constant that can cause a WAIT instruc- (SMAC). The downloadable BeeKit is a further identify the message. The tion to replace the STOP, enabling the development environment that helps receive routine checks for these debugger to be used without waiting you get started, guides you through before setting a flag (g8ValidMessage) forever for the timer interrupt. some configuration issues, and exports to indicate that a valid message is With the microprocessor in STOP3 the result as a CodeWarrior project. ready to be processed. mode most of the time, the idle cur- CodeWarrior is Freescale’s powerful With 802.15.4, there are 16 possible rent was 140 μA. Changing the port IDE that is shared across different channels in the 2.4-GHz band. The pin initialization to the recommended microprocessor product lines. If you frequency range partly overlaps the range used by Wi-Fi devices. Because I use wireless Ethernet, I chose channel 25, which seemed the least likely channel to interfere. The Panasonic module uses an MC9S08GT60 WWW.GiURUMELE.Hi2.ROand an MC13192. Both chips have multiple features that con- tribute to the power consumption. The first step in saving power is to turn off the radio by asserting the *RESET input to the radio chip. This will require a complete radio reinitial- ization before any data can be trans- mitted. The microprocessor has three power-saving modes. I selected Photo 5—Time spent reading data from the thermostat averages 174 ms. The large spike is the radio transmit and STOP3, which preserves the output receive with a visible discontinuity during the transition.

22 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710017 uchitil-test.qxp 9/4/2007 11:50 AM Page 23

don’t have CodeWarrior, there are sev- eral free versions available with a lim- ited code size or file count. A 30-day unlimited (any size, any file count) license is also available from your local Freescale representative. If you have not used CodeWarrior, note that it has its own paradigm for develop- ment. You may need a license exten- sion (as I did) while you become famil- iar with it. When the new Freescale software was released, I had just completed the software development for this project. I immediately tried to port it to their Photo 6—This is the transmit, receive, and transmit-ACK sequence. The normal 6-ms listen time (second pulse) is newest code base. Several of the appli- noticeably shortened by the arrival of a message. The Fan-On message used here did not require communication with the Lux thermostat before the ACK (narrow pulse at the end) was sent. cation interfaces had changed, mainly for the better. It took about a week of spare time to revise the application. stat. Thermostat code wakes up sixteenth minute. For the time of The most noticeable improvement once per minute and reads some day, I added some additional check- was in the transmit enable. The origi- data from the TX9000. Not all of the ing. When the minute wraps, it nal API merely started a transmission, data needs to be read once per always reads the hour, and when the and my application had to keep check- minute (i.e., the clock hours and fil- hour wraps, it reads the day of the ing for it to complete. Since my appli- ter usage). Because battery consump- week. cation was in a low-power WAIT until tion is dependent on how long the The thermostat accumulates total a time tick happened, the transmitter microprocessor is awake, I added a energy usage for heating and cooling was enabled for longer than necessary. priority table for the data, so values separately, and it keeps the previous For my two messages, I measured may be read every fourth, eighth, or day’s totals. Immediately after mid- close to 1 ms of additional enable time. The new API does not return until the transmission is complete, and the time corresponds very closely to the theoretical transmit time.

SNIFFING OUT A PROBLEM It is nearly impossible to trou- bleshoot a new wireless network with- out some kind of sniffer tool. The moment you start modifying a demo application, you lose track of which end of the network has the new code bug. Did I break the receive code or is something preventing the transmit? Freescale includes the very power- ful Daintree Networks ZigBee sniffer tool with their high-end ZigBee development kit, but the kit costs more than $1,000.WWW.GiURUMELE.Hi2.RO The tool is also available directly from Daintree Net- works. I bought a ZENA ZigBee snif- fer from Microchip Technology for $130. Although it is not as fancy as some, it was an invaluable trou- bleshooting tool.

THE SOFTWARE The CodeWarrior project has two targets, the master and the thermo-

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 23 2710017 uchitil-test.qxp 9/4/2007 11:50 AM Page 24

POL DC-DC Converters Compact and Programmable

AMPL-UZ series offers: • Input voltages of 5V and 12V • Output voltages range of 0.75V to 5V • High efficiency rate of up 97%

Over 3,400 searchable Aimtec products available at DComponents (802) 752-4321 Photo 7—In this message capture, the timestamp shows that the thermostat is set to transmit about every 28 s. The short message is where I set the temperature to hold at 77°, and an immediate ACK followed. My non-ZigBee packets are marked as “Invalid Data” by the ZENA tool. The ZENA also has a graphical display mode for Zig- DComponents.com Bee networks. night, it reads the totals from yester- there is time for additional commands day and today so they are current. to be sent. There is no “clear filter Circuit Cellar reader survey winners! After the data is updated, a 43-byte usage” command because only you Grand Prize — John Hopprich structure is transmitted with the lat- can physically change the filter. So, at est data. The code waits for the trans- the same time, you can clear the CD-ROM archives mission to complete and begins listen- counter with the thermostat buttons. Tom Feliz • Elpidio Eugeni Ian Forse • Robert Hoffman ing for a response. I was able to see The master listens continuously and Richard Gabric typical response times of 2.5 ms, so I prints a period once per second. When limited the listen window to 6 ms. If a a thermostat message comes in, the www.circuitcellar.com/survey2007 valid packet with recognized data is data is displayed in hex and decimal, received, it is and the SHT11 data is displayed in processed and an floating point (see Photo 8). I had ACK or NAK is some trouble getting the floating-point transmitted (see display to work, so I ended up writing Photo 7). a function to pull off the integer part, A total of 10 print it, and then scale the fractional commands are part and print it. It is not pretty, but it supported (see is good enough for debugging. Table 1). One com- When I started capturing current- mand temporarily consumption data, the time spent sets the listen reading data was far longer than I had window size so expected. To better quantify this, I

Thermostat master control commands Command Data Description Ann nn in decimal is address of the target unit Locally set, no data sent Tnn nn in decimal 50–85, 0 = disable Temperature hold Dnn nn range 0–6, 0 = Monday Day of the week WWW.GiURUMELE.Hi2.ROHnn nn range 0–24 in BCD format hours Hours Mnn nn range 0–59 in BCD format minutes Minutes Snn where nn × 10 = hours in BCD format Set filter limit Unn nn = 0 × 57 Unlock writes Lnn nn = 0 × 56 Lock writes Fnn nn = 0 for off, nonzero for on Fan control Xnn nn is in decimal ms Extend listen window

Table 1—The console interface supports 10 user commands. The master software rec- ognizes one character followed by a two-digit decimal number. The thermostat expects BCD data for time values, so H24 (CR), which has a number byte 0x18 (24 decimal), would be interpreted as 1,800 h, or 6 P.M.

CIRCUIT CELLAR® 24 Issue 207 October 2007 www.circuitcellar.com 2710017 uchitil-test.qxp 9/4/2007 11:50 AM Page 25

to degrees by the print routine. Data the University of Wisconsin, Milwaukee. from the SHT11 is in IEEE floating point. He is a senior design engineer at Real The filter usage is in four-digit BCD (0 to Time Automation in Wauwatosa, 1,999 h) so it is printed as 2 hex bytes. Wisconsin. Bitwise data is printed in hexadecimal and the thermostat has its own propri- PROJECT FILES etary bit definitions. The definitions are To download code, go to ftp://ftp.circuit included with the source code. cellar.com/pub/Circuit_Cellar/2007/207.

Photo 8—The packet sent by the thermostat contains ROOM FOR IMPROVEMENT SOURCES all the data of interest. For each message received, the My original goal was to be able to BeeKit wireless toolkit and radio provides a quality (signal strength) byte printed at remotely read the temperature and force a the beginning of the message. MC13191/92 starter kit setback. The wireless modules simplified Freescale Semiconductor, Inc. used the internal interrupt timer to the hardware so much that the final www.freescale.com measure the number of milliseconds result accomplishes far more. Never- TX9000LC and TX9000RF Program- spent reading data, which has a direct theless, I can envision several possible mable thermostats effect on power consumption. In enhancements: reading and writing the Lux Products Corp. Photo 8 you can see the Busy value current programming schedule, graphical- www.luxproducts.com displayed at the end of the message. ly editing it on a PC, and, of course, The master will queue one command taking care of that detail of a settable ZENA ZigBee sniffer from the console. You can enter some- unit number stored in flash memory. The Microchip Technology, Inc. www.microchip.com thing like “T77 (CR)” and it will send real fun will be using the thermostats in the message out the next time it hears an energy management system and set- PAN802154HAR00 LR-WPAN Module from the thermostat. The currently ting up a web page to display the status. Panasonic selected unit number will be used. But that is a topic for another time. I www.panasonic.com Temperatures inside the thermostat SHT11 Digital sensor are stored and provide 0.25° precision: Darryl Uchitil ([email protected]) Sensirion, Inc. (temperature – 32) × 4. This is converted has an M.S. in Computer Science from www.sensirion.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 25 2710015 black.qxp 9/4/2007 3:57 PM Page 26

FEATURE ARTICLE by Thomas Black The Monarch Butterfly Build a Barometric Altimeter

The Monarch is a compact, easy-to-use barometric altimeter. The ATmega169-based system is used for the barometric sensing of air pressure, digital temperature sensing, and RC servo pulse decoding.

Atmel’s Butterfly demonstration it into the Monarch, a grand Butterfly measurements extended to 35 VDC. board is a lot like the colorful gadget indeed (see Photo 1). that hangs in my nephew’s crib. His It all starts with a stock Atmel demo FREE FLIGHT light-, knob-, and sound-equipped toy board. Its affordable street price and The Butterfly is powered by an is actually a teaching tool in disguise. free software tools make the obstacles ATmega169 8-bit microcontroller. It has The Butterfly also has things to see, to joining my little classroom minimal. 16 KB of flash memory, 1 KB of RAM, knobs to push, and noises to make. It So, pick up a demo board from your and an integrated LCD controller, plus a is both entertaining and educational. favorite Atmel distributor and down- host of other features. It has so many If you have not tried Atmel’s $20 load the free software development features that it is best to download the hardware, you are missing out on tools. Then solder-up a bootloader datasheet from the Atmel web site to some fun. Atmel developed the board serial cable and dig into the inner- learn about them all. to demonstrate the features of its workings of Atmel’s resource design. The Butterfly schematics and soft- ATmega169 microcontroller. The little After that, the real fun begins when ware source code can be found on the gadget has a three-axis joystick switch, you morph your Butterfly into an Atmel web site too. You will also a light sensor, a piezo annunciator, and impressive Monarch. The Monarch is a need to download AVR Studio, the a large LCD. Its CR2450 3-V coin cell plug-in daughter board that extends the IDE that is used to edit, compile, and can power it for months. In addition, it demo board’s functions. You are going debug your software. It’s free, so put is preloaded with entertaining soft- to add several new features: barometric away the credit card. However, in case ware. For the diehard geek, it can be sensing of air pressure, 10- to 110-mbar your junk box is empty, plan on pur- used as a scrolling digital name badge. absolute range, a barometric altimeter, chasing a DE-9 serial connector and You can also use its built-in music gen- 1-m resolution (greater than 16 km some wire. You will need it to make a erator to annoy coworkers. Its various max), digital temperature sensing, serial cable to upload new firmware. tricks can be chosen with the joystick. radio-controlled servo pulse decod- Beyond that, there is nothing to buy But once the wonder of it all wears ing, software-controlled on/off out- to create custom Butterfly software. off, the gloves come off. That’s when put for flexible switching of external During my early efforts to modify it’s time to write custom code to devices, external battery operation the published source code, I quickly make it do useful things, which is (support for up to two power sources), flew into a wall. The Butterfly demo where you are headed. New code can low-battery detection, and voltage application was written for an IAR Sys- be uploaded through its RS-232 port or tems C compiler, a not-so-free commer- JTAG interface.WWW.GiURUMELE.Hi2.RO cial product. IAR offers a free evalua- There is something for everyone in tion version, but its 4-KB code limit this little package. The Butterfly board won’t compile the Butterfly’s larger has found life in a variety of hobby code size. Because one of my goals was projects. It has also been used to teach to minimize cost, I ported the software students about microcontrollers and over to the WinAVR GCC compiler. It programming. That is where my proj- is an open-source collaboration that is ect comes in. In this article, I will available as a free download. Best of show you how to transform the board all, it is compatible with AVR Studio into a more advanced teaching tool. Photo 1—This is no ordinary Atmel Butterfly. It’s flying and works seamlessly with it. Hang on tight, and get ready to morph at 633′! My early attempts to compile with

26 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710015 black.qxp 9/4/2007 3:57 PM Page 27

Atmel’s AVR JTAGICE mkII emu- lator. The $300 tool is USB- and RS-232-compatible. It can also be used to debug several other mem- bers of the ATmega and ATtiny microcontroller family, which helps justify the added expense. Instead of using the JTAGICE mkII, I purchased a $50 hobby-style AVR in-circuit emulator with a USB interface. It was a Bulgarian-manu- factured JTAG dongle that claimed to be compatible with AVR Studio. The low cost met my need to keep expenses within a student’s budget. (Students are a likely audience for the Monarch.) The purchased JTAG system includes written instructions. Rather than include a disk with the required software, they direct you to download the USB driver from a web site. Don’t forget to install it. I found that my budget-priced emulator was not recognized by AVR Studio, so I went online to Figure 1—The Monarch expansion board is very simple indeed. You need to add only a few components to create your special project. find a solution. I came up empty handed. Eventually, I took the the WinAVR IDE resulted in an endless you should be able to use the new (and emulator apart and saw that it had stream of warnings and errors. Because old) routines in your own customized optoisolators on the JTAG signals. That this was my first encounter with the software application. So, study the meant they needed external power. The GCC compiler, I stumbled a bit as I source code before flying off into a solution was to route the Monarch’s adapted the Butterfly source code to it. code writing frenzy. voltage-regulated power to pin 7 on the Then, I discovered Martin Thomas’s J402 JTAG I/O port. The coin cell was excellent web site (www.siwawi.arubi. FLASH LIGHT removed to prevent the JTAG’s current uni-kl.de/avr_projects/#bf_app). Lucky Loading hex files into the ATmega169’s draw from quickly draining it. Success! for me, he had already ported the But- flash memory is easily accomplished With power available to the emulator, terfly project to the GCC syntax. I was with the Butterfly’s bootloader feature. its LED lit up and AVR Studio recog- able to resolve all the loose ends in To simplify the task, AVR Studio has a nized the hardware. Oddly enough, the the converted code. I ended up with a utility in its tools menu that is called instructions specifically claim that combination of my port efforts and “AVR Prog.” All it takes is a do-it- external power is not required. his. With the Butterfly demo code yourself serial cable, which is certain- working with AVR Studio and ly light on the wallet. HARDWARE WinAVR, I was ready to integrate my Bootloader flashing begins by pressing There are few spare I/O lines on the hardware to it. down on the joystick’s Enter button Butterfly board (see Figure 1). Unfortu- To make room for the new software while applying battery power. Or, you nately, its existing hardware features features, I removed the existing test, can press the Enter button during a CPU have used most of them up. I was VCARD, EEPROM,WWW.GiURUMELE.Hi2.RO and sound modules. reset. Continue holding the Enter button tempted to add an I/O expander cir- This partial clean slate opened up plenty as you select AVR Prog from the IDE’s cuit, but I finally settled on a design of code space for me to get down to menu. If the programming dialog box that did without one. I also found that business. In case you need them, the appears, you have established serial com- all of the A/D pins were taken. It was discarded files can be obtained from munication and you can release the joy- a slight detour since I planned on the original Butterfly distribution. stick. From here you can select the using one of them for the Monarch’s The new code is intended to be a hex file to load and program it. analog pressure sensor. Not to worry. well-grounded starting point. It Although it’s not necessary, serious A pressure sensor with a digital inter- enables you to evaluate the Monarch’s code writing will be more enjoyable if face was used instead. I’ll write more appended hardware features. Once you you can watch variables and trace exe- about the sensor later (see Figure 2). are comfortable with how they work, cution. But, for that, you must purchase One significant design goal was to

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 27 2710015 black.qxp 9/4/2007 3:57 PM Page 28

minimize modifications to the Butter- PB1-PB3 MS5534B fly board. I wanted to be able to pain- Barometric S1 lessly convert it back to stock form. PB5 sensor CPU Reset 32-kHz Clock The solution was a small daughter RST J403 J400 J2 RC Servo board that plugs into the Butterfly. AVR Butterfly 1 signal demonstration board R/C Signal The only modifications to the Butter- GND PE4 2 +4.8 VDC input fly are some sockets that were sol- 3 GND J3 dered to its prototyping header pads. R4 VMON-IN 1 J407 50 VDC The Monarch board has mating pins 2 On/off output maximum R5 and everything literally snaps together. optocupler U3 In practice, it takes only a few PE5 1 J4 GND 3 moments to morph the Butterfly into a 1 On/off 2 4 2 output super-fly Monarch (see Photos 2 and 3). GND J401 J405 J403 OPTO GND BAROMETRIC SENSOR VCC-EXT PWR FAIL* The barometric pressure sensor is an VCC-EXT PE6 LP2951-3.3 Intersema Sensoric MS5534B. It costs Linear VREG VBAT1+ with power J1 about as much as an analog sensor. The fail detection VBAT2+ 1 Optional power IC is available in the U.S. from Ser- source (Backup) 2 voflo. Builders from other countries HDR2P should check the Intersema web site GND for their local distributor. Figure 2—The four smaller functional blocks represent the new additions to Atmel’s Butterfly demo board. When you purchase the sensor, be sure to obtain the “B” part. It is an custom PCB for the Monarch. I was a install than many other SMD devices I improved version over the older bit apprehensive about soldering the have used. Use caution. The task is MS5534A, which requires different sensor because the manufacturer’s best suited to a soldering expert who calibration software. It is only avail- reflow instructions were a bit daunt- has a decent SMD soldering iron. able in an SMD package, so I created a ing. But, it was no more difficult to The MS5534B is an interesting part. Inside the SMD-packaged IC is a micro- machined sensor, a 15-bit ADC, calibra- tion ROM, and a three-wire communica- tion interface. It is a 3-V part that draws very few microamps, which makes it a perfect choice for use with the Butter- fly demo board (see Figure 3). The MS5534B is not without some odd quirks. For one, the host must provide a 32-kHz conversion clock, which must be a square wave with near perfect symmetry. My solution was to hijack the signal that drives the piezo speaker. The clock signal is complements of the hardware PWM feature of the ATmega169. Although you cannot hear it, the speaker is driv- en with the 32 kHz, too. I suspect that the silent ultrasonic screams have WWW.GiURUMELE.Hi2.ROruined the life of a few mosquitoes. The three-wire interface is nearly SPI, but not quite. The problem is that the MS5534B commands are 12 bits, and the Atmega169’s SPI sends 8 bits at a time. The solution takes just a small bit of data trickery. In essence, the MS5534B command frame must be divided in two. Then, some zeros must be placed before and after the split data to form two complete bytes.

28 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710015 black.qxp 9/4/2007 3:57 PM Page 29

This also requires flipping the SPI Photo 2—The Butterfly is on the left. (Please note the sock- clock polarity midstream. Refer to ets at J400, J401, J403, J405, Intersema Sensoric’s application note and J407.) The Monarch is on AN510, “Using SPI Protocol with the right. (The bottom side has Pressure Sensor Modules,” for more mating pins.) information. Another obstacle to overcome was that the MS5534B’s data output was not tristated when it was idle. This problem driving the data signal rail to pass filter works well since the noise was a problem because the rail, even with the resistor in place. content is Gaussian. In fact, if exten- ATmega169’s SPI bus is shared with Unlike many of the popular pressure sive averaging and filtering were used, the Butterfly’s DataFlash memory sensors, the native data from the the practical resolution could be sub- chip. The pressure sensor’s application MS5534B is not temperature compensat- stantially extended for high-perform- note shows how to add a tristated ed, nor is it fully calibrated. To correct ance applications. Keep in mind that gate, but I did not have a spare I/O to the data, six data words are read from with the part’s 35-ms acquisition control it. After some pondering, a the sensor’s factory calibration ROM at time, there is a time burden to using cheap and dirty solution emerged. boot time. Because sensor temperature additional averaging. I was happy with Resistor R9 is the trickery behind has a huge effect on data accuracy, an 1-m resolution at a 4-Hz update rate, the SPI wizard’s curtain. It prevents internal temperature reference sensor is which did not require much filtering. the MS5534B from loading the SPI involved too. Using the algorithm from Converting air pressure to altitude data line during DataFlash access the datasheet, the factory calibration is often done with floating-point because the idle state for the constants are used to correct the raw math. Here again, the application MS5534B’s data out is logic high. For- pressure and temperature data. The notes were very useful. Instead of tunately, the DataFlash data output corrected data is then used to calculate floating-point, a clever 16-bit integer can sink well over 1 mA, so the resis- accurate pressures and temperatures. table-based scheme was used where tor acts like a weak pull-up. When the To improve pressure-data stability, a linear approximations were made from DataFlash is not in use, it tristates its software-based low-pass filter is used segments within pressure ranges. The data output. The MS5534B has no to average the pressure data. The low- result is very efficient code space with

SOFTWARE • Snap-in 50pin module • Bootloader and Tools • 32-bit 240MHz ColdFire Processor • Codec ,VoCoders and Audio Subsystem • DDR-SDRAM and NOR Flash • Nano-X LCD GUI Software • Ethernet, Serial, QSPI, I2C, USB Host • Open Source uClinux OS and Tools • LCD (up to SVGA) MODULE • Feature Rich SIP Media Middleware • Extended Temp (-40 to +85) • Full Management Middleware System • RoHS, FCC, UL

BUILDING SYSTEMS - PUSH-TO-CALL - ELEVATORS - SECURITY - HEALTH CARE - SERVICE KIOSKS - INTERCOM - DOOR ENTRY SYSTEMS

OEM PRICING EMBEDDEDEMBEDDED STARTS AT

$99$99ea VVOICEOICE 1Kpc QTY WWW.GiURUMELE.Hi2.ROCOMMERCIAL AND INDUSTRIAL VOIP APPLICATIONS

• Ready-To-Use Out of the Box • Software BSP (download) KIT • No Upfront NRE • Voice Module, Host Board • Broadly Compatible • LCD to VGA converter • Complete System Solution • Headset, Cables, Power Supply SYSTEM • Documentation

TEL +1.866.733.8647 FAX +1.416.621.0190 www.ArcturusNetworks.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 29 2710015 black.qxp 9/4/2007 3:57 PM Page 30

small amount, will translate to large SERVO SIGNAL SILLINESS pressure changes. For the best per- The Monarch board has a hardware formance, the board should be rigidly port (J2) that can decode radio-controlled mounted in a case. (RC) hobby servo signals. When plugged into an RC receiver, it can measure a ZEROING FEATURE servo signal with 50-μs resolution. Some Before I go much further, note that it of you will think that I was deranged is not possible to measure absolute alti- to add such a silly feature. However, tude from barometric sensors because model RC systems are used in a vari- Photo 3—The Monarch is plugged into the Butterfly. Other air pressure is constantly changing due ety of interesting applications, includ- than some row sockets, the Butterfly board is not altered. to atmospheric conditions. Air pres- ing robotics and animatronics. sure is like a wave that rises and falls. To help understand what is neces- reasonable accuracy and resolution. The pressure movement is the basis of sary to decode a servo pulse, you need Refer to Intersema Sensoric’s applica- simple weather forecasting. to know how the signal is encoded. tion note AN501, “Using MS5534 for To help make useful above ground Four decades ago, the interface Altimeters and Barometers,” for more level (AGL) altitude measurements, evolved into a simple three-wire affair: information. the Monarch has a zeroing feature. signal, power, and ground. The signal One thing to pay attention to is the Pressing the joystick’s Enter button is a simple digital pulse with a logic-low sensor’s light sensitivity. A cover must zeroes the altitude. Now any changes idle state. Approximately every 20 ms it be made to shield the open end from in height are readily apparent. Howev- produces a logic-high pulse. The width any stray rays. Omitting this will er, due to the nature of air pressure, of the repeating pulse is what gets the cause a lot of grief. Even though I the altitude values will move around, attention of the servo. placed a piece of thin yellow electrical even when standing still. Some of this Modern hobby servos define the tape on mine, it still experiences a error is due to mechanical movement center position as a 1.5-ms pulse data shift in bright light. There’s no of the sensor, some is due to changes width (see Figure 4). Full servo rota- need to go overboard, but choose your in air pressure, and some is the result tion to one side would require the light-blocking cover wisely. of system noise. So, it is not unusual pulse width to be reduced to 1 ms. Also, circuit-board flexing, even a to need to rezero throughout the day. Full rotation to the other side would require the pulse width to increase to 2 ms. Any pulse-width value between 1 and 2 ms creates a proportional servo position within the two extremes. Pulses outside the range are allowed to some degree, but they can cause servo damage if they go too far. A typical three-wire servo cable that plugs directly into nearly any of the pop- ular RC model receivers is soldered to the Monarch’s J2 port. Besides carrying the pulse-width modulated servo signal, the cable also provides power to the board. The actual servo signal is buffered by transistor Q1 before it is applied to the microcontroller. The software decoder uses the pin-change interrupt feature and Timer0 to measure the pulse value. The result is placed in gPulse, a WWW.GiURUMELE.Hi2.ROglobal variable. Comparing it to a thresh- old value will enable you to define your on/off servo pulse states. The demo soft- ware does this to control a couple of fea- tures, which I will describe in a moment. As you can see, the Monarch can measure a typical RC servo signal. This can be conveniently used in cus- tom applications to remotely activate your software features. Perhaps my madness is starting to make sense to

30 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 3.qxp 5/31/2007 9:17 AM Page 1

WWW.GiURUMELE.Hi2.RO 2710015 black.qxp 9/4/2007 3:57 PM Page 32

demo software, if the applied servo the callback functions (no longer used).

15-bit pulse is greater than 1.6 ms, the out- The menu system includes some ADC put will turn on. A software hysteresis changes and new additions. The Altitude feature requires that the servo signal entry displays barometric altitude. The ROM

Communication be less than 1.5 ms to turn off the out- up/down joystick toggles the units put. This feature is disabled if external between meters and feet. Pressing Enter Figure 3—The MS5534 pressure sensor wraps all of its power is missing. That is because the zeroes out the display for useful AGL analog functions in a convenient digital interface. (Source: Intersema Sensoric, www.intersema.ch/site/technical/files/ photocouplers’s LED current would measurements. Altitude is available ms5534b.pdf.) quickly drain the coin cell. when external power is available (dis- abled if running on a coin cell). There is you? Even in my deranged state, it’s SOFTWARE no significant change to the Time entry, clear to me that converting the Butter- The best way to get to know the soft- but the colon now blinks. There is no fly into a practical RC gadget just got ware functions is to first use the change to the Temperature option. The a little bit easier. Monarch demo software. Once you expe- Voltage entry operates the same as rience what the canned examples can do, before, but now voltages up to 35 SWITCH HITTER you will be better prepared to study the VDC continuous (50 VDC short term) In addition to the RC servo decoder, source code (see Figures 5a and 5b). can be measured. The data format there is an optically isolated output The io_functions.c module includes C includes a crude period rather than a for switching externally connected functions for the low-battery detection, “V” to denote the decimal position. devices. The actual output switch is a RC servo pulse decoding, and optically There is no change to the Light option, four-pin photocoupler IC that handles isolated switch output. The ms5534.c except the measurement is now labeled loads up to 80 VDC at 50 mA. It can module includes C functions for the “PC” (photocell). The Servo Pulse entry directly drive low-current loads and it Intersema MS5534B digital pressure sen- displays the pulse value from a standard is easily interfaced with external com- sor. The timer0.c module includes C RC servo-pulse source. Displayed reso- ponents for high-current applications. functions for Timer0, which is used to lution is approximately 50 μs, with an The switched output is useful in a help decode the RC pulse. This file is allowed range of 0.75 to 2.25 ms. Values variety of applications, including those not to be confused with the original outside this range will be displayed as that use an RC servo signal. In the timer0.c, which was used to support “BAD.” The MS5534 sensor displays sensor-provided air pressure and temper- ature data. The up/down joystick toggles between the two. The pressure is dis- played in millibars. In Temperature mode, pressing left/right on the joy- stick will toggle degrees Celsius and degrees Fahrenheit. This feature is avail- able when external power is available (disabled if running on a coin cell). The Options entry remains the same. In addition to the menu changes, there are two new LCD icons: the power loss icon and the servo signal icon. If the coin cell is installed and external power is missing or too low, the “1” icon (upper-left corner) will blink. It is not seen when external power is fine and the servo signal icon. If the applied RRC servo pulse is greater than 1.6 ms, WWW.GiURUMELE.Hi2.ROthen the “5” icon (upper-right corner) will be seen. It will blink if external power is missing. A software hysteresis feature requires that the servo signal be less than 1.5 ms to turn off the icon.

SOFTWARE INSTALLATION To install the Monarch software, you can use the serial port-based boot- loader or the JTAG method. Most of you will probably use the bootloader

32 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710015 black.qxp 9/4/2007 3:57 PM Page 33

because it is free. For additional con- measure air pressure, temperature, alti- 20 ms venience, the Monarch includes a tude, RC signals, and voltages. The sys- A Reset button, which is a nice way to tem also has a software-controlled out- initiate the Bootloader. put switch. Because I’m an RC model- If you use the JTAG method, be aware er, I can create some custom code to 1.5 ms that the Bootloader code is not present record how high I’ve flown. I can even B in the Monarch software. It will be lost configure the RC decoder to remotely during the JTAG flashing. So, restoring trigger a digital camera shutter at a par- Figure 4—Classic RC servo timing is shown here. The 1.5-ms timing represents a “centered” servo position. it will require the JTAG-based reloading ticular altitude. These lofty ideas are of the Butterfly’s software. A copy of the easily achieved with the provided rou- Butterfly hex file that includes the Boot- tines mixed with your custom code. that records daily barometric and tem- loader is on Atmel’s web site. Using the Monarch’s features, you perature data. Along with storing the The Monarch’s compiled demo soft- can just as easily build a weather station data in the EEPROM, the LCD can dis- ware is distributed as a common hex file and, as mentioned, the AVR Studio IDE is used to load it. For example, for serial flashing, just use the “AVR Prog” menu selection and load monarch_gcc.hex. JTAG programming uses the “Program AVR” menu choice. If your JTAG inter- face requires external power, install the Monarch’s JP1 jumper.

SYSTEM POWER The coin-cell battery is not needed because system power is applied through the Monarch’s external battery inputs. The coin cell can be used for back-up power in the event of external power loss. However, the barometric sensor and switched output related fea- tures are disabled when this occurs. External power can be connected to VBAT1 or VBAT2. Any voltage between 4.5 and 12 VDC will do just fine. My preference is a four-cell NiCd battery, but almost any stable power source can be used. Don’t forget to connect your power source while flashing new firmware. If the coin cell is installed, it should be removed soon after the external power is turned off. This will prevent unwanted battery discharge.

HOW HIGH DOES IT FLY? The Monarch is a practical and fun learning tool. UsingWWW.GiURUMELE.Hi2.RO the simple tech- niques I’ve described in this article, you can expand your own microcontroller- based system. And because the software was written in C, you can use the Mon- arch and high-level language techniques that run on resource-constrained micro- controllers. But, once you have your C legs, what do you do next? Let’s see. You have a compact, battery-powered platform that has data storage and can

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 33 2710015 black.qxp 9/4/2007 3:57 PM Page 34

Thomas Black manages a technology a) b) Monarch Revision firm that develops communication Press Up/Down to toggle units. equipment. He has almost two Press Enter to Options Display Adjust contrast Altitude Feet/meters zero AGL. decades of experience working in Jump to Bootloader manufacturing and test engineering bootloader Adjust clock Time Clock positions. Thomas also spent several Power Save Press Enter mode to sleep years as an executive manager in the Date Adjust date Auto power medical electronics industry. In his Analog 5 to 90 min., Off save temperature 29°C/84°F Press Up/Down to free time, he enjoys flying RC model air- toggle units. craft and packing them with interesting Voltage 23.5 V video- and telemetry-related electronic gadgets. Of course, his family and Light PC322AH (photocell) friends rarely understand why anyone Figure 5a—Those familiar with the Butterfly’s would want to do such a thing. You 1.55 ms Servo pulse original demonstration menus should recognize can reach him at [email protected]. a few new features. b—The menu functions are MS5534 920.1P the same as those in the factory release. Keep- sensor ing most of my original menu features was one Press Left/Right 84°F/29°C to toggle units. of the goals for this project. PROJECT FILES To download code, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2007/207. play a weather forecast. You can also The only limitations are your pro- alter it to trigger an alarm if a voltage gramming abilities. drops too low or the temperature gets So, who said you can’t teach an old RESOURCES too hot. You can even create an appli- lepidoptera new tricks? This one cer- Atmel Corp., “AVR Butterfly Quick cation for a balloon that records tainly has flown to the top of its class, Start User’s Guide,” 4249A, 2003, atmospheric temperature and altitude. as well as morphed into a brilliant www.atmel.com/dyn/resources/prod_ It could drop a payload when it reach- Monarch. Hopefully this little fellow can documents/doc4249.pdf. es the target height. The list goes on. help you learn a few new tricks too. I Intersema Sensoric, “AN501: Using MS5534 for Altimeters and Barometers,” www.intersema.com/site/technical/files/ an501.pdf.

———, “AN510: Using SPI Protocol with Pressure Sensor Modules,” www.intersema.com/site/technical/ files/an510.pdf.

M. Thomas, “AVR-Projects,” Technical University of Kaiserslautern, 2007, www.siwawi.arubi.uni-kl.de/avr_projects.

SOURCES ATmega169 Microcontroller, AVR JTAGICE mkII emulator, and AVR studio IDE Atmel Corp. WWW.GiURUMELE.Hi2.ROwww.atmel.com MS5534B Pressure sensor Intersema Sensoric www.intersema.ch AVR JTAG USB Emulator Olimex www.olimex.com GCC Compiler WinAVR http://winavr.sourceforge.net

34 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710018 Kagan.qxp 9/4/2007 4:04 PM Page 35

FEATURE ARTICLE by Aubrey Kagan Resilience in Embedded Designs (Part 2) RS-485, Voltage Supervisors, Watchdogs, & Outputs

Last month, Aubrey described how you can protect your designs’ inputs so they can endure under the worst conditions. This month, he covers RS-485, resilient outputs, and watchdogs. Keep your designs protected!

Last month, I covered approaches resistors, R5 and R4. As the current board to ensure that there are no other that you can take to protect inputs so increases, the temperature and resist- undesired effects during power up or they survive under difficult condi- ance of the PTCs increase, reducing the power down. tions. This month, I will start with a current even more. There are also A reset generator is often included general RS-422/485 interface because products that include the Zener diodes. with a watchdog (which will be dis- it is practical and it encompasses (Refer to the “RS-485 Protection” sec- cussed later). But whether or not it is many of the protection techniques tion in ResilienceReferences.pdf on the integrated with the watchdog, make that I covered last month. In the gray Circuit Cellar FTP site.) sure the trip voltages match the micro- zone definition of inputs and outputs, If the common-mode range is insuf- computer’s and the other devices in the low-voltage detection and watchdog ficient, there are also extended-range system. I used the word “system” circuitry are vital to the correct opera- devices, which include optical and because you may need to protect tion of outputs. In this article, I will capacitive coupling. devices that are not on the PCB. address this before focusing on Some processors have the reset resilient outputs. VOLTAGE DETECTION & RESET issue mostly resolved, but the detect All electronics, especially micro- signal is internal and it is not avail- RS-422/485 processors, are rated to operate in a able to the outside world. In this case, The RS-422/485 standard allows up specified voltage range. When a volt- it helps to use a microcomputer out- to 12 V and as little as –7-V common- age is below the recommended operat- put that will indicate that a reset has mode voltage difference. It provides ing voltage, the reset of the microcom- been asserted. This depends on what reliable communication by using a dif- puter must be held active so unpre- the reset state is for. The output not ferential method of data transmission dictable actions do not occur. Undesir- only varies between microcomputer and reception. All RS-485 drivers pro- able actions include outputs being types, but also between port types on vide that. However, there are other switched on at random with disas- the microcomputer. Where the port issues involved, such as input/output trous consequences or settings in EEP- reverts to a floating input on reset, use protection, fail-safe operation, and ROM being lost. The RESET signal is an external pull-up resistor together open-loop detection. often fed to additional devices on the with active-low logic (when the soft- Refer to Figure 1 for a general- ware gets to configure the port ized approach. R1 and R3 are as an output) to indicate that the used to define the voltage levels reset has been de-asserted and to the inputs ofWWW.GiURUMELE.Hi2.RO the IC. If no driv- the microcomputer is now run- er is connected to the RS-485 ning. On reset the resistor would bus, the receiver will not see an pull the signal high indicating a erroneous message. This is gener- reset condition. Any other I/O ally described as “fail-safe” in combination should be inspected the literature, and you can find so the microcomputer reset devices with the feature built in. results in a system reset. Voltage levels beyond the com- Resist the temptation to use mon-mode voltage range are a simple, cheap RC circuit sys- clamped by the Zener diodes, and Figure 1—This is an RS-485 protection schematic. The values of fail- tem reset. The slow rise time the current is limited by the PTC safe resistors may need to be recalculated for a particular application. and the unpredictable threshold

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 35 2710018 Kagan.qxp 9/4/2007 4:04 PM Page 36

voltage can lead to problems issue, but the ability to reset with mistimed resets and fail- the display requires hardware ures to reset with transients. interaction and may need a method to remove and reapply WATCHDOG power to the subprocessor if A watchdog is a hardware there is no hardware reset line. timer that generates a physical Be careful. All inputs to the reset to the microcomputer device being powered down when it times out. Correctly should be at 0 V before the sup- operating software refreshes the ply is independently removed. counter periodically to prevent the reset. (This topic is relevant OUTPUTS in both hardware and software. I Figure 2—You can control the supply to the relay, preventing the relays from Just because outputs are will cover the software in Part 3 turning on during a reset. Back EMF from the relays can be suppressed by low-impedance and nominally connecting pin 10 (the common of the internal diodes) to 24 VDC. of this series.) Many microcom- under the control of your puters include onboard watch- electronics doesn’t mean they dogs, but their performances should be ensure that the failure still results when are less prone to problems. As I said in viewed with skepticism. the microcomputer is reset. The prob- the first part of this series, outputs First, they tend to be basic, so the lem with this (and future improve- need to be protected with MOVs and software that “kicks” them cannot be ments that will be discussed) is that TVSs where there are semiconductor- intricate, thereby reducing the confi- the increased confidence is traded for controlled outputs. The only problem is dence level that the watchdog will microcomputer resources and PCB area. that the output is supplying current. “bite” if a failure occurs. Second, the (Refer to the “Simple Watchdog” section Thus, the resistance of a current-limit- watchdog is implemented with the in ResilienceReferences.pdf, which is ing resistor is restricted to lower values. same type of circuitry, and it is on the posted on the Circuit Cellar FTP site.) same piece of silicon as the microcom- The next step up the ladder of confi- FAIL-SAFE puter it is supposed to protect. As a dence is to make sure that the kick An important aspect of resilient result, it is susceptible to the same occurs within certain time con- design is what happens when you are problems that you are trying to detect straints. This helps detect if the not in control of the outputs. That on the microcomputer. They are bet- processor is running too fast or slow, happens every time the power is recy- ter than nothing, but if you really or if it is executing processes out of cled or when the reset is activated want additional confidence you should sequence. Several manufacturers make from a power or watchdog sequence. use an external watchdog. watchdog timers that provide this Every microcomputer has a start-up If you have an external watchdog, “window” feature: Texas Instruments condition on all of its I/O pins forced first make sure that the reset output (TPS3813), Atmel (U5021M), Maxim by the reset pulse. Other electronics in oscillates. In other words, make sure Integrated Products (MAX6324/4), and the design may also have this feature. that it asserts the RESET pin for a EM Microelectronic (the 615x family). Consider the state of each pin after period and then relaxes it to enable George Novacek, who has published reset. If the output is active high and the processor to start up. If a watchdog 29 articles in Circuit Cellar, has sug- on reset, the microcomputer output kick is not received within the defined gested that the ultimate watchdog converts to an input with a nominal watchdog period, the reset is asserted timer is a state machine in which a pull-up resistor. This could be suffi- again, and so on. In a nutshell, you series of codes is fed to the state cient to activate the output with dis- shouldn’t use a monostable to drive machine at predetermined periods. It astrous consequences. You can define the reset input. is very likely that the processor is the active outputs to be the opposite Most discrete watchdogs need two operating correctly because the of the reset condition. Using pull-up definitive actions to kick them. The sequence of operation is monitored and/or pull-down resistors judiciously, “kick” pin must go high and low. If with the correct timing. Unfortunate- you can define that no output is active there is only oneWWW.GiURUMELE.Hi2.RO place in the software ly, such a device does not exist, so you when reset. An alternative is to create where the microcomputer output is will have to design one, possibly com- an “output enable” signal that is dis- set and another where it is cleared, bining it with a “window” watchdog. abled on reset and must be enabled by you have gone up a notch in your con- a definite microcomputer action (or fidence level because you know that at SUBPROCESSORS sequence of actions). That action must least two sections of software are Many designs have subprocessors. not be activated during a reset. being executed. This dovetails with You may even overlook some, like the The concept is shown in Figure 2, the software design. For added confi- one in the ubiquitous character-based where an 8051 processor controls dence you may have to add additional LCD displays. It is possible for the some relays. When a reset occurs, all hardware. It is true that more circuitry processors to suffer soft errors as well. the I/O pins turn to inputs with inter- increases the probability of failure, so Error detection is normally a software nal pull-up resistors, which is the

36 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710018 Kagan.qxp 9/13/2007 10:55 AM Page 37

same as an output with a “1” off. This is shown as the bleed on it. When P1.0 is low, it capacitor in Figure 4d. enables the supply to the relays. A final method of suppress- No matter the state of P1.1 ing arcing (if you are not and P1.2, neither of the relays implementing phase control) is can be activated until P1.0 is to use zero-crossing switching low. This allows for any kind of techniques on TRIACs. output setup and stabilization Because the on and off occur at before the single pin P1.0 is 0 V and 0 A, respectively (a taken low and so the functions Figure 3—Use a monostable to protect output against unexpected micro- TRIAC always turns off at associated with the relays are computer events or failure. zero current), no noise is radi- disabled during this period. ated, or a least that is the the- Consider the cases when the micro- values of the resistor and the capaci- ory. The simplest way to achieve this computer freezes, goes “nuts,” or its tor are a function of the coil’s induc- is with the Fairchild Semiconductor output or the inverter’s output is tance and switching frequency. A MOC3063 TRIAC driver family. stuck high. It is possible to head off Google search will yield several hits these problems by placing a mono- for calculating the values of the resis- SWITCHING TRANSISTORS stable between the inverter and the tor and capacitor. Remember to con- It is often necessary to use discrete STMicroelectronics ULN2803A driver sider the voltage ratings for the resis- transistors as output drivers. It sounds (see Figure 3). tor and the capacitor. trite, I know, but it is a good idea to P1.0 must be toggled faster than the It is good design practice to snub ensure the basics. In the case of bipo- time constant of the RC network in the outputs of a relay if any arcing is lar transistors, is the device being driv- order to keep all of the outputs active. likely to occur. Sometimes the en into saturation? MOSFETs have a This follows the same principle as the snubbed output is used to drive an capacitive input and may turn on or watchdog timer. You can apply all of input on a connected device. For off slowly, which leads to conditions the same arguments to it. You can instance, on most programmable that will burn out some components. also extend the same precautions to logic controllers (PLCs), the generic Sometimes a transistor is used to all of the outputs. You can even use TRIAC outputs are all snubbed with short out a capacitive load. A short the same watchdog ICs. (Refer to the an RC network. The RC network across a capacitor can theoretically “Serial Output” section in presents an AC path and a leakage generate infinite current. In practice, ResilienceReferences.pdf.) current will flow, often enough to however, something will fail before turn on a cascaded input. The nor- that pinnacle, and it is normally the BACK EMF mal protection technique is to add a transistor. A correctly sized current- Any driver that works with an elec- current drain to the input to draw off limiting resistor is a good idea. tromagnetic device (like a relay or sole- enough current so the input remains Also, keep in mind that when using noid) will experience a a Darlington pair of transis- reverse-voltage transient tors, the output voltage a) when de-energizing the load. b) c) goes only to about 1.2 V

This is known as back elec- 24 VDC 24 VDC 24 V AC when it is saturated. This tromotive force (EMF). It can is normally above the value both destroy the electronic of a logic low, so don’t try driver and generate radiated and use this to drive a digi- emissions that are often tal input without adding enough to cause a soft fault some form of signal condi- in a dynamic register or Diode TVS Snubber tioning. memory location. Figure 4 shows a few techniques for d) OFFBOARD SENSORS suppressing theWWW.GiURUMELE.Hi2.RO spike. The 120 V AC There are often offboard diode technique in Figure 4a sensors in a project that PLC output can sometimes be included require some form of power on the silicon as part of a to operate. In the automo- driver IC, such as the tive industry, these are sin- Bleed INPUT ULN2803 (see Figure 3). capacitor to DC circuitry gle-wire signals where the The values of the ratings return ground is derived Leakage immunity of the components must be through the body of the able to withstand the maxi- sensor and ultimately the Figure 4—Here are some back EMF suppression techniques. Note that a, b, and c mum voltages generated. In are for DC, while d is used on AC control. The snubber provides a leakage path, which chassis of the device whose the case of the snubber, the could activate the input. The additional bleed capacitor is used to drain the current. property is being measured.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 37 2710018 Kagan.qxp 9/4/2007 4:04 PM Page 38

Either due to miswiring or a failure operation. If possible, conduct a test at PROJECT FILES when the wire breaks off, the positive elevated temperatures for extended supply can be shorted to ground, result- periods of time to highlight deficien- To download ResilienceReferences.pdf, ing in the tracks being burned right off cies in the design. go to ftp://ftp.circuitcellar.com/pub/ the PCB, which will force you to In addition, it helps to try environ- Circuit_Cellar/2007/207. replace the board in order to repair it. mental influences to observe system You can prevent this by designing in a behavior. Mimic the real operating RESOURCES current-limiting resistor or a fuse. environment for better results. An Freescale Semiconductor, Inc., Good self-resetting options include the ESD tester may be good for regulatory “eXtreme Switch Protection Guide- Tyco Electronics PolySwitch or a PTC approval, but as I said before, it may lines,” Application Note AN3274, resistor. not reflect the real world. I actually 2006. found that an old camera flash gener- READ BACK OUTPUT ated enough of a disturbance to cause J. Ganssle, “Born to Fail,” Embedded When you set an analog or digital the microcomputer’s memory to be Systems Design, December 2002. output, it is prudent to ensure that the scrambled. A very old Intel application action has occurred. Of course, this note described the construction of a ———, “Li’l Bow Wow,” Embedded uses system resources, but you get tester using an automotive coil and a Systems Design, January 2003. additional confidence in the operation of spark plug as a noise source! the system. One approach is to use a It is often beneficial to allow spare J. Goldie, “Failsafe Biasing of Differen- shunt resistor in the current path of the inputs and outputs to help with test- tial Buses,” Application Note 847, load and measure the current passing ing. Although it does nothing to help National Semiconductor Corp., 1992. through it. Some devices, such as the directly with adding resilience, it is ———, “Ten Ways to Bulletproof RS- International Rectifier IR3310, have the easy to monitor the execution of criti- 485 Interfaces,” Application Note circuitry built into the silicon. cal parts of code by setting and clear- 1057, National Semiconductor Corp., Freescale Semicondcutor’s MC33888 ing an output and watching the 1996. and MC33982B take this approach to sequence of events on an oscilloscope. its extreme conclusion with the abili- Add an LED and generate code B. Perrin, “I/O For Embedded Con- ty to detect several different failure sequences to provide clues about the trollers,” Parts 1 & 2, Circuit Cellar modes along with sophisticated on/off system’s status. The eye is amazingly Online 110 and 111, 1999. control. good at detecting anomalies in opera- One technique for expanding a tion even with the simple LED flash. ———, “Pedigree Protection, Watch- microcomputer’s I/O space is to use dog Circuits,” Circuit Cellar Online some form of a serial-to-parallel con- ON TO THE SOFTWARE 108, 1999. verter like an Allegro Microsystems Prudent hardware consideration can A6812. These devices often have a make your product resistant to most R. Valentine, “Protection Techniques serial output so the shifted output can kinds of vagaries in the environment, Ensure μC Reliability in Power-Con- be shifted back into the microcomput- but it needs to be combined with trol Circuits,” EDN, October 10, 1996. er and verified. (Refer to the “Serial some software approaches to ensure Output” section in ResilienceRefer- the most robust design possible. Join SOURCES ences.pdf.) me next month for the third and final It is possible to detect communica- article in this series. I will tackle the A6812 Source drivers tion channel problems while using dif- topic of adding resilience to the Allegro Microsystems, Inc. ferent hardware techniques. I have dis- firmware. I www.allegromicro.com cussed fail-safe circuitry as applied to MOC3063 Optocoupler the RS-485, but this does not give any Aubrey Kagan is a professional engi- Fairchild Semiconductor Corp. indication that there is a problem. It neer with a B.S.E.E. from the Tech- www.fairchildsemi.com may be possibleWWW.GiURUMELE.Hi2.RO to check-in software, nion—Israel Institute of Technology which is easy enough in the case of a and an M.B.A. from the University of MC33888 and MC33982B Switches digital communication protocol where the Witwatersrand. He works at Freescale Semiconductor, Inc. no message has been received for a Emphatec, a Toronto-based design www.freescale.com period. However, in the case of a con- house of industrial control interfaces tinuous current loop or voltage input, and switch-mode power supplies. In IR3310 Power switch hardware may be better than software addition to writing several articles for International Rectifier at detecting that the loop is open. Circuit Cellar and having ideas pub- www.irf.com lished in other periodicals, Aubrey TEST, TEST, & TEST wrote Excel by Example: A Microsoft ULN2803A Darlington array The more you test, the more confi- Excel Cookbook for Electronics Engi- STMicroelectronics dent you’ll become in the system’s neers (Newnes, 2004). www.st.com

38 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 39.qxp 9/11/2007 11:04 AM Page 1

WWW.GiURUMELE.Hi2.RO 2710014 Merk.qxp 9/4/2007 4:06 PM Page 40

FEATURE ARTICLE by Ken Merk Simple Ethernet You can use a picoFlash SBC with an Ethernet controller to send embedded Ethernet packets between master and slave nodes. The easy-to-use system makes writing software and debugging a cinch.

Mention the word “network” to would be used everyday by millions Data can be collected or sent from a someone and the first thing that of people around the world. This single location and boards can be con- comes to their mind is the Internet or workhorse, “the Internet,” is com- figured or programmed remotely. the computer that they use at work, monplace now, and it is accepted into When connected to the Internet, any- which is connected to a host of others. our homes as a necessity like our one can get access, if desired. With Connecting computers together to telephones and TVs. this in mind, I selected an SBC that share information is an efficient way With advances in microcontroller came with an Ethernet interface for to work. Networking is commonplace technology, Ethernet is becoming my project. In this article, I’ll describe in businesses, and it is even finding its embedded. Small and powerful single- my design. way into our homes. Cat-5, RJ-45, board computers (SBCs) are available hubs, routers, and switches are terms with Ethernet interfaces. The boards, PROJECT OVERVIEW that you are familiar with if you use a which can be used as controllers or for My project includes three nodes computer at work. The technology has data acquisition, can be networked that act as slave controllers and a stepped into the wireless world, which together and managed more efficiently. main node, which is the master. gives you even more freedom. Short- range Bluetooth and spread-spectrum wireless LANs give you the portability to move around without the hassle of tangled cords. The idea to network computers orig- inated in the early 1970s when Bob Metcalfe, a researcher for Xerox PARC, introduced us to the Ethernet protocol. He used the packet-based protocol to network a bunch of com- puters so they could interact with each other, share files, and print to the first laser printer, which was invented by Xerox. (It also gave us the mouse and a windows-based GUI.) There was no Internet then, so his simple LAN was a closed networkWWW.GiURUMELE.Hi2.RO without a router or a gateway. At about the same time, Vinton Cerf and Robert Kahn introduced the world to TCP/IP. The protocol, or suite of protocols, would look after routing and provide reliable data deliv- ery. The protocol was developed to create a network of networks. When Photo 1—The four picoFlash boards were networked together with a simple hub. The board on the bottom was config- Ethernet and TCP/IP came together, a ured as the master with the three slaves shown on top. DiskOnChip flash memory drive upgrades can be added to the global network was born, which boards filling the empty DIP sockets. The RS-232 interface cable used during development is on the master board.

40 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710014 Merk.qxp 9/4/2007 4:06 PM Page 41

Ethernet frame

Destination Source Data Data Frame check Preamble Start of frame MAC MAC length 46 min, 1,500 max CRC 7 bytes 1 byte 6 bytes 6 bytes 2 bytes bytes 4 bytes

Packet 1,514 bytes max 60 bytes min

Figure 1—The basic Ethernet datagram will be used to transport your bullet to the target node. Your concern will be with only the packet section because the Ethernet controller chip will take care of the rest. Your bullet will be carried by the data section of the Ethernet frame.

Each node is “smart” and looks after enables you to write code on your PC its own housekeeping, but they (in any language) and then upload it would be networked together. The to the onboard flash memory drive. master can interrogate each node, The board is equipped with a 10Base- download data, or send control func- T Ethernet interface using Realtek tions, if necessary. The slaves don’t Semiconductor’s RTL8019 Ethernet talk until spoken to by the master, controller chip, two serial ports, 16 which eliminates packet collisions. digital I/Os, a clock/calendar, and a The arrangement is so simple that a socket for a DiskOnChip upgrade. TCP/IP stack would be overkill. The software was written in Forth Keeping it simple makes writing language (pico186), which enabled software and debugging easier. me to get the hardware up and run- Because this is a closed network, I ning quickly. Forth words were use pure Ethernet like Bob Metcalfe developed on the SBC and executed did at Xerox. This eliminates the through the serial port using a termi- hassle of configuring IP addresses, nal program running on a PC. Each subnet masks, address resolution pro- Forth word could be run from the tocol (ARP), gateways, and extra soft- command line, which was a great ware to interface with the TCP/IP debugging environment. stack. All four SBC boards were connect- Think of the Internet in the fol- ed to a simple HUB, where one was lowing way. Ethernet is a flatbed assigned to be the master and the truck with a big box on the back other three were slaves (see Photo 1). marked IP. Inside the box is another The slaves would maintain the box labeled TCP. The data that housekeeping at their node and await you’re sending is inside the TCP. The commands from the master con- Ethernet truck is cruising along the troller. For development purposes, all Cat-5 highway driving through gate- I needed were two picoFlash boards ways and routers to its destination. connected together with a yellow In your case, you will take the IP box crossover cable and a computer con- off the truck and place your data nected to each board’s serial port. A directly on the flatbed. The Ethernet terminal program, such as Symantec’s truck will now drive your data to its Procomm running on each computer, destination. EachWWW.GiURUMELE.Hi2.RO SBC has its own enables me to send, receive, and view unique MAC or Ethernet address, packets between the two nodes. which you will use to send data to its destination. Your software will INSIDE ETHERNET PACKETS deal directly with the NE2000 packet Ethernet is a packet protocol, driver installed on the board. which means your data is broken up I used a JKmicrosystems picoFlash into smaller chunks called packets, embedded DOS SBC for the master or datagrams, which are sent to a tar- and slave nodes. The inexpensive, get destination. This gives other powerful board includes a 40-MHz nodes a time slot to send their pack- 80186-compatible processor that ets to their destinations. The flurry

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 41 2710014 Merk.qxp 9/4/2007 4:06 PM Page 42

of data is called net- the packet is your data working. with a maximum of An Ethernet packet 1,500 bytes and a mini- has a maximum length mum of 46 bytes. of 1,514 bytes and a There is a 7-byte pre- minimum of 60 bytes. amble for synchroniza- The first 6 bytes of the tion, a start-of-frame packet are the destina- byte at the beginning of tion MAC address, the the frame, and a 4-byte next 6 bytes are the frame check CRC at the Photo 2—A data dump of two bullets shows how they are constructed. The MAC addresses source MAC address, the end of the frame, which and data count can be seen with the data block following. The first bullet shows the next 2 bytes are the data led.on command. The second bullet shows how the text “Hello World” is sent to the tar- is added automatically. length, and the rest of get’s serial port. Your only concern is to insert the Destination/ Source MAC addresses, data length, and data. The Ethernet controller chip will do the rest (see Figure 1). When an Ethernet frame is sent to a node, the RTL8019 Ethernet con- troller chip checks the CRC for pack- et corruption and compares the desti- nation address to its own address for a match. The controller interrupts the 80186 CPU (INT0), which enables the packet driver to receive the packet through I/O port 300h into a buffer. A flag is set, which indicates that the buffer contains a new packet ready to be used by your application software. To send a pack- et, build up a packet in a buffer and send it through the packet driver using software interrupt 60h. Send and receive packets through the packet driver, which interfaces the controller hardware, to your applica- tion software. All the details needed to build an interface to interact with NE2000-compatible packet drivers are in FTP Software’s PC/TCP packet driver specification (version 1.09). The procedure may seem a bit overwhelming, but read on. You will build a system that will make it easy for you to send and receive packets.

SHOOTING BULLETS WWW.GiURUMELE.Hi2.ROThe data that you will be sending in your packets will be limited to a maximum of 255 bytes. The 255-byte chunk will be called a “bullet.” The bullet will be fired from the master to the slave node. When the slave receives the bullet, it will interpret and execute (run) the contents imme- diately. To see how this works, let’s look at some examples. To build and send a simple bullet,

42 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710014 Merk.qxp 9/4/2007 4:06 PM Page 43

type the following: Listing 1—This is the code for sending and receiving Ethernet bullets. The word Load places the bullet in the data field and the count into the length field. Is.Target fills the destination MAC field. Fire.bullet sends the bullet to its destination. At the receiving end, Parse.bullet pulls the bullet out of the packet. “ Led.on” >send Run.bullet executes the bullet data. The ASCII text string Led.on will be \ Bullet.seq \ Bullet routines for JKmicro PicoFlash SBC put into the data field of your bullet \ KRM because it is inside double quotes and \ ************** Writing Bullets ************** the word >send will shoot the bullet create master $00 C, $A0 C, $24 C, $8B C, $05 C, $47 C, to its destination. The node receiving create node1 $00 C, $90 C, $C2 C, $40 C, $49 C, $54 C, the bullet has a Forth word or subrou- create node2 $00 C, $90 C, $C2 C, $20 C, $24 C, $03 C, tine called Led.on in its dictionary. create node3 $00 C, $90 C, $C2 C, $55 C, $32 C, $22 C, create broadcast $FF C, $FF C, $FF C, $FF C, $FF C, $FF C, When the node receives the bullet, it will execute (run) its contents Led.on : Is.Target \ eg Node1 Is.Target and turn on the LED. (The LED is on xmit.buf 6 cmove ; the picoFlash SBC.) : Shoot.data ( n1 ... ) get.address mac.buf xmit.buf 6 + 6 cmove This is a powerful system because dup flip xmit.buf 12 + ! you can execute small routines or 14 + 60 max 1514 min packet.length ! even large applications by sending one send.packet ; : >send word in your packet. You can build-up tuck xmit.buf 16 + some words on your master to control place 3 + shoot.data ; your slave nodes. First, select your xmit.buf 14 + Constant data.buf \ ************************************* destination node by typing create bullet.buf 255 allot dest_name Is.Target: bullet.buf 255 erase : end bullet.buf count dup 1+ allot ; : bullet place ; : Led-ON " Led.on" >send ; : bullet{ ascii } parse bullet.buf +place ; : Led-OFF " Led.off" >send ; : ,{ ascii } parse tuck here place 1+ allot ; : reset.tib SP0 @ 'TIB ! >in off span off #TIB off ; Typing Led-ON from your master will : system.clear xmit.buf 14 + 2 erase ; turn on the LED on your slave node. : Load \ eg Test.bull Load Typing Led-OFF from your master will system.clear turn off the LED on your slave node. xmit.buf 16 + 256 erase get.address mac.buf xmit.buf 6 + 6 cmove You can turn an LED on and off count xmit.buf 16 + place remotely from the master node, but xmit.buf 16 + C@ 3 + flip how can you interrogate the slave xmit.buf 12 + ! ; : Show.bullet \ Show loaded bullet node to send back an indication of the cr cr xmit.buf xmit.buf 16 + c@ 17 + LED status? On the slave node, write 60 max dump cr ; a Forth word called Led.status:

: Fire.bullet \ Send the loaded bullet Xmit.buf 16 + C@ 17 + : Led.status 60 max packet.length ! Get.Led.status send.packet ; IF " .( Led is ON ) " : Shoot Load Fire.bullet ; ELSE " .( Led is OFF ) " : Parse.bullet rec.buf 16 + ; THEN >send ; : Run.bullet \ Execute (run) bullet rec.buf 12 + @ flip 4 258 Ubetween IF settib run reset.tib Get.Led.status reads the I/O port, ELSE drop which controls the LED. If it is on, it THEN ; will send back the status string Led : Test.bulletWWW.GiURUMELE.Hi2.RO settib run reset.tib ; : Listen is ON or Led is OFF if the port drive time-reset is off. On the master, make a Forth BEGIN word called LED?. sec-elapsed 2 > IF cr ." ** No Response **" cr BREAK Recbuf.busy? @ dup : LED? “ Led.status ” >send Listen ; IF parse.bullet run.bullet false Recbuf.busy? ! When you type LED? from the mas- THEN UNTIL ; ter, Led.status is sent to the slave and executed. It sends back the status \s string, which is then displayed by the word Listen.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 43 2710014 Merk.qxp 9/4/2007 4:06 PM Page 44

Photo 3—To extend my master-to-hub Ethernet segment, I used a pair of SDSL megabit modems. The white cable in the middle represents the 1-mile single-pair copper link. The set-up process is a breeze. Power-up the modems and wait for the SYNC LED to come on solid, which indicates the link is up. The modems will become transparent to the system as packets sent to one modem emerge from the far-end modem.

So, let’s summarize what you’ve done. and then executed. A Forth word, the data field. To use it, you have to Any text put in between double quotes , is created and compiled and Load the bullet: will be placed in the data field of the then is executed. You can packet, and the receiving node will exe- build a similar bullet, but send 80186 Test.bull Load cute the word or words. The word to be assembler code to be compiled and executed must already be compiled in the then executed: Once it is loaded, give it a destination, dictionary of the receiving node. Trying then fire it: to execute a word not onboard will cause “ code ...80186 assembler the watchdog to reset the system. The code...end-code ” >send Node.1 Is.Target Fire.bullet Forth running on the picoFlash SBC has a set of control words ready to be sent by The bullet contains assembler code You can send the same bullet to a dif- the user. Port I/O pins can be turned on between code and end-code, which ferent destination: or off with words like PA.3 HIGH and is compiled and then executed when PB.1 LOW or toggled with the words PD.3 is encountered. You can send Node.2 Is.Target Fire.bullet TOGGLE. Pins acting as inputs can be the code to be compiled in one bullet read with the words PA.0 ON?. and execute it at a later time with You can load a different bullet and Any text surrounded by .( ) will be another bullet containing just . send it to the same target: sent out the serial port on the receiv- With the “power” bullets, keeping ing node. This gives you a path to track of node software is not a con- Test1.bull Load Fire.bullet send text to the RS-232 port on the cern. slave node for display or to send con- So far, you have been building sim- A shortcut will give you the same trol functions to a serial device: ple bullets “on the fly” and embedding results: them into Forth words. Other details : Greeting “ .(Hello World) ” >send ; will be revealed that will show the Test1.bull Shoot full working power of the bullet con- Typing the word Greeting will cause struct. You can create bullets, assign The word Shoot combines Load and the text Hello World to be displayed on them names, and store them for future Fire.bullet into one operation. the receiving node (see Photo 2). use. During the development process, Load and Is.Target are sticky so I have mentioned that any word that you have been sending bullets from they stay the same until changed. is sent in a bullet must already be in the your computer keyboard. With a Using broadcast with the word receiving node’s dictionary in order for it library of bullets stored in the memo- Is.Target will cause the fired bullet to execute. YouWWW.GiURUMELE.Hi2.RO can send a bullet that ry, you can assign them to be sent to be received by all nodes. Execute contains source code that will be com- with the press of a push button for the bullet at the receiving node by piled into the receiving node’s diction- industrial applications, eliminating using the words: ary first and then execute that code: the keyboard in your final product. To create and store a bullet, use the ,{ } Parse.bullet run.bullet “:....Forth Code .... ; construct instead of the double quotes: ” >send This turns on the LED on the target create Test.bull ,{ led.on } board. When you send the bullet, the text If the need arises, you can send a full between the colon and the semicolon Here you have created a bullet called packet of 1,500 bytes to a node. This will be compiled in the receiving node Test.bull with the string led.on in would not be considered a bullet and

44 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710014 Merk.qxp 9/4/2007 4:06 PM Page 45

would not be executed, but it would to 100 m. My hub-to-slave nodes Forth, but you can use any language that be taken in as a datastream and processed meet the 100-m requirement. My is familiar to you. Once a software inter- with the necessary user-supplied code. master node-to-hub segment needs to face is built between the packet driver Just load the data into Data.buf and be about 1 mile in length. The dis- and your application, you can build a then use the word Shoot.data. At the tance exceeds the maximum length similar bullet construct like the one I receiving end, the data will be in a buffer allowed by the Ethernet transport. I described. The bullet structure is basi- called rec.buf, which can be viewed needed a way to extend this Ethernet cally a language in itself, which can be by typing the words show.packet. segment. extended to become your application. There is a communication cable My goal in writing this article was BULLET CODE between my master and hub where I to show you a simple way to send an Listing 1 shows the code needed to can get access to a single-pair copper Ethernet packet in the embedded construct and send bullets. First, line. On one end, I installed an ADC world from point A to point B. It is up assign a name to all your MAC symmetric digital subscriber line (SDSL) to you to use this technique for an addresses that will be used in the net- megabit modem, which gave me a high- application of your own. I work. The name will be used with the speed data connection to send and word Is.Target, which places the receive my Ethernet packets. The actual Ken Merk is an electronics technolo- MAC address into the destination usable distance depends on line-condi- gist with a degree from the British field of the packet buffer. Is.Target tion factors, such as noise, wire gauge, Columbia Institute of Technology. He and >send are the only two words and data rate. The distance ranges from currently works for Canadian Pacific needed to build and send simple bul- 2 to 5 miles depending on the transmis- Railway where he is involved with lets. You could stop here and build sion rate that is selected on the modem. radio-controlled locomotives and applications on this code alone, but Setting up the modem pair was very wireless data systems. continue on. easy. I connected the picoFlash SBC at After you create a bullet, load it one end with a straight cable and con- with the word Load, give it a desti- nected the hub at the other end with a PROJECT FILES nation with the word Is.Target, yellow crossover cable. I powered up the To download code, go to ftp://ftp.circuit and send it off with the word modems and waited for the SYNC LEDs cellar.com/pub/Circuit_Cellar/2007/207. Fire.bullet. For convenience, you to indicate that the SDSL link was up. have a word Shoot, which combines When the link LEDs indicated that Load and Fire.bullet in one opera- the Ethernet link was up, I started RESOURCES tion. At the receiving end, use the sending packets that could be moni- FTP Software, Inc., “PC/TCP Packet Dri- word Parse.bullet to strip the bul- tored on the network side and SDSL ver Specification, Rev 1.09,” Crynwr let out of the packet and then use side with the corresponding TX and Software, 1989, www.crynwr.com/ Run.bullet to execute the bullet. RX LEDs (see Photo 3). packet_driver.html. For debugging, you can display a JKmicrosystems, Inc., “picoFlash User’s dump of the loaded bullet with the NOW IT’S YOUR TURN Manual Ver 1.1,” 94-0030, 2004, word Show.bullet and even run the The bullet construct shows how you www.jkmicro.com/documentation/pdf/ loaded bullet on the master board with can send and receive simple packets to a picoFlash_man_v11.pdf. the word Test.bullet. The word network of smart nodes using just Ether- Listen waits for a response from a net. The connection is not “reliable” in slave node. The Recbuf.busy? flag the network sense, such as TCP/IP, but it SOURCES will set when a packet arrives, causing is acceptable for certain applications. If 300S Megabit modem the bullet to be parsed-out and execut- you need to send and receive a few bytes ADC ed. If no packet arrives within 2 s, a of data without having all the overhead www.adc.com No Response string will be displayed that TCP/IP carries, then this is the way and Listen will end. If you need to send to go. If you need a reliable, connection- F-PC V3.60 Compiler large streams of raw data for acquisition oriented service with positive acknowl- Forth Interest Group purposes, load upWWW.GiURUMELE.Hi2.RO the buffer Data.buf edgments and flow control, then you www.forth.org and use the word Shoot.data. At the should consider a TCP/IP stack, which is picoFlash SBC receiving node, the data can be pulled available from JKmicrosystems. JKmicrosystems, Inc. out of rec.buf. Your data chunk can I reserved the first 2 bytes in the data www.jkmicro.com be up to 1,500 bytes in length and will field called “system” bytes, which I not be executed as a bullet. will use in the future to increase the RTL8019 Ethernet controller reliability factor. Realtek Semiconductor Corp. GOING FURTHER Structures like packet sequence num- www.realtek.com.tw The maximum physical length of an bers and ACK responses could be Procomm Ethernet segment is about 100 m. implemented in your application code. Symantec Corp. This restricts the node-to-hub length The code described here was written in www.symantec.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 45 2710017Birsan.qxp 9/4/2007 4:07 PM Page 46

FEATURE ARTICLE by Nicusor Birsan & Ionut Tarsa Embedded Speech Speech Synthesis for Small Applications It’s time to try your hand at an embedded speech application. In this article, Nicusor and Ionut introduce you to speech synthesis technology and describe how to bring audio capabilities to small embedded applications.

Writing code for an embedded on the Internet. Many of them work Circuit Cellar 178, 2005). application is simple: all you need are well, but we complicated the require- Basically, there are two approaches an appropriate compiler and linker. But ments a little. We wanted our TTS to embedding speech: storing sounds why are a lot of software engineers mov- system to fit into a small microcon- with low bit rates using various algo- ing away from it? While some engineers troller without additional hardware, rithms (ADPCM, LPC-10, and CELP) still consider easy-to-develop code for which would have meant higher costs. and drawing an external dedicated chip small processors, many realize that As you read this article, keep in mind on a schematic. In this article, we’ll offer designing complex embedded applica- that embedded software development is a way to embed the control application tions on Pentiums or geode-based an art form. At the same time, you must and the speech feature in the same chip. PC104+ boards is not that easy. In fact, be aware of what is happening in the If you analyze dedicated chip per- both (tasks) are the same, because rapid, marketplace. Remember that although formance, you’ll find that most low- risk-free development requires knowl- 8-bit microcontrollers are still in use, cost chips don’t generate high-quality edge of the application domain, hard- new powerful 32-bit chips with the speech. For example, the Emic text-to- ware/software codevelopment, and a con- same amount of memory are starting speech module, a WTS701-based sideration of safety concerns. Still, like to take their place at the same price. board, is good at speaking numbers, any other job done with passion, embed- but when it comes to announcing ded development has its great moments, EMBEDDING SPEECH something, its performance drops. which are not as rare as you may think. A lot has been written about speech On the other hand, the RC Systems In this article, we’ll cover the topic of synthesis. There is a plethora of scientif- DoubleTalk RC8650 and RC8660 are ver- embedded speech synthesis. In particu- ic papers, books, devices, and profes- satile voice and sound synthesizers. They lar, we’ll explain how to develop the sional software at your disposal. For integrate a sophisticated text-to-speech “software only” portion of an embedded instance, in a 1999 Circuit Cellar arti- processor, audio recording and play- application, which, at first sight, doesn’t cle, Rodger Richey explained how to back, musical and sinusoidal tone gener- require too much additional knowledge build a text-to-speech system with ators, a telephone dialer, and an ADC, all or skills. There are a lot of freely down- small Microchip Technology PIC in easy-to-use chipsets. The downside loadable text-to-speech (TTS) solutions microcontrollers (“Talking Back,” is that the modules are expensive. Circuit Cellar The aforementioned devices have 110). More recent- something in common: their manufac- High-level synthesis ly, the subject also turers support application development Text input Cortex M3 MCU Text preprocessing appeared in Jeff with boards and software programs WWW.GiURUMELE.Hi2.ROBachiochi’s arti- (e.g., RC Studio from RC Systems and Dictionary-based Prosodic and cles about the ChipTalk from www.speechchips.com). Dictionary translator intonation analysis Winbond Electron- Thus, we set out to design portable ics WTS701 firmware for small microcontrollers Low-level synthesis (“Next-Generation and a desktop software tool for devel- Concatenative Wave generator tables synthesizer Text to Speech,” opment and application tuning. Phoneme Circuit Cellar 158, SoundSound PWM data driverdriver (PWM1) 2003) and the Mag- SPEECH SYNTHESIS TECHNIQUES nevation SpeakJet Before starting an embedded project, Figure 1—The block diagram contains mostly software parts, stored data in inter- (“Speech Synthesis it’s a good idea to look at the applica- nal flash memory, and a PWM peripheral. with SpeakJet,” tion domain to find the appropriate

CIRCUIT CELLAR® 46 Issue 207 October 2007 www.circuitcellar.com 2710017Birsan.qxp 9/4/2007 4:07 PM Page 47

high-quality English stored data. The eSpeak sounds good speech, it uses a different on the desktop speakers, but a 360-KB synthesis method than executable and hundreds of kilobytes other open-source TTS of data files discouraged us. How do engines, it sounds different you port more than 0.5 MB of code (it’s clear and easy to listen and data into 64 KB of ROM and 8 KB to), and it can translate text of SRAM? The answer is simple: don’t to phoneme codes so it can port all of it. Port only the program be adapted as a front end kernel and the necessary data. Other for another speech-synthe- features may be added as they are sis engine. In addition, the needed. For instance, why embed all of synthesizer’s source code is the languages? For a Spanish applica- Figure 2—Simple separation and low-pass filters are all the external highly portable, so you can tion, you can include only the neces- hardware needed to test the application. use it with different operat- sary files for speaking that language. ing systems, and there are Before going further, let’s cover the algorithms for embedding. Several dif- various development tools that you can topic of porting eSpeak to a microcon- ferent techniques can help you gener- use to produce and tune phoneme data. troller. We moved the application ate embedded speech. The methods Although the project was originally from C++ to C and kept as much as are usually classified into three developed for Acorn/RISC OS comput- possible from the original project. groups, each of which has its own ben- ers, Jonathan Duddington turned it Next, we reduced the structure sizes efits and drawbacks. into an open-source project last year. for a better fit with embedded applica- The first method, articulatory syn- The new version is an update and a tions and optimized the implementa- thesis, involves modeling the human rewrite that includes relaxed memory tion for greater efficiency. speech production system. In the sec- and processing power constraints. It ond method, formant synthesis, syn- also includes support for additional SOUND FROM LUMINARY MICRO thesized speech output is created languages. Our first task was to develop a using an acoustic model. Parameters “sound driver” and a small application such as fundamental frequency, voic- SYSTEM BUILDING BLOCKS for testing. We wanted the driver to be ing, and noise levels are varied over time Because our job was “simple”—we as simple as possible (i.e., sound gener- to create a waveform of artificial speech. were porting an existing project to a ation could be a secondary feature in a The third method, concatenative synthe- microcontroller—we kept the skeleton control application). sis, involves prerecorded audio samples of the eSpeak project and designed the In terms of the hardware, things are derived from natural speech. modules from the bottom up (i.e., the very simple. Only DC blocking and a The articulatory method is still too translator, prosody and intonation, the low-pass filter are needed (see Figure 2). complicated for high-quality imple- synthesizer, the wave generator, and Due to the high frequency of the Lumi- mentations, but it may turn out to be the sound driver). nary Micro LM3S811’s PWMs, an RC a useful technique in the future. The As you can see in Figure 1, the input filter was enough for a 35-dB rejection formant and concatenative methods text is analyzed and then split into at the PWM frequency. The resistor are the most commonly used in cur- phrases, words, and numbers. Each value we chose did not exceed 8 mA, rent synthesis systems. Formant syn- word is translated into a list of the maximum current of the thesis was dominant for a long time, based on a dictionary with LM3S811’s ports. (Appropriate settings but the concatenative method is a limited vocabulary. While the must be done in the initialization rou- becoming more and more popular. prosody is analyzed, the phoneme list tine too.) With this simple circuit, we is filled with pitch, pitch variations, can drive low-power headphones or an OPEN-SOURCE PROJECT amplitude, and transitions between amplifier (e.g., the line-input of a Building a text-to-speech synthesis phonemes and pauses. After each application from scratch is a hard task, phrase or sentence is translated, the especially becauseWWW.GiURUMELE.Hi2.RO of the complexity phoneme list is passed to the low-level of the data files. That’s why we found synthesizer, the digital signal proces- a project that could be ported into an sor (DSP). Based on the phoneme list, embedded application. the concatenative synthesizer puts When dealing with a new applica- simple commands into a queue from tion domain, it’s always a good idea to where they are processed by the wave find an open-source project as a start- generator. Those commands could be ing point. After looking around, we pointers to waveforms or formant data eventually found the eSpeak synthe- from the “Phoneme data” table, sizer, an open-source project with amplitude or pitch settings, and so on. Photo 1—The LM3S811 evaluation board is speaking many attractive features. It produces We had some trouble with the “stereo” through the PWM1 peripheral.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 47 2710017Birsan.qxp 9/4/2007 4:07 PM Page 48

sound blaster, giving us an opportuni- ty to perform waveform analysis or store the generated sound on the hard disk). There is no need for any circuit- ry if the amplifier is class D (e.g., the TPA family from Texas Instruments). Building the hardware was as simple as soldering a few components and a jack (see Photo 1). This was the only hard- ware we needed to finish the project. The basic functionality of the driver is to output samples to a PWM periph- eral from a circular buffer. The buffer is filled as the interrupt routine eats sam- ples based on a double-buffering tech- nique. While the interrupt generates from one half of the buffer, the applica- tion fills the other half (see Listing 1). We used indices instead of pointers to get a more optimized implementa- tion based on the index addressing Photo 2—After trying to port eSpeak to embedded applications, we developed a new tool. espeakdev lets us test mode of the new RISC microcon- the embedded implementation and adjust it in many ways. trollers. This way, the time spent in interrupt routines is significantly of snd_ix index.) More importantly, generated using eSpeak. The file was reduced. By choosing the length of the it is easy to keep the index within the stored in a constant array in flash buffer as a power of two, testing which range of the buffer with only an AND memory. (Refer to the TestDrv project half is currently “playing” is much eas- instruction. on the Circuit Cellar FTP site.) ier. (Test only the most significant bit To test the driver, a WAV file was The first time that we tried the sys- tem, it was a success. The sound gen- erated was the same as the sound from a desktop speaker. Hearing the small LM3S811 evaluation board speak “Cir- We Listen. Think. And Create. cuit Cellar and Luminary Micro Con- test” motivated us to continue.

FIRST BIG PORTING PROBLEM Distributed Serial Digital Industrial HMI I/O I/O I/O Computing In eSpeak, sound is generated based on two principles: sinusoidal for vow- els and short waveform files for conso- nant phonemes. With the formant • Digital & Analog I/O method, WAV files and transition information are stored in three data • Connection via Ethernet, USB, files: phondata, phontab, and phonin- RS-485, or RS-232 dex. The main problem is the size of • Daisy Chain Expansion those files. We planned to use English • Field Removable Terminal Blocks for our first attempt, but the phoneme data was too large to fit into the • Compact, Rugged Form Factor WWW.GiURUMELE.Hi2.ROLM3S811’s memory. Also, going down • DIN Rail or Table Mount Design from 22,050 samples per second to • Robust Development and 8,000 has some effect, but this affects Confi guration Tools only the size of the WAV files stored. A deep look into those tables reveals FCUS that there are a lot of redundancies. On Success That’s because the eSpeak developer added a lot of diphthongs to make speech generation more natural. A phonetic variation is added if a specif- ic letter is followed or preceded by

48 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 33.qxp 6/28/2007 9:42 AM Page 1

WWW.GiURUMELE.Hi2.RO 66.qxp 9

USB RF Ethernet I/O I2C Testing / 5H r6Mz2-ch +60MHz or 25MHz with 7.8” color LCD. LCD. color with7.8” PDS5022S standaloneUSB with expensive LCD scopes! PDS6062T PDS6062T Check outthewholeFTDIline! FT232BL $2.93 FT232RL $2.50 unique IDandInternalEEP Each new "security-dongle"feature. FT232RL USB I2C/IO$79 boards formoreI lines. Freesoftware. Use multiple your PCto90kHzI “drop-in” solutionforconnecting Devasys - eCOV-110-P $99 10/100mpbs RS-232 IP instant Provides an without aPCusingthis28”cable. Network yourserialproducteasily motor - control 35V/3A- idealforrobots/industrial unipolar steppermotorsupto motor driveandcontrolsystemfor Easy-Step 3000 Serial-Ethernet Cable based emb.dev. system phones, etc.microIceBlue- Easy connectionformicro'stoPCs, module (UART master/slavebridge). Emxys PearlBlue Bluetooth develop 6

www.saelig.com Best 1-888-7SAELIG /

Seller Scope LCD Color c 2007 12:10PMPage1 USB inoneIC Stepper Motor h control expert! USB toI2C e otcompatible withmost port TIUB.-eilI with - FTDIUSB1.1-serialIC Bluetooth turns youintoaninstant c (60MHz) (60MHz) (25MHz) (25MHz) Ethernet hubs. Provides asimple k k k - Advanced stepper - Advanced UNIQUE PRODUCTS PRODUCTS UNIQUE f ment. - 100m-Bluetooth o bench scope bench 2 C/IO. 2 r r r C +20I/O

WWW.GiURUMELE.Hi2.RO Compare for PIC16F877 from $84 ROM, s address. shortest p trigger $599 $349 PDAs, (1K) (1K) e $99 c i HDS2062M HDS1022M great foryourtoolkit. color LCD.Built-inmeter- rugged handheld USBscopewith3.8” 60MHz or 20MHz Touchpanel Controller T70 $359 CT1720 2 RS232MODBUSsupport. and/or LadderLogic.82I/Osand CUBLOC PrograminBasic Graphic LCD Touchpanel/controller. CUTOUCH - UM232R $19.99 adds USB1.1instantly! cuit forFT232R.Plug-inmodule foryourproject.Reference cir- er module -USB-TTL serialconvert- UM232R - GS-10J$34 EG-SR-7150MJ Internet-enable anyserialpart. 230kbps serial.Ethernet/ - for 10/100Mbps Ethernet Ethernet Gateway. Simple WIZnet - International Standards ISO14443 RFID ReaderChip- S-0 vlKt$350 RSK-100 EvalKit TRH031M $6.95 Single-chip solution. A/B, Tag-IT, FelicaandISO15693. GHB-3224C $199 graphics, etc. Basic. Displaybmp,text, white backlight.Programin graphics/text 4.8”x3.6”LCD- I2C/RS232-driven easy-to-use a Blue 320x240LCD Ethernet toSerial l ll FT232R Module o Handheld Scope f f 3ALogics Ready-to-go e FT232RL 24-pinDIP (20MHz) (60MHz) r s 320 x240Blue ! Reads FIVE seria set-up $749 $529 l-to- SIO4 $69 USBI/O24R USB port. programming. I/OcontrolviaPCs SX52 allowsindividualpinI/O powered fromUSBport.Ubicom Elexol - te-O2 $109 Ether-IO 24 TCP/IP Ethernetnetwork. programmable. Connects toany ports eachindependently digital I/Oboard3x8-bit TTL Ether-IO - C$9 Demoboard$59 IC $29 USB k external ER900TRS today! wireless capability toyourproject FATfile system to your peripherals USBwiz - ieesdt transmission wireless data ipefrU and Europesimple forUS LPRS easyRADIO FMod-TCP Connect I inputs, 19 xdigital I/O,5x 10-bit A/D Fiveco - oa tentnetwork! to anEthernet Transceiver Modules USB to24xI/O Ethernet toI2C nowledge needed.Plug-n-play! Mixed-Signal PCOscilloscope and UART serialinterface. 4lthdIOlnss 24 latchedI/Olines TCP/IP serverwithI2C, Ether-IO USBwiz USB hard UDP/IP-controlled 24 2 C devices/sensors Easily addUSB for USB from $38(100) ytm I system. TM from $250 rvs No drives. thumb & makes ncludes ! Add elf- CS700A CS328A-8 CS328A-4 inputs formixedsignaldisplay/trigger. dynamicrange.8digital than 60 dB with more channels x10,12,14bit swept signalgenerator. 2 Analog drilling andzooming.Optionalbuilt-in Huge 4or8MSbuffer fordeepdata hard-to-get-at glitches,spikes,etc. lets youdocomplextriggeringtofind 100 MHzScopeandLogic Analyzer PicoServ P01V0 $205 PP1001-V00 control, SCADA, buildingcontrol. a webconnection. Collect analog&digital data over allows remoteI/Oandservicing. Owasys from$441 etc. RS232/485/CAN/ for M2M-autos, Ethernet wireless GSM/GPRS/GPS/Bluetooth/ microUSB $25 3.3V Gnd/RX/TX Suspend,Reset,& based onSiLabsCP2101. Interface to1Mbps 0.7”x0.5” microUSB - AFTI $14 uALFAT IC uALFAT-SD $40 out. FATfile data - Serial data in product. your to SD storage Micro ALFAT-SD- Wireless Controllers PCI93LV 400kHz! Transparently monitorat UCA93LV and debugI2Cbussystems. gives windows-interfacetodevelop for PCs. Mini Web Server FATfile Storage 100mA source. I2C for (signal generator) : industry-standard I2C Easy USB TM (8MS Buffer) (4MS Buffer) WINI2C/PCI iyraymd USB Tiny ready-made Miniature Web Server is USBversion. Remote sensing/ PCs Easily add + controllers A/D-I/O. machines, software $1642 $1149 $499 $249 card 585-385-1768 fax [email protected] iyn ibe $55 B915FH-tiny/40-SMD-WA $61 TinyOne Zigbee integration intowirelessapplications. RF moduleensuresfastandeasy transmission.MiniaturizedOEM data Complete RFsolutionforfast&reliable Micro LCD-OLED$99 Micro LCDMKII$82 anymicrowithserial/USB. for Add text/graphics/animations bright or 128 xcolorLCD Micro LCD- W5100 improves systemperformance. No OSrequired. TCP offload chip! Fullyhardwired TCP/IP core. 10/100 Ethernetcontrollerona NM7010B+ Eval$22 hardwired TCP/IP-I - NM7010A-LF REV2 network speedsto8Mbps. W3100A-based boardforinstant microprocessor systems.Drop-in stack forhi-speedInternet- ue rcSikI $209 Super TrackStick II data onGooglemaps! location, routeandspeed. personnel, etc.Records tracks positiondata for TrackStick II- PS2105 Delphi/LabView/VEE C/VB/ 100MS/s, 24kSbuffer scope-in-a-probe! Upto PS2105 PS2104

NEW SUPPORT! IntTPI IC WIZnet TCP/IP TinyOne Zigbee Ethernet toI2C n GPS Logger e Pen Scope (integrated PHY) Easy LCD (10MHz, 50MS/s) (25MHz, 100MS/s) 5H USBpow - 25MHz w w w aywyt d ”sq Easy waytoadd2” Pocket-sized logger p 2 r C module.Offloads o d Complete, date, time, u vehicles, drivers. enabling c Shows OLED. $6.95 $234 $372 $175 TM t ered $22 s s s e USB-COM USB-COM-S provide virtualCOMport. products to older Instantly adapts FTDI - RTM-USA $89 port! for yourproductfromPCUSB your device!Getremotecontrol boards addwirelessRS232to USB-powered radiotransceiver Portbase-3010/RS232 from$171 IP/DHCP/PPPoE. 10/100Mbps-230kbps. Static devices. 1/2/4/8/16/32ports network-enabling legacyserial RS232/422/485 deviceserver appliance mfrs by theworld’s largest Spread-spectr Key Patented Adj. sensor ICsforswitching&control. Quantum ICs LAP-16128U $299 clipleads, USBcableandsoftware. and UART monitoring.Includes Sophistcated triggering.I 16-channel with4mbmemory. ZeroPlus -Intuitivefull-featured USB-Serial Adapter FREE COFFEE not availablewithanyotheroffers Touch-Sensing ICs Call 1-888-7SAELIG v e Mention Offer#SBW Serial Server Logic Analyzer Data Modem ae serialport based r While supplieslast- with yourorder! Starbucks y y y to getafree USB! Included (13”) m nuse um. In - World’s bestcapacitive d a (45”) y Card Suppression, ! consumer/ worldwide 2 from $1 laptops. RS232 C, SPI, drivers $25 $19 for 2710017Birsan.qxp 9/13/2007 11:04 AM Page 51

Listing 1—While playback is done from one half of the buffer, the other half is filled with data. platform toolkits, wxWidgets applications look and feel native. This is because //internal driver buffer wxWidgets use the platform’s own native #define MAXIM_BUF 1024 controls rather than emulate them. It’s unsigned char* MCU_out_ptr; unsigned char* MCU_out_end; also extensive, free, and open-source. unsigned char MCU_outbuf[MAXIM_BUF]; Instead of building C files directly from //======binary data files, it was added to a // Sound Handler // Output samples to PWM1 new class, CompileEmbedded, to gen- // if max_ix is reached the generation is stoped erate C files from phoneme source files. //======This was a good choice because the void IntSoundHdl(void) { unsigned short m_ind = snd_ix; phoneme tables could be minimized //use a register as apointer to SFRs or optimized by any embedded devel- unsigned long* p_gen = (unsigned long*) TIMER0_BASE; oper with permanent feedback from p_gen[((TIMER_O_ICR)/4)] = TIMER_TIMA_TIMEOUT; if(m_ind != max_ix){ the desktop speakers. unsigned long c = MCU_outbuf[m_ind++]+5; In the CompileEmbedded class, all snd_ix = m_ind & (MAXIM_BUF -1); of the before and after variations for p_gen = (unsigned long*) (PWM_BASE + PWM_GEN_1); p_gen[((PWM_O_X_CMPA)/4)] = c; virtual phonemes were removed. This p_gen[((PWM_O_X_CMPB)/4)] = c; way, the phoneme tables, indices, and }else{ data for English fit into about 30 KB. //stop generation (disable timer interrupt) HWREG(NVIC_DIS0) = 1 << (INT_TIMER0A - INT_GPIOA); From a user’s perspective, the process sound_stopped = 1; of C file generation is as simple as select- } ing a menu item. Then, two files are cre- } void task_sound_driver(void){ ated in the “data” folder mcu_phondata.c static unsigned short prev_ix=0; and mcu_phontab.c. The files are unsigned short curr_ix = snd_ix & (MAXIM_BUF/2); included in mcu_synthdata.c, which is if( (curr_ix != prev_ix) ){ // driver is playing, fill next half buffer only a part of the synthesizer kernel source MCU_out_ptr = MCU_outbuf + prev_ix; files (see Photo 3). MCU_out_end = MCU_out_ptr + (MAXIM_BUF/2-1); filled = MCU_WavegenFill(0); } SYNTHESIZER } The synthesizer’s inputs consist of a list of phonemes and speech variations that must be synthesized into com- another one in the text (before and mcu_wavegen.c, mcu_synthesize.c, and mands to the waveform generator. The after modifications). This issue pre- mcu_translate.c. The user interface was commands are stored in a queue. sented a new challenge: we had to modified by adding elements to help us Pointers to formants and wave-sound develop a special tool. As you’ll see, verify the implementation by comparing data are stored in the queue, as well as the tool helped a lot. the speech quality with the full eSpeak pitch and amplitude, variation, and a You might think that porting soft- (see Photo 2). formants modifier. ware to an embedded platform is as With espeakdev, you can generate C For more natural speech, sound param- simple as copying source files to a source files with constant arrays. You eters are modified in short frames of microcontroller project. But the files can also test and modify it with closer about 3 to 8 ms, depending on the sample can’t be linked or even compiled. feedback. At the same time, you can rate. Because of intonation and prosody Sometimes you have to modify a lot of adjust formants or test prosody because rules, the formant parameters are not the source files and settings. A faster it can be done in the espeakedit program. same as data files, but each frame could approach is to write code for a PC to In order to keep the espeakedit be multiplied, copied multiple times with gain both a well-tested embeddable ver- portable, we built the new tool with frequency modifications, and so on. sion and a development tool. The tool wxWidgets in Visual C++. This way, One of the main reasons for moving code is based on the WWW.GiURUMELE.Hi2.ROespeakedit program. we have both development environ- from C++ to C was to avoid complica- Source files are available on the ments for the PC utility program and tions and overhead due to dynamic allo- SourceForge web site. The new tool, μVision for the LM3S811 on the same cation in small-sized SRAM. So, instead espeakdev, is the same as espeakedit. Windows platform. of using heap memory for allocating It offers the same functionality plus The wxWidgets toolkits enable space for queues or frames, a fixed- some menus and buttons dedicated to developers to create applications for length queue is declared and a simple generate tables and test the embedded various platforms, such as Win32, Mac frame allocator is written, which implementation. OS X, GTK+, X11, Motif, Windows CE, returns pointers from a fixed-sized As you’ll see, the espeakdev includes and more using one codebase. It can be buffer. espeakedit functionality and some addi- used with languages such as C++, Python, After all the source files were tested tional source files: mcu_synthdata.c, Perl, and C#/.NET. Unlike other cross- in Windows, a short application

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 51 2710017Birsan.qxp 9/4/2007 4:07 PM Page 52

(play_phoneme) was easily developed Listing 2—Sound driver, speak, and other tasks are called from a while loop. in Keil μVision for synthesizing phonemes on the LM3S811. The input while(1){ of a synthesizer consists of a list of task_sound_driver(); Task_Speak(); phonemes generated by espeakdev in a if(new != g_TickValue){ //A user task timed scheduled; source file named play_list.c. Even new = g_TickValue; though this looks like a child’s game, p = GetSourceGen(); //get the pointer to current word if( p != NULL) { //if is something speaking we achieved an important task: we if( p != last_p){ tested the DSP part of the synthesizer. last_p = p; for(i=0;i<12;i++){ //copy the text to a buffer buf[i]=*p++; TRANSLATOR } The translator’s basic function is to buf[12]=0; transpose text to be spoken into OSRAMStringDraw(buf, 11, 1); //and display it } phonemes. Generally, this is done based }else{ //speak again on language rules and a dictionary of SpeakLumi((char*) HelloMsg); phonemes. The two approaches have } } advantages that have been discussed in } many papers and books. Here is the problem. English has so many rules that it could not fit into the LM3S811’s modified by selecting data-compile couldn’t be called speech because each flash memory. And those rules can’t dictionary from the menu. phoneme changes its length, pitch, and cover all the possibilities. A long list We wrote a new class for generating C amplitude as a function of the adjacent of exception words must be kept in a files with the phoneme table. We added a phoneme. So, after translation, pitch and dictionary. new function, Translator::Generate length are adjusted by two simplified There is only one solution for this. Dict(), in which the current dictionary functions: MCUCalcPitches() and Because our small microcontroller list is saved in a header file (m3_dict.h). MCUCalcLengths(). It’s hard to call must speak a limited number of words, Now we have a dictionary. For the quick this prosody or intonation, but words we used a dictionary with only the search of words in the dictionary, a can be heard clearly on a speaker. vocabulary needed for our application. 10-bit hash table is generated. Now is the time for espeakdev to reen- On the microcontroller, all the func- THE LM3S811 SPEAKS ter the scene. First, we have to make a tions regarding translation are written in After all the pieces were written and new voice just for testing the new dic- mcu_translate.c. Due to the limited tested on the desktop, it was time to tionary on the desktop (voices/m3). In memory, the MCUTranslate() function move the application to the LM3S811. this file, we can set the language name to takes data directly from the text source It was easy to do this by taking the whatever we want, so let’s choose “m3” so the string passed to it must not suffer skeleton of play_phoneme with few as the name of our application-specific any changes until the current translation minor modifications and adding language because we are testing on a is finished. Each word in the string is mcu_translate.c. Cortex-M3 device. Second, we must have looked up in the dictionary by calling For demonstration purposes, a short a compiled dictionary in the -data MCULookup-DictList(). If the word piece of text was copied from the folder whose filename must start with is found, its phonetic translation is Design Stellaris Contest announce- the same prefix (m3_dict). The compiled moved into the phoneme list at the ment web page as a constant string dictionaries are binary indexed versions input of the synthesizer. into the main source of the project: of two text files that must be edited and The simple playback of a phoneme “Circuit Cellar and Luminary Micro saved into the dictsource folder: m3_list and m3_rules. The m3_list file must con- Listing 3—This task is called from the main routine to synthesize more phonemes or translate the remaining text. tain the phonetic translations of the void Task_Speak(void){ words from the application vocabulary. static int gen_resume = 0; The file m3_rulesWWW.GiURUMELE.Hi2.RO must exist, but since int trans=0; we don’t have any rules for our language, gen_resume = MCU_Generate(MCU_phoneme_list,&MCU_n_phoneme_list,gen_resume); if(0 == gen_resume){ //if there is nothing in the phoneme list it is empty. In order to use our new lan- if(p_cgen != NULL){ //is there more text? guage, we must compile the dictionary trans = MCUTranslate(NULL); //if so, translate the rest from the espeakdev application’s menu MCUCalcPitches(1);//analyse prosody MCUCalcLengths(); (Data-Compile dictionary). Now we can gen_resume = MCU_Generate(MCU_phoneme_list,&MCU_n_phoneme_list,0); make espeakdev speak the new lan- if( (trans ==0) && (0 == gen_resume) ) guage by selecting the m3 voice (on the p_cgen = NULL; //finished to synthesize } speak-voice menu) to see how it } sounds. A new compiled m3_dict can be } obtained any time source files are

52 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710017Birsan.qxp 9/4/2007 4:07 PM Page 53

(see Listing 4). Listing 4—Any task from the application “could speak” by calling the SpeakLumi function, but it would have to wait until another task was finished speaking. If the synthesizer is busy (p_cgen pointer is not NULL), the function int SpeakLumi(char* src){ returns a failure, so the task is if(NULL != p_cgen) return -1; //the synthesizer is busy right now p_cgen = (char*) src; //this task get access to the synthesizer informed that something else “is MCUTranslate((char*) p_cgen); //and start speaking speaking” now. But it could preserve MCUCalcPitches(1); the state and speak a little later. MCUCalcLengths(); return 0; The complete application fit into } 7,856 bytes of SRAM and 57,436 bytes of flash memory (43,032 going to tables). If more memory space is required, the are pleased to offer design engineers an to the software delays from the OLED dictionary may be reduced to just the incredible contest opportunity called library, that may cause blocking. The words needed in the application. Also, Design Stellaris 2006. And with Circuit display functions are not called often. the WAV generator buffer could be Cellar magazine, they also have the #1 The DSP part is called from the smaller, but this would result in some venue for peer recognition of their win- speak task in order to synthesize all of overhead because the sound driver must ning applications.” the phonemes from the list. If the list be called more frequently to fill it. After all the peripherals are initial- is empty, the remaining text is trans- Repeating the same text stored in flash ized in the main routine, several coop- lated and a new list of phonemes is memory, our application may not appear erative tasks are called from within a obtained for passing to the low-level to be too relevant. But this is enough to while loop (see Listing 2). synthesizer (see Listing 3). This is test the text-to-speech synthesizer’s qual- Periodically, the text being spoken is done until all the phonemes from the ity. From now on, only your imagination displayed on an OLED using a pointer current text are synthesized. is the limit. The Stellaris application can returned from a GetSourceGen() func- Playing another phrase or sentence report anything with its “new voice” tion. This feedback is achieved by from application tasks can be done asyn- (alarms, port states, analog values, etc.). including a pointer at the beginning of chronously by calling the SpeakLumi() the word from which a current phoneme function, which has only one parame- MORE SPEECH APPLICATIONS is translated into the phoneme list. Due ter: a pointer to the text to be spoken With espeakdev and source files

TrackBotTM

shown with optional SunSPOT (purchase separately)

TrackBot is an affordable, autonomous robot platform with a real-time P2P network of RISC chips which manage all WWW.GiURUMELE.Hi2.ROtransducers (including custom ones you can add). Any controller with a standard UART can be added as the high- level application brain. It's lead-free and RoHS-compliant. TrackBot was developed specifically for university-level education and research. It's so unique that multiple patents are pending.TrackBot is in stock and shipping now!

SYSTRONIX® 939 Edison Street, Salt Lake City, Utah, USA www.trackbot.systronix.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 53 2710017Birsan.qxp 9/4/2007 4:07 PM Page 54

way is to modify the file sounddrv.c by Nicusor Birsan has developed embed- confining only the output buffer (with ded systems for more than a decade. its refresh mechanism and update reg- He now shares this experience with ister names) to a specific architecture. his students at the Military Technical A complex project, such as speech syn- Academy in Bucharest, Romania. thesis, could not be built from scratch in a short amount of time because a lot of Ionut Tarsa is an undergraduate student data was required (phonemes, rules, etc.). at the Military Technical Academy. He A solution for building low-cost embed- is fascinated by the fantastic domain of ded speech applications has been around embedded systems. Ionut also enjoys since 1995, and thanks to Jonathan Dud- playing sports, listening to good music, dington you can use it now. Because you watching movies, and reading. have an existing project as a starting point, you just have to optimize the code PROJECT FILES in order to fit it into a smaller embedded To download code, go to ftp://ftp.circuit processor. cellar.com/pub/Circuit_Cellar/2007/207. Photo 3—The espeakdev has the same structure as Even if you don’t have a project to espeakedit and an additional “mcu” folder. start from, it is better to build PC soft- ware first (developed in a top-down RESOURCES from the SRC directory, speech can be manner) and then port modules in the P. Boersma and D. Weenink, “Praat: integrated into other applications. How- firmware from bottom to top. It is easi- Doing Phonetics by Computer,” Insti- ever, only the dictionary must be updat- er to edit, build, and run software on tute of Phonetic Sciences, University of ed to reflect the new product’s vocabu- the same machine than develop directly Amsterdam, www.fon.hum.uva.nl/praat. lary. To do this, you must modify the for embedded targets. For example, the m3_dict file from the dictsource fold- development of the project was facilitat- X. Huang, A. Acero, and H. Hon, Spoken er. The operation must be done manu- ed with espeakdev, which will be a use- Language Processing: A Guide to Theory, ally by translating word by word. Here ful tool for future upgrades. Algorithm and System Development, espeakdev could be improved to generate Because the quality of a speech syn- Prentice Hall, 2001. or automatically update dictionary thesizer is judged by its similarity to F. Popescu, “Evaluation of Lexical source files from a given text file. the human voice and its ability to be Stress Parameters,” The sixth IEEE If you want to make additional mod- understood, you must test the applica- Communications International Con- ifications, you can write new tion. Automated tests aren’t necessary ference, Bucharest, 2006, phonemes, voice, or dictionary files. here. Testing the synthesized speech www.comm2006.ro. This is explained in the eSpeak docu- from Windows software is more mentation. Getting new tables on C appropriate because of the faster code- M. Tatham and K. Morton, Develop- source files is as simple as clicking on build-test process. This is a require- ments In Speech Synthesis, Wiley, 2005. the menus in the espeakdev program. ment here because the naturalness of Furthermore, if the formant and WAV sine wave synthesis by itself is not so files from the phsource directory don’t good, but it’s easy to make the output SOURCES satisfy the requirements, then the understandable by mixing it with the RealView microcontroller develop- development team could use Praat and short waveform files. ment kit espeakdev to record, analyze, and modify One thing must be pointed out. Syn- Keil new formant data for a given phoneme. thesis quality tests have to be done on www.keil.com But, consider yourself warned that this multiple subjects. Even if you think the LM3S811 Microcontroller could be a very time-consuming job. So, output sounds good, another person Luminary Micro, Inc. it’s time to again thank Mr. Duddington. might not. Our work could be improved www.luminarymicro.com Because it is written in a portable in many ways (e.g., code optimization, language like C,WWW.GiURUMELE.Hi2.RO the firmware can be the quality of speech, etc). By porting an DoubleTalk RC8650 and RC8660 syn- moved to any architecture. Porting the active open project, we can also include thesizers synthesis to another platform is as easy additional features such as multiple RC Systems, Inc. as compiling the source files from the voices and languages. I www.rcsys.com SRC directory. The only specific part is eSpeak Text-to-speech synthesizer the sound driver, which consists of an Authors’ note: We want to thank to our SourceForge interrupt service routine in which the colleagues for helping us improve our http://espeak.sourceforge.net waveform data has to be passed to a limited resources on embedded speech PWM or DAC peripheral. Of course, implementation. We especially thank Cross-platform GUI library the peripheral must be initialized by Mr. Florin Popescu for sharing his expert- wxWidgets another routine at startup. The easiest ise in speech synthesis techniques. www.wxwidgets.org

54 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710004 nisley.qxp 9/4/2007 4:09 PM Page 55

ABOVE THE GROUND PLANE by Ed Nisley Hearing Clearly Hardware In his last column, Ed covered his hearing booster’s design. This month he focuses on the actual circuit board and its limitations.

Although Spice simulation models milling machine made short work of shape the audio signal. The high-pass fil- provide reassurance that a circuit can drilling the holes. I fake plated- ter is down 3 dB at 3 kHz, as expected, do what you expect, persuading that through holes by soldering wires and reaches –25 dB at about 700 Hz. A circuit to actually work requires fur- between the top and bottom layers. steeper drop-off, while desirable, requires ther effort. My August column (“Hear- The Spice simulation in my August additional poles and more components. ing Clearly,” Circuit Cellar 205) veri- column matches up reasonably well U6C combines the output of the two fied my hearing booster’s design with with the schematic in Figure 1, which filters with 10 dB gain (voltage gain = a quick-and-dirty prototype, so now presents one channel of the actual cir- 3.3) for a maximum output voltage of it’s time to explore what happens on cuit. As you’ll see, some components 1.8 V peak at 120 dB SPL input. That the circuit-board version. irrelevant to the Spice simulation turn signal passes through volume control I’ll walk through the actual circuitry, out to be vital in the real-world circuit. R28, a dual audio-taper potentiometer, examine its dynamic range limitations, The electret mic elements produce to the MAX4298 headphone amp. then show how a switching power sup- about a 280-mV peak at 120 dB SPL Most potentiometers have a “linear ply might not be as noisy as it seems. and the MAX4467 provides 6 dB of gain taper” with resistance directly propor- (and a voltage gain of 2), for a maxi- tional to wiper angle. That works well CIRCUIT WALKTHROUGH mum 560-mV peak at the loudest for most applications, but produces com- I laid out the hearing aid on a 9×7-cm sound I ever want to hear. pletely unsatisfactory results in audio homebrew PCB that, along with a pair The three op-amps of this channel’s fil- circuits, because human hearing reacts of AA cells, fits in a more-or-less ter reside in U6, a single MAX4334 chip. to ratios rather than absolute differences. pocket-sized box. Most of the layout It’s visible near the top of the circuit For example, most people can detect uses 16-mil lines and generous spaces, board, amid a sea of passive components. a 3-dB change in loudness, a voltage fac- with a few 12-mil traces tucked under Op-amp U6A implements the two- tor of 1.4. Reducing the volume by 6 dB surface-mount ICs. My Sherline CNC pole high-pass Chebyshev filter, with requires cutting the voltage in half: half 0 dB of gain for the total wiper rotation. A linear-taper high frequencies pot would therefore change the volume and a 3-kHz corner very little over most of its rotation: frequency. U6B just 18 dB at 1/8 rotation. implements a simi- An “audio taper” resistive element lar low-pass Cheby- varies more or less exponentially with shev filter: its out- rotation: the center resistance is put at pin 7 has 0-dB 10–20% of the total, not 50%. The gain at low frequen- output of R28, the small blue pot at WWW.GiURUMELE.Hi2.ROcies and breaks at the right side, thus corresponds direct- 1.5 kHz. R45, the ly with attenuation in decibels. blue trimpot near R46 sets the minimum output level the center of to –30 dB relative to the maximum: Photo 1, sets the 330 low-pass output −=×30 dB 20 log 10,000 + 330 level between –12 and –40 dB. The attenuation varies by about 10 dB The response for each 1/3 rotation of the wiper: 0 dB Photo 1—The circuit fits neatly in a small box, even if it’s not as compact as a real hearing aid. The power supply in the upper-left corner has a pair of ground planes curves in Figure 2 at full clockwise and 30 dB at full connected at a single point to the analog planes on the right. show how the filters counterclockwise.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 55 2710004 nisley.qxp 9/4/2007 4:09 PM Page 56

Figure 1—Despite the number of passive components, the overall signal flow is simple: a mic amplifier, a specialized filter, and an earphone buffer. Schematics always omit a key component: the AGND planes covering both surfaces of the PCB under the analog circuitry. Without a solid voltage reference, analog circuitry simply doesn’t work!

Homework: plot the attenuation of at the earphones, at least for high fre- destination. Noise on the VCC/2 refer- both linear and true exponential-taper quencies. The filters attenuate the ence directly affects the most sensi- 10-kΩ pots in that circuit. input by 25 dB below 1 kHz, which is tive points of the circuit, so the com- The MAX4298 earphone driver can the point of this whole exercise. mon bias connections provide an Ω deliver 1.5 VRMS into a 16- load: 140 mW Single-supply op-amps reference their excellent path for positive feedback. maximum. Based on the measurements signals to an AC common voltage, typi-

shown in my August column, Shure E2C cally VCC/2, rather than the “ground” ATTACK OF THE DYNAMIC RANGE

earphones require about 400 mVRMS, just power supply voltage. The MAX4298 Figure 3 shows what happens to the

10 mW, to produce 120 dB SPL. This headphone driver produces a clean VCC/2 electrical response of Figure 2 after circuit could (in simulation!) drive them bias voltage at to 143 dB SPL, the level inside the pin 5, which op- space shuttle’s cargo bay during liftoff. amp U6D buffers I rather doubt they can get that loud, into a simple RC but I have no intention of finding out! low-pass filter to In any event, 120 dB SPL corre- eliminate high-fre- sponds to a 560-mV peak, which is quency transients. exactly the micWWW.GiURUMELE.Hi2.RO amplifier output for I soldered dis- that SPL. The 10 dB of gain provided crete wires from by U6C boosts quiet sounds, although that filter to the

it does pose the risk of hearing damage points using VCC/2. in extremely loud environments. If A more robust you favor such places, a fast automatic design would have gain control or hard output limiter a separate refer- would be a very good idea. ence plane (and a Setting R28 to 2/3 rotation, 10 dB four-layer board!) Figure 2—The high-pass filter attenuates sounds below about 3 kHz, where R45 sets the low-pass filter level to match my high-frequency response. I shifted these attenuation, gives 0 dB overall gain with separate curves vertically to simplify comparisons. They represent peak-held pink noise, so from audio at the electret mic to audio decoupling at each the low-frequency response is rather lumpy.

56 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710004 nisley.qxp 9/4/2007 4:09 PM Page 57

passing through my ears. I While the earphone driver measured my threshold limits the maximum possi- hearing response using the ble output voltage, circuit Audio-CD hearing test, as I noise limits the minimum did last month, then invert- level. The difference between ed the results to show atten- the two, roughly the circuit’s uation rather than gain. dynamic range, defines its In round numbers, my overall resolution: you can- hearing falls off at 40 dB per not hear a sound buried in octave beyond 5 kHz, so a the random hiss of electrons. corrective circuit should pass This circuit’s overall 5-kHz sounds with 0-dB gain noise floor runs at an unim- and amplify 10-kHz sounds pressive –70 dB, so the low- by 40 dB, a factor of 100. If Figure 3—The purple trace shows that the filter flattens my hearing to within ±10 dB est audible signal at the mic between 100 Hz and 7 kHz. While that’s terrible for high-fidelity audio gear, it’s much the maximum earphone out- better than what I started with! I shifted the curves to align near 5 kHz and inverted will be (120 – 70 = 50 dB) put corresponds to 120 dB my hearing threshold response to show attenuation. roughly the level of an aver- SPL at 10 kHz, then an input age conversation. Anything of 70 dB SPL at 5 kHz should be 90 dB Pop Quiz: what’s the voltage? lower than that is lost in the hiss. lower (120 – 70 + 40), a factor of 32 × 103. Commercial hearing aids “ride the Lest this seem terrible, that’s just Assuming a linear response, 90 dB faders” with automatic gain control to under 12 bits of binary resolution: a μ below 400 mVRMS is 13 V (0.4/32k): keep the output within the limitations of DSP with 12-bit ADC and DAC cir- an inaudible 30-dB SPL. But it gets both ears and earphones. An ideal, multi- cuits would just barely keep up with even worse! band, frequency-dependent AGC could this circuit. Of course, the analog cir- The blue trace in Figure 3 shows limit high-frequency gain while simulta- cuitry surrounding the DSP must be that my hearing also requires 25 dB of neously boosting soft low-frequency even quieter so the smaller digital val- attenuation at about 700 Hz, so those sounds. That’s tough to accomplish in the ues don’t represent pure noise. sounds will produce only 5 dB SPL in analog domain, thus accounting for the After some preliminary listening the earphones. popularity of digital DSP-based circuitry. tests, that lower limit seems about

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 57 2710004 nisley.qxp 9/4/2007 4:09 PM Page 58

right; our evening reading sessions However, measuring high-speed, high- sound pretty good, albeit with some frequency analog signals requires more hiss at 10 dB gain. I must try it out at care than you might expect and I think some classical music concerts to see many of the complaints about “switching whether another 10 dB of mic gain hash” arise from simple probing errors will help or hinder the results. rather than the converter circuitry itself. The three oscilloscope screenshots

POWER SUPPLY NOISE in Figure 5 show the VCC supply volt- The circuit consumes less than age, with AC coupling to reveal small- 100 mW under quiet conditions, so a er transients atop the 5-VDC value.

pair of AA cells can provide power for The top screen shows VCC probed several weeks of intermittent use. The near the regulator output, with the MAX1706 converter in Figure 4 steps the scope probe’s 15-cm “ground lead” battery’s declining voltage up to 5 VDC clipped to a lug soldered to the top for the op-amps and earphone amplifier. AGND plane. You can barely see that Although either alkaline or NiMH cells Photo 2—Accurate measurements of low-level, high- lug in Photo 1, just to the left of the will work, I set R1 and R2 to shut off the speed signals require a short ground connection: this lower trimpot, along the lower edge of converter at 1.8 V (0.9 V/cell) to avoid 9-mm tip-ground whisker produced the good-looking the board. This is the way we all make trace in Figure 5c. The op-amp’s V bypass cap and damage to rechargeable cells. A lower CC quick oscilloscope measurements. ground pin connect directly to the AGND plane on the endpoint voltage would extract more The major transients in the top PCB’s bottom surface. My hand-soldered SMD joints energy from alkaline cells. don’t look nearly as nice as commercial reflow joints, trace mark the switching regulator’s The MAX1706 includes a low-dropout but they work reasonably well at audio frequencies. 315-kHz PWM cycle time. The dra- linear regulator that I set to 3.3 V for the matic ringing on the lower, delayed- mic amplifiers. Those circuits have caused by their necessarily abrupt sweep trace is not something you the lowest signal levels and benefit changes in current. As I’ve explored in want on a supply rail.

most from an electrically quiet supply. previous columns, much of that noise The middle screenshot shows VCC Switching regulators have a notori- arises in the stray inductance found in probed at the same point, but with the ous reputation for electrical noise poorly laid out circuit board traces. probe’s short tip-ground whisker

WWW.GiURUMELE.Hi2.RO

58 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710004 nisley.qxp 9/4/2007 4:09 PM Page 59

touching the adjacent top-side GND plane (see Photo 2). All of the high- current paths through the energy-stor- ing capacitors terminate on that plane, making it a better reference point. Simply changing the probe reference point dramatically decreases the noise and changes its characteristics. Rather than a damped oscillation, it now resem-

bles a short square-wave pulse. VCC may still be noisy, but it’s not so bad. Photo 2 shows the same probe across the power supply at U6, one place where power supply noise really matters. C25, the capacitor to the left of the probe tip, connects to the AGND plane on the bottom surface of the board, as does Figure 4—The MAX1706 converts 3 V from a pair of AA cells into 5 V for the op-amps and headphone driver. It the “via” to the right of the probe’s tip- also includes a low-dropout linear regulator that produces a low-noise 3.3-V supply for the electret mic amplifiers. ground whisker. Measured here, U6 The top PCB surface has the GND plane, the bottom surface has the DGND plane, and both are connected to the sees only 10 mV of noise, not the 100 top-and-bottom AGND planes at the SJ2 “solder jumper.” or 200 mV reported at the supply. Perhaps the switching power supply jumper SJ2, between the power switch You can get the complete schematic doesn’t pose such a problem after all! and input jack at the top of Photo 1. and my PCB layout in EAGLE format The MAX1706 sits atop two separate None of the switching transients circu- from the Circuit Cellar FTP site. I ground planes: the high-current GND on late beyond the GND plane, so AGND Ed Nisley is an EE and author in the top surface and the DGND digital and DGND handle only relatively Poughkeepsie, NY. Contact him at reference on the bottom. Both join the small and stable currents. [email protected] with “Circuit Cellar” AGND planes at a single point: solder Increasing this circuit’s dynamic in the subject to avoid spam filters. range beyond 70 dB will require more attention to PROJECT FILES a) detail. For example, 100 dB requires 16-bit accuracy, To download code, go to ftp://ftp.circuit which is less than 10 μV of cellar.com/pub/Circuit_Cellar/2007/207. noise with a 1-V signal! While it’s difficult to achieve RESOURCE 100 dB, it’s painfully easy to R. Elliott, “The Audio Pages: Begin- hit 0 dB. Just daisy-chain your ner’s Guide to Potentiometers,” 2001, analog and digital grounds, run http://sound.westhost.com/pots.htm. b) your switching converter’s ground through wires rather SOURCES than planes, and pay no EAGLE schematic and PCB software attention to the datasheet CadSoft Computer recommendations. Haven’t http://cadsoft.de we all seen it done that way? Maxim parts CONTACT RELEASE Maxim Integrated Products, Inc. www.maxim-ic.com c) If I were doing this for a real WWW.GiURUMELE.Hi2.ROproduct, I’d build a three-band Toner-transfer PCB material stereo equalizer using a DSP, Pulsar Professional fx rather than a handful of analog www.pulsarprofx.com parts, so that I could wrap a CNC Milling machine multiband AGC around it. My Sherline Products, Inc. back of the envelope calcula- http://sherline.com tions say a Microchip dsPIC has enough throughput for the TrueRTA Audio spectrum analyzer Figure 5—The amount of switching power supply noise depends on task, but that’s just a bunch of where and how you measure it. a—Filter cap with a clip lead ground to software distant AGND. b—Filter cap with tip ground to adjacent DGND. c—Across firmware. Are you up for a True Audio op-amp power pins to AGND. Note the vertical scale change! challenge? http://trueaudio.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 59 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 60

FROM THE BENCH by Jeff Bachiochi

RoboGrowth Jeff attended the recent RoboBusiness Conference and Expo in Boston. This month, he pres- ents everything you need to know about this year’s crop of promising robotics technologies.

I reported on the newly established portation, and Field Robotics. In this a complete redesign of an already suc- Emerging Robotics Technologies and article, I’ll present you with brief cessful line of products to leverage the Applications Conference in Cam- descriptions of some of the lectures. features of its Microsoft Robotics Stu- bridge, Massachusetts, back in 2004. There is something interesting for dio (MRS) type of development envi- Now billed as the RoboBusiness Con- everyone. ronment (www.robosoft.com). This is ference and Expo, the event has enabling the production of service moved to the Hynes Convention Cen- PRINCIPLES FOR PROFIT robots at industrial costs and quality. ter in Boston to accommodate a con- Joe Jones, the cofounder of Q Robotics, Robosoft provides advanced robotics tinued rising attendance. The event’s took the audience on a journey through solutions for services, such as educa- focus has also shifted from product the “chronicles of Roomba.” He said the tion and research, transportation, and market development to include success of iRobot’s Roomba is based on cleanliness, security, and healthcare. sales, marketing, and partnering the technique of using common compo- The service-based control architecture strategies. Today’s technology has nents in novel ways (www.irobot.com). can be used for basic to autonomous pierced the industry in a number of The goal was to build a product first and control of a single robot. It can also be fields, including first-responder, a robot second while keeping in mind used for supervision, mission plan- defense and security applications, that its cost must be commensurate ning, or decision making in field robotics, robotic homecare, and with its utility. Since complexity has fleets/swarms of robots. Each service assistive technology. The most suc- been known to kill a project, use innova- has a structured state behavior, a set cessful entries are collaborative tion to solve the tough problems. Test of dependent “partners,” and a con- efforts that demonstrate the new part- everywhere. Test often. tract. Its operations consist of state nering strategy. Note that a deluge of inquiries retrieval and manipulation, creation This year’s RoboBusiness conference about Roomba’s experimenter’s capa- and termination, and notifications. featured a world-class line-up of bilities has led to the release of iRo- An experimental mission, which keynote speakers from the consumer, bot’s Create platform (see Photo 1). happened last June, was the “Robuter commercial, healthcare, defense, and Odyssey,” a behind-the-scenes tour of security robotics markets. Henrik INDUSTRIAL SERVICE ROBOTS the Versailles Palace. Orange fiber cus- Christensen (KUKA Chair of Robotics, Robosoft’s RobuBOX technology is tomers (in France) can now discover Georgia Tech) and Tandy Trower (Gen- private areas of the palace, thanks to a eral Manager, Microsoft Robotics high-speed, broadband connection. Group) were two of the speakers. In The self-guided remote tour of the addition to theWWW.GiURUMELE.Hi2.RO special sessions, there rooms in the Palace of Versailles is led were the usual tracks or themed ses- by a Robuter fitted with an HD cam- sions, which ran concurrently. This era (see Photo 2). This is a world first year, the Tuesday track consisted of that brings together culture, high- Business Development and Partner- speed broadband, and robotics. ship, Technology and Standards, Applications and Products, New Mar- Photo 1—The iRobot Create won’t fall apart after all NETWORKED ROBOTICS kets, and Bonus (miscellaneous). your hard work. After all, it is based on the iRobot Although “networked” meant Wednesday’s tracks included Security Roomba vacuuming robot platform. An open cargo bay “wired” in the not-so-distant past, and a 25-pin expansion port enable you to add your and Defense, Healthcare Robotics, own sensors, grippers, wireless connections, comput- wireless networking is now rapidly Consumer Robotics, Intelligent Trans- ers, or other hardware. (Source: www.irobot.com) taking hold. A networked robot is

60 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 61

teleoperated if the operator has software physics) of your plat- full control over all of the form and environment using robot’s moves (i.e., RobotWars). visual and physical views. The When an operator guides a robot services and samples package toward a goal, with the robot in offers tutorials, popular robot control of its environment, the support, and libraries of useful connection is telerobotic (i.e., functions (camera, speech, the Mars rover). If the operator GPS, etc.). receives a view of the net- The new MRS V1.5 supports worked robot’s remote activity, Windows CE and Windows the operation is telepresence. mobile devices. It includes Energid Technologies’s Actin enhancements to VPL and SVT software toolkit has algorithms and expanded services for iRo- Photo 2—Robosoft’s Robuter is allowing fiber optic subscribers in and software for control and France a behind-the-scenes view at the Palace of Versailles. (Source: bot Create, color tracking, simulation (www.energid.com). www.robosoft.com) speech recognition, and IP cam- The software uses a manipula- eras. A free download is avail- tor control markup language (MCML). includes a runtime package that uses able for noncommercial use at the It can handle multiple joints, branches, a concurrency and coordination run- Microsoft Robotics Studio web site and end effectors, and it is ’Net trans- time (CCR) library to avoid manual (www.microsoft.com/robotics). ferable (see Figure 1). Advanced algo- threading, locks, and semaphores. The rithms handle critical 2-D and 3-D decentralized software services (DSS) CREATING A COMMODITY robot vision tasks. Presently, Energid is enable live monitoring, which can run I dream of having the ability to port working with the Vecna Robotics BEAR locally or across a network. The any robotics application to any robot- (www.vecnarobotics.com/robotics) and authoring package supports writing ics platform. (This would create huge NASA’s Robonaut (www.nasa.gov/ robot applications via a browser, Visu- opportunities.) The possibility of any missions/science/robo_sensors.html). al Studio, or .NET. The visual pro- robot easily integrating (interoperat- gramming language (VPL) uses the ing) with any other robotics (or nonro- ROBOTICS IS IN JAPAN familiar drag-and-drop method to cre- botics!) platform means never having Japan’s declining birth rate will ate graphical dataflow diagrams. The to reinvent the wheel. While Holly- lead to a decrease in the labor force, simulation visualization tool (SVT) wood would have you believe it’s as an increase in the aging population, gives a 3-D rendering (using integrated easy as R2-D2 plugging into the Death and a load on social welfare and nursing services. Financial ini- String-float map tiatives are beginning Surface properties Kinematic structure to fuel an investment “red” 0.5 … … “green” 0.5 Base link in expanding the “Metal-1” 0.75 robotics market Actuator properties “blue” Link 0 … throughout Japan. … “frictionK” 0.2 Link 1 RoboKind, the first nationally recognized

consumer robotics Shapes Link 2 Link 3 project between Japan “Metal-1” Polygons and the U.S., is sched- uled for release in Dynamic base 2008. For more infor- Universal Static base mation on partner- Sensor properties Distal ship, visit WWW.GiURUMELE.Hi2.RO frame www.osakacity.org. State System Proximal ROBOTICS STUDIO frame Link Microsoft Robotics Environment System Studio is a develop- Joint kinematics ment platform that Reference frames supports a variety of Mass properties users, hardware, and applications scenarios Figure 1—Energid Technologies’s Actin software has algorithms and software for control and simulation. It uses the manipulator control (see Photo 3). It markup language (MCML) to describe the task universe.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 61 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 62

High Technology Consortium Foun- dation (www.wvhtf.org)—has respond- ed to an urgent explosive ordnance disposal (EOD) requirement. The BomBot is a low-cost RC robot that can be rapidly deployed to place explosive charges on or near an improvised explosive device (IED) without exposing the operator to dan- ger (see Photo 4). Public service applications abound for small mobile robot platforms (e.g., situational awareness and remote response applications). Robots provide support to bomb squads, SWAT and HAZMAT teams, Photo 3—The Microsoft Robotics Studio is free for noncommercial use. It supports many robotic platforms. Simu- fire and rescue organizations, and lation enables you to test actual code right on the PC. (Source: Tandy Trower, http://msdn2.microsoft.com/en-us/ correctional facilities. robotics/default.aspx) PERFORMANCE STANDARDS Star to interpret the “whole imperial portability based in commercially Founded in 1901, the National Insti- network,” what you have in reality available software (www.omg.org). tute of Standards and Technology are disconnected islands of data, infor- The OMG is an international, open- (NIST) strengthens the U.S. economy mation, and computational power. membership, not-for-profit, member- and improves quality of life by work- What can you expect from a diverse controlled consortium with freely ing with industry to develop and apply conglomeration of languages, operat- available specifications. It’s been technology, measurements, and stan- ing systems, and networks? around for 17 years with some notable dards. The Intelligent Systems Divi- Standards are a good thing, but get- successes, such as the unified model- sion is developing the measurement ting there is a difficult road because a ing language (UML), model-driven and standards infrastructure, which standard can be the source of enor- architecture (MDA), and common includes robotic and operator-assisted mous wealth or the death of corporate object request broker architecture systems for defense, public safety, empires. The standards world is huge. (CORBA). security, and transportation. It includes internationally accredited The mission of OMG’s robotics Recently, the NIST has been work- standards bodies (ISO, ITU, etc.) and domain task force (RDTF) is to foster ing with other agencies to develop nationally accredited standards bodies the integration of robotic systems performance requirements, metrics, (ANSI, DIN, AFNOR, etc.), as well as from modular components through and standard test methods for home- consortia and forums (OMG, TOG, the adoption of OMG standards. OMG land security robots (www.isd.mel. TMF, etc.). OMG’s mission since 1989 is organized into three groups: infra- nist.gov/US&R_Robot_Standards). has been to develop an architecture structure, devices and data profiles, They will enable agencies and users using appropriate technology for mod- and functional services. The infra- to obtain the best value for their eling and distributed application inte- structure group handles the tools investment in robots to save lives gration, which guarantees reusability needed to support applications devel- through the broader deployment of of components, interoperability, and opment (i.e., component model, robots and to help robot suppliers deployment, software framework, and middleware). The devices and data profiles group is responsible for deter- mining actuators, sensors, and com- WWW.GiURUMELE.Hi2.ROposite device and relation manage- ment. The functional services group takes on system components, such as localization, navigation, task plan- ning, object recognition, and human interface issues.

Photo 4—The BomBot robot is designed to disable BOMBOT and dispose of IEDs. The robots can be rapidly The robotics program of the scien- Photo 5—Testing requires creating a disaster environ- deployed to place explosive charges on or near an ment. No simulations here. Robots get to run through IED without exposing the operator to danger. (Source: tific research group (SRG)—which is actual debris fields. (Source: Brian Antonishek, Carey Butler, www.wvhtf.org) supported through the West Virginia www.isd.mel.nist.gov/US&R_Robot_Standards)

62 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 63.qxp 9/6/2007 12:01 PM Page 1 We’re semi nuts

We’ve got semis on the brain. Jameco offers more major brands of semiconductors than anyone — almost twice as many as these catalog distributors.* It’s another Jameco advantage.

Mouser® Newark® Allied® Jameco® Atmel Semiconductor Altera Analog Devices Altera Avago Technologies Analog Devices Atmel Semiconductor Analog Devices Cypress Semiconductor Avago Technologies Avago Technologies Atmel Semiconductor Diodes, Inc. Cypress Semiconductor Freescale Semiconductor Avago Technologies 5 Fairchild Semiconductor Fairchild Semiconductor Infineon Technologies Cypress Semiconductor Freescale Semiconductor Freescale Semiconductor Integrated Devices Diodes, Inc. Intersil Integrated Devices Intel Corporation Fairchild Semiconductor Lattice Semiconductor Intel Corporation Intersil Freescale Semiconductor Lite-On Semiconductor Intersil Lattice Semiconductor Infineon Technologies 10 NEC Corporation Lattice Semiconductor Maxim Integrated Devices Sharp Microelectronics Maxim National Semiconductor Intel Corporation ST Microelectronics National Semiconductor NXP (formerly Philips) Intersil Texas Instruments ST Microelectronics ST Microelectronics Lattice Semiconductor Texas Instruments Texas Instruments Linear Technology 15 Lite-On Semiconductor Maxim Micron Technology Microsemi National Semiconductor 20 NEC Corporation Free shipping NXP (formerly Philips) on these and Renesas Technology other brands. Sharp Microelectronics 79 ST Microelectronics Call for details. 25 Texas Instruments Toshiba

OTHER JAMECO ADVANTAGES: I More major passive, interconnect and electro- mechanical brands than other distributors. I 99% of catalog products ship the same day. WWW.GiURUMELE.Hi2.ROI Lowest prices guaranteed, or we pay 10%. I Major brand names and generic equivalents for even greater cost savings.

Order 24 hours a day, 7 days a week www.Jameco.com Or call 800-831-4242 anytime

©Jameco Electronics. *According to their web sites on July 23, 2007. Trademarks are the property of their respective owners. 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 64

maker of the TUG robotic indoor transport system shown in Photo 6, separates the potential mobile envi- ronment into one of three environ- ments: highly structured (i.e., factory floor), mostly structured (i.e., indoor navigation), and unstructured (i.e., outdoor navigation). It has developed an effective navigation system for Photo 6—The TUG robot centers its load between its mostly structured environments drive wheels. It acts like a big rig’s cab, enabling its without expensive sensors and navi- Photo 7—Although mapping can supply an overall load to be connected like a trailer. (Source: Aethon, gation systems (2-D/3-D) and costly plan, collision avoidance sensors are a must for getting Inc., www.aethon.com) infrastructure. The solution uses through congested areas. (Source: Anthony Diodata, www.cypressworld.com) dead-reckoning with odometry in accelerate the development of conjunction with inexpensive sen- advanced capabilities (see Photo 5). sors for location (1-D). able to make subtle adjustments to The three-step process begins with Using dead-reckoning for position- compensate for accumulated errors. gathering requirements (in this case) ing has the weakness of accumulat- A rank of onboard sensors pays atten- from FEMA teams and bomb squads. ing position errors due to differences tion to the expected environment and The NIST then develops test methods in programmed versus actual wheel helps make the minor adjustments and collects data by testing products. radius or wheel-to-wheel measure- automatically. Finally, it publishes the results of the ments. Even a perfectly implemented tests. You can get more information system can be thrown off by slippage HOSPITAL ENVIRONMENT (including preliminary reports and or irregular surfaces. By centering the Representatives of Cypress Computer results) by visiting its web site. workload over its center of rotation, Systems discussed the process of using the forces on each wheel remain bal- an autonomous platform to enhance INDOOR NAVIGATION anced and positional errors are kept useful applications in a hospital envi- Aethon (www.aethon.com), the to a minimum. The trick is to be ronment (www.ccsrobotics.com). The

WWW.GiURUMELE.Hi2.RO

64 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 12/4/2006 11:56 AM Page 1

WWW.GiURUMELE.Hi2.RO 81.qxp 12/5/2006 1:31 PM Page 1

Keil Microcontroller DevelopmentTools Only 4 Steps... help you create embedded applications quickly ...are required to generate efficient, reliable and accurately. Keil tools are easy to learn and use, yet powerful enough for the most applications with the μVision IDE and demanding microcontroller projects. development tools from Keil.

Step 1. Select Microcontroller and SpecifyTarget Hardware Use the Keil Device Database (www.keil.com/dd ) to find the optimum microcontroller for your application. Inμ Vision, select the microcontroller to pre-configure tools and obtain CPU startup code.

Step 2. Configure the Device and Create Application Code The μVision Configuration Wizard helps you tailor startup code to match your target hardware and application requirements. Extensive program examples and project templates help you jump-start your designs.

Step 3. Verify Program Execution with Components of Keil Microcontroller Development Kits Device Simulation High-speed simulation enables testing before hardware is available and helps you Keil makes C compilers, macro assemblers, with features like instruction trace, code real-time kernels, debuggers, simulators, coverage, and logic analysis. evaluation boards, and emulators.

Over 1,200 MCU devices are supported for: Step 4.WWW.GiURUMELE.Hi2.RODownload to Flash and n 8-bit - 8051 and extended 8051 variants Test Application n 16-bit - C166, XC166, and ST10 Once your application is runs n 32-bit - ARM7, ARM9, and Cortex-M3 in simulation, use the Keil ULINK USB-JTAG Adapter for Flash programming and final Download an evaluation version from application testing. www.keil.com/demo

800-348-8051 www.keil.com 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 67

Mode of autonomy Defines task goals Supervises vehicle direction Motivates motion Prevents collisions control, forward collision Teleop Human Human Human Human warning, adaptive cruise con- Safe Human Human Human Robot trol, blind spot monitoring, Shared Human Human Robot Robot lane departure warning, auto- High-level tasking Human Robot Robot Robot mated parallel parking, and Autonomous Robot Robot Robot Robot low-speed following will be Table 1—This table shows where the responsibilities of a particular task might lie based on the level of autonomy given to implemented shortly on new a robot. automobiles if they haven’t already. Self-aware and con- Speci-Minder project proved that like its robot intelligence kernel, which text-aware vehicles are not far most applications, defining the task is provides a portable behavior architec- behind. They will not only be aware often more difficult than implement- ture (www.inl.gov/adaptiverobotics). of the vehicle’s surroundings, they ing it with hardware and software. One facet is its dynamic use of opera- will also monitor the driver and pas- Dealing with a changing environment tor involvement. The kernel divides sengers to anticipate their needs. puts heavy demands on an autonomy into five levels between autonomous platform (see Photo 7). teleop (total user control) and UNIVERSAL ROBOTIC PLATFORM The task at hand is to deliver speci- autonomous (total robot control). Gostai presented its core technolo- mens within the hospital’s pathology Refer to Table 1 to see how various gy, a universal real-time behavior lab. Delivery requires a simple human modes determine responsibilities for interface (URBI). It is a powerful par- interface for nontechnical operators, certain tasks. allel script engine, coupled with static and dynamic obstacle avoidance The ability to dynamically change a UObject component architecture, for the platform, and zero tolerance robot’s autonomy has many advan- that can control hardware and soft- for failures. Facility integration often tages. It can significantly reduce an ware components in a flexible and presents its own stumbling blocks operator’s workload and communica- portable way. URBI provides robot (e.g., automatic doors, elevators, and tions bandwidth. It can improve task manufacturers and end-users with a ramps). efficiency and the operator’s “touch.” universal robotic platform with state- Speci-Minder uses a platform manu- of-the-art software modules (i.e., factured by MobileRobots. The AUTONOMOUS TECHNOLOGY voice recognition and face detection) Advanced Robotics Command Lan- Police reports indicate that 90% of in partnership with leading robotics guage (ARCL) supports MobileEyes accidents are due to driver inatten- software companies and academic (interactive control), the MobilePlan- tion. Passive safety systems focus on research labs. The script language ner (mapping), and AR-Networking (a minimizing damage (e.g., airbags and brings parallelism, event-based pro- C++ API). Over the course of a day, seat belts). Active systems (e.g., driv- gramming, and distributed object the delivery service vehicle travels er warnings or collision avoidance) management via the UObject. URBI about 15 miles, saving precious steps can prevent an accident before it is also fully interfaced through Libur- for hospital personnel. happens. bi (GPL license) with C++, Java, Mat- The computing ecosystem contin- lab, Python, Ruby, and many other CONVERSATIONAL ROBOTS ues its expansion from a tethered languages. This one is out there. Hanson universe toward full autonomy (see URBI represents the present direc- Robotics is a company that special- Figure 2). Government-sponsored tion of robotics. This is an attempt to izes in near-human facial animatron- programs like the ics and holds a patent for a structured DARPA challenge porosity elastomer, aka “Frubber” have caused organi-

(www.hansonrobotics.com). It mimics zations to push Untethered Mobile appliances Tethered Laptop PCs Autonomous vacuums real facial tissues better than existing technology to new Desktop computers Cell phones Security/telepresence Wireless telephones GPS devices Toys compounds, thereby reducing the limits. Figure 3 Cable TVs PDAs Cars power required to muscle a subtle shows a DARPA expression. WWW.GiURUMELE.Hi2.ROvehicle’s array of Beauty is only skin deep, however, awareness sensors.

so special AI software can give an Our military’s Tethered android the ability to carry out a con- future combat sys-

versation (see Photo 8). A big part of tems (FCSs) group is Untethered the total package is to have the already planning to android track its subject via a vision have one-third of all Mobile system. vehicles to be autonomous by Figure 2—Our computing ecosystem is centered on a basic tethered state. Wire- UNMANNED SYSTEMS 2015. less technology has cut our umbilical cords, but we are only beginning to move Idaho National Laboratory touted Electronic stability into the mobile (and autonomous) state. What comes next?

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 67 2710002-Bachiochi.qxp 9/6/2007 11:57 AM Page 68

hyper-agile mobility platform with dynamic balancing and a high- strength upper body. The humanoid form can carefully lift a payload up to 500 lbs, carry it over a distance, and safely set it down, as directed by its wireless operator. Although best known for its per- sonal transporter (PT)—the first two- wheeled, self-balancing, electric transportation device to use patented dynamic stabilization technology— Segway now offers a robotic mobility platform (RMP) that comes in two- or four-wheel versions (www.segway.com). The Segway RMP base is capable of producing 2 hp continuously (4- to 5-hp peak), and it is powerful enough to carry a human-sized payload. It can also carry a variety of battery and tire/wheel Photo 8—Dubbed “Frubber,” the prosthetic replacement goo comes close to real skin. The more human an android combinations for up to 15 miles (24 km) looks, the easier it is for us to fall under its spell. (Source: David Hanson, www.hansonrobotics.com) with a payload capability of up to 400 lb (181 kg). bring together (sometimes propri- intelligence. The core design for a Neuro Robotics displayed its Neuro etary) subsystems in a way in which robotics “thinking machine” is based Arm (www.neurorobotics.co.uk). The they can work together toward a on a new architectural concept (patent robot arm is a balanced design that common goal. It has been imple- pending), which is independent of a incorporates enough “base-level” mented on a number of platforms robotics hardware platform. mechanics, electromechanics, and and should continue to grow in popu- The Brainstorm is a complete learn- electronics to provide a flexible and larity (see Photo 9). ing/reasoning/cognitive software mod- powerful platform for the researcher, ule developed for UAVs in the educator, or product developer. It EVOLVING ROBOTIC MIND Swedish military. It is a byproduct of offers practical reach and payload per- The Institute of Robotics in Scandi- the continuing search for improved formance for real-world tasks, while navia was founded in 2006 with the technologies for autonomous intelli- specializing in human-robot interac- goal of turning research and work in gent systems (TAIS). It includes rea- tion safety. the evolving robotics industry into soning, reactive learning, modeling, Allen-Vanguard aims to build commercial products (www.irobis.com). and security functions. In addition to equipment that meets the practical The iRobis team provides mobile, being able to generalize large amounts needs of operators for working in vari- autonomous, and semiautonomous of data to simple laws, it has a built-in ous environments (www.allen-van robotics systems with advanced, high- simulator, dreamer, and fantasizer. It guard.com). The global supplier is ly organized, multilevel, and adaptive can learn physical properties, commu- known for an innovative portfolio of nication, and scene interpretation specialist equipment that meets the from a single image or video with gen- needs of clients and the problems eralization. It is also compatible with they face. The Vanguard is among the the Microsoft Robotics Studio.

THE EXPO FLOOR WWW.GiURUMELE.Hi2.ROWhile robotic platforms of the two-, three-, and more-wheeled variety are still emerging, the ability to grip, grab, and get was the central theme on the expo floor. Refer to Photo 10 (clockwise from the upper left) for a collage of photos I took of the follow- ing armed bots. Photo 9—A universal real-time behavior interface Figure 3—DARPA vehicles use multiple sensors to fix (URBI) supports a variety of robotic platforms. Two The largest robot on display was from their positions and avoid obstacles. While a GPS system companies, Neuroarm and iRobot, could be seen on can locate a position to within meters, long-, medium-, and Vecna Robotics. Its battlefield extrac- the expo floor. (Source: Jean-Christophe Baille, short-range sensors are necessary for obstacle avoidance. tion-assist robot (BEAR) combines a www.gostai.com)

68 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710002-Bachiochi.qxp 9/13/2007 11:11 AM Page 69

newest generation of high-risk use robots that can be used to respond to chemical, biological, radiological, nuclear, and explosive (CBRNE) threats. It can be used for HAZMAT, tactical, and surveillance operations. It has an advanced modular design (to facilitate easy field repair, which is a critical success feature for remote locations or distant combat threats) with a compact size/weight envelope that aids rapid deployment in all civil law enforcement and mili- tary scenarios. SCHUNK Intec—which is known for automation, tooling, and workhold- Photo 10—I took these photos of various arm technologies on the expo floor. There was a plethora of platform ing—displayed a modular, lightweight proposals to peruse. robotic arm (www.schunk.com). Four module sizes can be combined (as robots (e.g., Roomba) and several source of compressed air. You can read required) to provide an arm with up to hundred tactical robots are used more about this on the company’s web 7 degrees of freedom (DOF). Gripper around the world today. The PackBot site. styles are available in three- (dextrous) is now famous as a robust and reli- and four-finger (anthromorphic) hands. able product that makes life safer and ROBOTICS TRENDS iRobot, the founding sponsor of better for our troops. Enhanced track Robotics Trends, the show’s produc- RoboBusiness, had a large presence at technology and increased torque offer er, divides its robotic vision into mul- the show. Millions of iRobot’s cleaning more powerful maneuverability, tiple conferences. In 2008, RoboDevel- enhanced stair climbing, and agile opment will be held in Santa Clara, obstacle avoidance. CA, and RoboBusiness will move to Pittsburgh, PA. You can learn more LURKING ABOUT about these and other conferences at Everyone at the conference seemed www.roboticsevents.com. to be carting something around. There I can definitely see how the industry were cell phones, PDAs, laptops, and is beginning to work together. The vacuum cleaners. Wait? Vacuum “invented here” philosophy is slowly cleaners? This person doesn’t look falling by the wayside as companies like Hyne’s maintenance personnel. find that they can bring a product to Was this Mr. Dyson? No, it’s the market faster by sharing their expert- Shadow (www.shadowrobot.com). A ise. The approach to standardizing all closer look identified the vacuum aspects of the robotics industry will cleaner as a robotic arm nicely dis- make it easier for manufacturers to played in a rolling display case. The succeed at this in the future. Robotics arm, however, was nothing like its is the future. The only question is, robotic counterparts displayed on the how close to the future are we? I expo floor. The dexterous Shadow hand shown in Photo 11 mimics the muscular sys- Jeff Bachiochi (pronounced BAH-key- tem of the human hand. Instead of AH-key) has been writing for Circuit WWW.GiURUMELE.Hi2.ROlots of motors, the Shadow hand con- Cellar since 1988. His background tains an integrated bank of 40 air includes product design and manu- muscles, which make it move. The facturing. He may be reached at muscles are compliant, which enables [email protected] or the hand to be used around soft or www.imaginethatnow.com. fragile objects. It can be fitted with touch sensing on the fingertips, offer- Photo 11—The Shadow’s hand muscles are actually ing sensitivity sufficient enough to RESOURCE air bladders located in the forearm. Tendons from each detect a small coin. The Shadow uses bladder tug on their respective joints. Sensors across RoboBusiness Conference & Expo, the fingertips give pressure feedback. (Source: air muscle technology, so the system Boston, MA, May 15 to 16, 2007, www.shadowrobot.com) requires both electric current and a www.roboevent.com.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 69 2710005lacoste.qxp 9/4/2007 4:14 PM Page 70

THE DARKER SIDE by Robert Lacoste No Fear with FIR Put a FIR Filter to Work Working with finite impulse response (FIR) filters isn’t black magic. Robert covers the basics and touches on the mathematical concepts you’ll need to understand in order to put a FIR filter to work.

Welcome to the darker side! skip to the “FIR for You” section! to “real” signals (as opposed to Fourier Because this month’s theme is signal transforms of complex numbers), and for processing, I scratched my head to BACK TO BASICS easier reading, I will skip a number of find the best subject for this column. I Before digging into the topic of FIR implementation details, which are post- wanted something that would be more filters, let’s start by refreshing our ed on the Circuit Cellar FTP site. than useful for your applications, rea- neurons on the Fourier transform. As Suppose that you worked on some sonably easy to use, and still a little you may have noticed (even after the kind of digitizer and got 1,024 samples magical. It also had to be a subject talented Circuit Cellar editors correct- of a real-life signal in RAM with a that I could easily explain in a few ed my approximate English), I’m not a sampling rate of 250 ksps. As you pages. I think I found the perfect can- U.S citizen. I’m French. So, I can’t know, the sampling rate limits your didate. In this column, I’ll describe a resist telling you that Jean Baptiste knowledge about the signal to fre- well-known and very powerful class of Joseph Fourier (1768–1830) was a quencies below the Nyquist limit: digital filters: finite impulse response French mathematician and physicist. 250 ksps filters, or FIR for short. His life was quite busy. He was deeply 125 kHz = [1] As usual, I will use plain English to involved in the French Revolution and 2 explain the concepts, but some mathe- kept his head on his shoulders only by A DFT takes the 1,024 time domain matical concepts will still appear from chance. He then went with Napoleon samples and converts them into their time to time. However, I will try to during his expeditions and became gov- frequency domain representation, stay as close to the bench as possible. ernor of Lower Egypt. Later, he returned from DC to 125 kHz, with a frequency So, don’t be afraid, breathe normally, to Europe and to science and published resolution of: and keep reading. If you get lost, just his well-known paper on thermodynam- 250 kHz ics in 1822, which brings us 244.14 Hz = [2] 1, 024 Imaginary axis back to our subject. In the paper, Fourier claims that any So, you started with 1,024 samples b (Quadrature function of a variable can be and you got only 512 frequency bins phase amplitude) expanded in a series of sines of (i.e., 125,000/244.14). Why half the A.Cos (ωt - ϕ) = a.cos(ωt) + b.sin (ωt) multiples of the variable. This number of samples? The trick is that

litude) p transformation was later the outputs of the DFT are not real WWW.GiURUMELE.Hi2.ROnamed the Fourier transform. numbers. They are complex numbers A (Signal am There are books just on the with two components for each frequen-

ϕ (Phase) mathematical theory behind the cy. A complex number is equivalent to concept, but I will focus on the a magnitude and also to a phase (see Real axis a “engineer’s view.” For an engi- Figure 1). What does it mean? The DFT (In-phase amplitude) neer, a function is usually a operation transformed your 1,024 time- Figure 1—Don’t be afraid of complex numbers. They have two table of discrete numbers, so I domain digitized samples into a sum of coordinates (a and b), and they are usually represented as a + ib will never use the real Fourier 512 sinusoidal signals with respective or a + jb. It is a convenient way to represent a given sinusoidal transform. I will use its dis- frequencies of 0 (DC value), 244.14 Hz, function with an amplitude A and phase ϕ. The representation can crete time equivalent, the dis- 488.28 Hz, 732.42 Hz, and so on, up to be either a single point on the complex plane or the sum of its in- phase and quadrature-phase coordinates. If you love math, just crete Fourier transform (DFT). I 125 kHz, each with a given amplitude remember that cos(a – b) = cos(a)cos(b) + sin(a)sin(b). will also restrict my presentation and a given phase. It is important to

70 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710005lacoste.qxp 9/4/2007 4:14 PM Page 71

understand that this is not A simple eight-point signal DFT decomposition and sum of sines Original and recomposed signals compared an “approximation,” it is 5 5 5 just another way to see the same signal. The best proof 4 4 4 is that the DFT has its recip- rocal, the inverse discrete 3 3 3 Fourier transform (IDFT), which returns your original 2 2 2 signal from its spectral rep- resentation. And, an IDFT 1 1 1 is nothing more than a DFT, just a different scaling 0 0 0 factor somewhere. Why not experiment? -1 -1 -1 You may be familiar with tools like MATLAB, but all -2 -2 -2 of the examples presented in this article were done -3 -3 -3 with Scilab, which is a similar tool. Scilab is open- -4 -4 -4 source. I love it just 012345678 0 102030405060708090 0 102030405060708090 because it works under the OS of your choice, it is sup- Figure 2—This is the output of Listing 1 when run in Scilab. The left-most graph is the original signal, an arbitrary signal defined on eight points. The middle graph shows the four sinusoidal components calculated by the FFT in green, with frequencies 1/T, 2/T, 3/T, plied with plenty of com- and 4/T. T is the duration of the signal, as well as its sum (in red). Lastly, on the right, the superposition of the original signal and its patible toolboxes for signal recomposition show that there is a perfect match on each of the signal points. processing and graphics, and it is free (www.scilab.org). Listing 1 the signal as a sum of sines. Figure 2 fast Fourier transform (FFT) algorithm. is a short Scilab script, which actually is the output. This is just the common and efficient decomposed a very short signal in its Just a word on the calculation way to calculate a DFT on a computer; Fourier coefficients and reconstructed method. The examples use an optimized it is not a new concept. Basically, an FFT gives the same result as a DFT, but it requires n.log(n) and not Sine signal FFT of sine 2 1.0 300 n operations. It’s a great advan- 0.8 tage when n starts to get large. 0.6 250 0.4 200 Some Fourier transforms of 0.2 0.0 150 simple signals are illustrated -0.2 -0.4 100 in Figure 3. Take a look at -0.6 50 them to get a feeling for a fre- -0.8 -1.0 0 quency spectrum. 0 100 200 300 400 500 600 0 50 100 150 200 250 300 Square signal FFT of square 1.0 350 FREQUENCY DOMAIN 0.8 300 0.6 Thanks to the Fourier trans- 0.4 250 form, you can convert a time- 0.2 200 0.0 domain signal into its frequen- -0.2 150 -0.4 100 cy spectrum. This will give -0.6 50 -0.8 you a first straightforward -1.0 0 0 100 200 300 400 500 600 0 50 100 150 200 250 300 method and introduction to WWW.GiURUMELE.Hi2.ROImpulse signal FFT of impulse implementing digital filters. 1.0 2.0 0.9 1.8 Filtering a signal is just 0.8 1.6 modifying its frequency spec- 0.7 1.4 0.6 1.2 trum, attenuating or enhanc- 0.5 1.0 0.4 0.8 ing the subbands you are inter- 0.3 0.6 0.2 0.4 ested in. That’s really easy 0.1 0.2 with a DFT with a three-step 0.0 0.0 0 100 200 300 400 500 600 0 50 100 150 200 250 300 process: DFT, filter, and IDFT. With this method, if you Figure 3—The Fourier transform of a sinusoidal signal is just one frequency on the spectrum where the spectrum of a square signal contains all odd harmonics of the original frequency. Finally, a very interesting case. If the input signal is a signal pulse want to implement a low-pass (input signals are all at 0 except one sample at 1), then the output spectrum is flat, with all frequencies at the same amplitude. filter, the first step is to take

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 71 56-57.qxp 7/2/2007 10:52 AM Page 1

WWW.GiURUMELE.Hi2.RO 56-57.qxp 7/2/2007 10:52 AM Page 2

WWW.GiURUMELE.Hi2.RO 2710005lacoste.qxp 9/4/2007 4:14 PM Page 74

your input time-domain signal and cal- Listing 1—This short Scilab script defines an eight-point arbitrary signal, calculates its Fourier transform, culate its Fourier transform. The sec- extracts the amplitude and phase of each sinusoidal component, and allows it to verify (on a graph) that the ond step is to remove all components original signal and its recomposition are identical (see Figure 2). above the wanted cutting frequency // from its spectrum, which can be easily // FFT of a very small signal and the corresponding decomposition done by multiplying term by term, the // spectrum, and a rectangular frequency mask equal to 1, from DC up to the cut- // Just take an eight-point signal signal=[4.4 2.3 -3.5 -1.2 -2.8 2.0 1.6 2.5]; ting frequency, and then null. You now have a filtered spectrum and you can get // Plot it in a 3-box graph, with rollover of the last to first point back to a filtered time-domain signal by subplot(1,3,1); plot(signal,’black’); the third step, an inverse Fourier trans- xtitle(‘A simple eight-point signal’); form. So, for those of you who like equa- // Calculate its Fourier transform, giving eight complex numbers tions, if S is the signal and M is the spectrum=fft(signal); wanted frequency response, then the filtered signal S′ is given by: // However, as the input signal is real then only the first half // of the FFT is actually useful (the last half is the complex // conjugate of the first half) : S ′= IDFT( DFT() S × M) [3] usefulspectrum=spectrum(1:$/2+1);

This is illustrated in Figure 4 and in // Calculate amplitudes and phases of all frequency bins amplitudes=abs(usefulspectrum)/8; the accompanying Scilab source code. phases=imag(log(usefulspectrum)); The real strength of the method is that virtually any linear filter can be // First amplitude is the DC value of the signal (phase is always 0) implemented with the same algo- f0=amplitudes(1); rithm. You are not limited to simple // Then generate the sinusoidal waves for the harmonics 1, 2, 3 and filters, such as low-pass filters. Noth- // 4. Each should be doubled because there is a complex conjugate ing forbids you from designing a more // partner in the second half of the fourier transform except the complex filter with several subbands // last one (which is real) x=2*%pi*(0:80)/80; // calculate it on 80 points and a different behavior in each sub- f1=2*amplitudes(2)*cos(x+phases(2)); band. You just have to design a frequency f2=2*amplitudes(3)*cos(2*x+phases(3)); mask accordingly. The calculations will f3=2*amplitudes(4)*cos(3*x+phases(4)); be the same and you will also be able to f4=amplitudes(5)*cos(4*x+phases(5)); modify that filter very easily. // The signal is the sum of the DC value and all harmonics f=f0+f1+f2+f3+f4; FROM FREQUENCY TO TIME subplot(1,3,2); plot(f1,’green’); plot(f2,’green’); plot(f3,’green’); The frequency domain filtering plot(f4,’green’); plot(f,’red’); xtitle(‘DFT decomposition and sum of sines’); method using a DFT and an IDFT is great and it is effectively used, but it // Compare original signal and recomposition has two problems. The first is that a subplot(1,3,3); plot(f,’red’); plot2d([0:7]*10+1,signal); DFT (or IDFT) requires a significant xtitle(‘Original and recomposed signals compared’), halt(); amount of processing power and mem- xdel(); ory. The second is that the process is block oriented. You must wait until you have a full buffer of data before cal- tiplications and additions. (Refer to called the impulse response of the fil- culating its DFT. This introduces a long the pseudocode in Figure 5.) Based on ter. Figure 4 shows the IDFT of the delay in processing, as well as difficul- the result, trust me (or demonstrate it spectrum mask on the middle-left box. ties on the block’s boundaries, requiring yourself, it’s easy), the method I have That is an IMP. complex windowingWWW.GiURUMELE.Hi2.RO techniques if you described for frequency domain filters So, with this method, the filtering want to filter a continuous signal. can be done without a DFT or an operation is now only based on time- Can it be simpler? Yes, but this will IDFT. The filtered signal S′ can be cal- domain signals. You just have to calcu- unfortunately require a very powerful culated by a convolution between the late the convolution of the signal to be mathematical result. If you have two original signal S and a new signal IMP. filtered and the impulse response of the signals A and B, then: And IMP is simply the IDFT of the desired filter. Of course, because the fre- frequency mask that you want to quency mask is a finite length table, the IDFT( DFT() A × DFT() B) =⊗ A B [4] implement. Physically speaking, an impulse response calculated as its IDFT What is this crazy ⊗? It is what IMP is the signal on the output of the is also finite. The impulse response is mathematicians call a convolution. It filter when a short impulse is applied time-limited. That’s why the algorithm is nothing more than a couple of mul- on its input. That’s why an IMP is is called a FIR. The main point here is

74 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710005lacoste.qxp 9/4/2007 4:14 PM Page 75

FFT of original signal Original signal 100 2.0 90 1.5 80 1.0 70 60 0.5 50 0.0 40 -0.5 30 -1.0 20 10 -1.5 0 -2.0 0 50 100 150 200 250 0 20 40 60 80 100 120 140 160 180 200 220 Filter in the frequency domain Impulse response of filter 1.0 60 0.9 50 0.8 40 0.7 0.6 30 0.5 20 0.4 10 0.3 0 0.2 0.1 -10 0.0 -20 0 102030405060708090100 0 50 100 150 200 250 Filtered spectrum FFT on the filtered spectrum 100 250 90 200 80 150 70 100 60 50 50 0 40 30 -50 20 -100 10 -150 0 -200 0 102030405060708090100110 0 20 40 60 80 100 120 140 160 180 200 220

Figure 4—A low-pass filter can easily be constructed in the frequency domain. The first line shows a test signal synthesized as a sum of two sines, both in the time and fre- quency domains. The second line shows a low-pass rectangular frequency mask, as well as its Fourier transform, the impulse response. The last line shows the multiplication of the spectrum, the frequency mask, and its inverse Fourier transform, which is the filtered signal.

that the IMP signal can be precalculated ly be the clock frequency of your than the maximum frequency of the (with an IDFT) when you design your fil- ADC. This task may sound trivial, but input signal. However, this would ter. The real-time calculation of the fil- it is often the most important step in require a perfectly sharp antialiasing ter then doesn’t need the DFT at all. the design process. And, this is not an low-pass filter with 100% transfer up If you have been following me so easy step, so I will spend a little time to the cutoff frequency and then 100% far, you should see that the FIR algo- on it. As you know, thanks to attenuation, which doesn’t exist any- rithm gives exactly the same result as Nyquist, the sampling frequency where else other than in the minds of the frequency domain digital filtering should be at least two times higher mathematicians. In real life, the defi- process we discussed first (Fourier transform, then multiplying the fre- quency spectrum by a filter mask,

then inverse Fourier transform). This Input signal (S) is not another method, just a far more effective implementation, especially Sum( x x x x x x x x x x x ) for time-continuous signals. WWW.GiURUMELE.Hi2.ROFigure 5—A convolution between Impulse response (I) two signals is calculated as N FIR FOR YOU multiplications and one big addi- You should now have an idea of tion for each output sample. N is where a FIR filter comes from. Let’s the shortest length of the two Filtered signal (S’) input signals, usually the impulse stop focusing on the theory and see response. For each output sam- what you will actually have to do to ple, the impulse response is shift- implement a FIR digital filter in your Pseudo code ed and aligned with the last N samples of the input. The two sig- next design. It will be an easy, seven- For each new sample S(n): T = 0 nals are then multiplied term by step process (see Figure 6). For i = 0 to N-1: term, and all of the results of the T = T + S(n-i) × I(i) multiplications are summed. The first step is to define the overall S′ (n) = T sampling frequency, which will usual-

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 75 2710005lacoste.qxp 9/4/2007 4:14 PM Page 76

than 5.12 Msps! Of course, better filters low-pass filter with an “easy” cut-off Select the sampling rate will enable you to limit the require- frequency somewhere in the middle of ment. For example, a six-pole filter will the passband, an eight-tap FIR filter provide an attenuation of 36 dB/octave, may be enough. However, if you need Define the frequency reponse which will enable you to use a sam- a band-pass of 1/100 of the frequency pling rate of 50 ksps, but that is still band, you will need significantly more Select the filter length far above the theoretical 20 ksps that than 100 taps (possibly 500 or more). some engineers would have used (see Figure 9 illustrates the frequency

Synthesize the filter Figure 7). Even with very good response of a simple low-pass filter for antialiasing filters and modest require- different numbers of taps. For a cus- ments (8 bits), the sampling frequency tomer who wants a razor filter, select Simulate the filter should be significantly above the dou- a 200-tap filter or more. ble of the input signal frequency, and it may be 10 times higher if you want SYNTHESIS! N Y Satisfactory? to use simple filters. This is why over- The fourth step is the magical one: sampling is so often a good engineer- the synthesis of the FIR filter. Magical,

Implement it! ing solution. Think about it for your but understandable after the first part next project! of this article. The synthesis of the Figure 6—The implementation of a FIR filter in your The second step in the FIR design FIR filter means that you need to cal- project is a seven-step process. The key is to spend as process is far easier and quite fun. It culate the coefficient of each tap. The much time as required in the simulation steps in order to consists of defining the theoretical fre- coefficients are the values of the be 99% sure that the filter will do what you want it to do. quency response that you would dream inverse Fourier transform of the fre- to have. Take a sheet of paper and draw quency response. Remember: IMP is nition of the sampling frequency will a frequency scale from DC to the the IDFT of the frequency mask M. In be a difficult cost balance between an Nyquist frequency (half the sampling order to calculate them, you need a expensive antialiasing filter and an frequency) and draft the desired filter tool like SciLab to create a table with expensive, quick ADC and digital fil- response. Assume that you need a com- as many points as the number of taps ter. Still not convinced? Take a plex filter like the one in Figure 8. The to fill its first half with the frequency numeric example. Suppose that you first box is a filter with two passbands response from DC to the Nyquist fre- need a perfect 8-bit digitization of a with respective gains of one and two. quency and to duplicate it upside DC-to-10-kHz signal. Easy isn’t it? The third step involves defining the down in the second half. (Refer to the However, you want to get 8 bits of number of taps of the FIR filter. This is second plot in Figure 8.) The duplica- precise measurement, so avoid spuri- often a trial-and-error process, but you tion is just because the inverse Fourier ous signals with amplitudes higher will have a starting point. Remember our transform assumes that the input fre- than one least significant bit. This discussion about frequency domain fil- quencies are both positive frequencies means that the antialiasing filter ters? Because the FIR taps are calculated and negative ones (trust me). Then, should reduce out-of-band signals to from the frequency mask through an call the inverse Fourier transform levels 256 times lower than the ampli- inverse Fourier transform, the number of function and you get the impulse tude of the desired signal. In terms of taps of the filter is equivalent to the response of the filter, which is the power, because power is the square of number of bins on the frequency mask. coefficient of each successive tap of the voltage, the rejection of the So, the more complex the target frequen- the FIR filter. (Refer to the third plot antialiasing filter should be better cy response, the higher the tap count. For in Figure 8.) than 1/65,536 above the Nyquist example, if you want to design a crude Mathematically speaking, the filter limit, which is: ⎛ 1 ⎞ 10 × log =− 48 dB Power Figure 7—This selection of the overall sam- ⎝⎜ 65,536⎠⎟ [5] pling frequency is a cost-optimization process 0 dB between an ADC and an antialiasing filter. For Do you plan WWW.GiURUMELE.Hi2.ROto use a simple first- example, to get an 8-bit spurious free-resolu- order RC filter? The filter provides an tion on a 10-kHz signal, the filter rejection above the Nyquist limit should be better than attenuation of only 6 dB per octave, 48 dB, which translates into a Nyquist frequen- meaning 6 dB each time the frequency cy above 30 kHz even with a good fifth-order is doubled above the cutting frequency. Band of interest antialiasing filter giving 60 ksps. Fourth To get 48 dB, you will need to double order First Second order the frequency eight times. This means Fifth Third order order order that the Nyquist frequency should be: –48 dB 10 kHz ×= 28 2.56 MHz [6] 10 kHz 40 kHz 63 kHz 160 kHz 2.56 MHz Frequency The sampling rate should be no less 30 kHz

76 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710005lacoste.qxp 9/4/2007 4:14 PM Page 77

2.0 1.8 1.6 1.4 1.2 1.0 0.8 0.6 0.4 0.2 0.0 0 20 40 60 80 100 120 140 160 180 200 2.0 1.8 1.6 1.4 1.2 1.0 0.8 0.6 0.4 0.2 0.0 0 20 40 60 80 100 120 140 160 180 200 120 100 80 60 40 20 0 -20 -40 -60 -80 0 20 40 60 80 100 120 140 160 180 200 450 400 350 300 250 200 150 100 50 0

Actual transfer function 0.00 0.05 0.10 0.15 0.20 0.25 0.30 0.35 0.40 0.45 0.50

Figure 8—This figure is the output of Listing 2. From top to bottom, it shows the desired frequency response, the frequency response extended in negative frequencies, its inverse FFT, which is the impulse response of the filter (i.e., the coefficient of the FIR filter), and the actual simulated frequency response.

will be perfect. The actual response could enable you to optimize the filter will be the exact specified response at for a given number of taps and for a each of the N discrete frequencies given list of mandatory setpoints on used to define it, from DC to 10 kHz the frequency response graph. The with a step of 50 Hz (i.e., 10 kHz/200) techniques limit the oscillations of in my example. However, in real life, the frequency response between the it is also very important to know how setpoints by using windowing and the filter will behave for frequencies optimization algorithms. One of them, between these individual frequencies, using the Minimax algorithm, is sup- especially if the tap count is small. ported in Scilab through the eqfir This is the fifth step: simulation. You function. You will find an example of can do the simulation yourself with it in the code posted on the Circuit test software in your preferred lan- Cellar FTP site. This was the method guage, but it will need you to generate used for the examples in Figure 9. sine signals of slowly increasing fre- Now that you have a simulated quencies to filter it with the synthe- response of the FIR filter, it’s time to sized FIR and then to measure and compare it to the specifications you plot the output amplitude for each fre- were looking for. Is it fully satisfacto- quency. Simple, but painful. The other ry? If not, you will have to reiterate solution is to useWWW.GiURUMELE.Hi2.RO a ready-made fre- the entire process of taking different quency-response analysis function assumptions, which is the sixth step available in SciLab: frmag. The entire of the design process. You will proba- synthesis and simulation code in bly need to tweak the number of taps Scilab is in Listing 2. The actual out- or optimize the frequency response a put is in Figure 8. The bottom plot is couple of times. the actual response, which is very close to the theoretical one because TIME TO SOLDER the number of taps is high. The last step is the easiest one. I must mention that there are more Select your preferred digital platform. elaborate synthesis techniques that You can use a microcontroller for low-

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 77 2710005lacoste.qxp 9/4/2007 4:14 PM Page 78

speed applications, a DSP Minimax FIR, ntaps=8 0.5 1.1 1.2 for medium-speed projects, 0.4 1.0 1.0 0.3 or an FPGA with plenty of 0.2 0.9 0.8 hardware multipliers for 0.1 0.8 0.6 0.0 0.7 0.4 high-end ones. Code the FIR FIR coefficients -0.1 -0.2 0.6 0.2 FFT of FIR coefficients algorithm, which should -0.3 0.5 Actual transfer function 0.0 012345678 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 0.000.050.100.150.200.250.300.350.400.450.50 need only a couple of source Minimax FIR, ntaps=16 0.5 1.1 1.2 code lines and some non- 0.4 1.0 0.9 1.0 volatile memory to store the 0.3 0.8 0.8 0.2 0.7 FIR coefficients. To make 0.6 0.6 0.1 0.5 0.4 0.4 your life easier, a skeleton of FIR coefficients 0.0 0.3 0.2 -0.1 0.2 FFT of FIR coefficients a FIR algorithm coded in C -0.2 0.1 Actual transfer function 0.0 0 5 10 15 20 012345678 0.000.050.100.150.200.250.300.350.400.450.50 language is posted on the Minimax FIR, ntaps=32 0.5 1.1 1.2 Circuit Cellar FTP site. 1.0 0.4 0.9 1.0 Your FIR filter should 0.8 0.3 0.7 0.8 0.6 work well as soon as you 0.2 0.5 0.6 0.1 0.4 0.4 have corrected the usual FIR coefficients 0.3 0.0 0.2 0.2

FFT of FIR coefficients 0.1 bugs (at least if you haven’t -0.1 0.0 Actual transfer function 0.0 0 5 10 15 20 25 30 35 0 5 10 15 20 0.000.050.100.150.200.250.300.350.400.450.50 forgotten a good antialias- Minimax FIR, ntaps=128 ing filter on your PCB). 0.5 1.2 1.2 It is possible to perform 0.4 1.0 1.0 0.3 0.8 0.8 signal processing on a 0.2 0.6 0.6 0.1 0.4 0.4

microcontroller, and FIR in FIR coefficients 0.0 0.2 0.2 FFT of FIR coefficients particular. A reasonably Actual transfer function -0.1 0.0 0.0 complex 32-tap FIR filter 0 20 40 60 80 100 120 140 0 10203040506070 0.000.050.100.150.200.250.300.350.400.450.50 needs 32 multiplications and 32 additions per sam- Figure 9—The optimized impulse response and the theoretical and actual frequency response of low-pass filters with 8, 16, 32, and 128 taps, respectively. Of course, the filter response is better and better with higher tap counts, but at the expense of increased computations. pling cycle, usually done on 16-bit integer numbers. If you are clever, you will notice that the microcontroller, make sure you use one 40 ksps or more. So, digital filters are impulse response is always symmetrical, with an on-chip 8 × 8 bit hardware not only for high-end applications. which could enable you to divide the multiplier (e.g., a PIC18F). You then I hope I have convinced you that number of multiplications by two. Any- should be able to implement such a FIR filters are not black magic, even if way, even if you select an 8-bit 10-MIPS FIR filter with sampling rates up to they are sometimes on the darker side. Try them in your next project! I Listing 2—This Scilab script is the complete code needed to synthesize and simulate a FIR filter. The actual output of the code is in Figure 8. Robert Lacoste lives near Paris, France. He has 18 years of experience working //------on embedded systems, analog designs, //Custom complex filter and wireless telecommunications. He //------// Specification of the desired frequency response has won prizes in more than 15 interna- ntaps=200; tional design contests. In 2003, Robert wanted(1:ntaps)=0; started a consulting company, ALCIOM, wanted(10:20)=1.0; wanted(40:60)=2.0; to share his passion for innovative subplot(4,1,1); mixed-signal designs. You can reach him plot(wanted); at [email protected]. Don’t forget to // Invert it in the second half (negative frequencies) write “Darker Side” in the subject line for i=1:ntaps/2;wanted(ntaps-i+1)=wanted(i);end; subplot(4,1,2);WWW.GiURUMELE.Hi2.ROto bypass his spam filters. plot(wanted); // Calculate its FFT, which is the impulse response fircoeff=real(fftshift(fft(wanted))); PROJECT FILES subplot(4,1,3); To download code, go to ftp://ftp.circuit plot(fircoeff); // Calculate the actual frequency response cellar.com/pub/Circuit_Cellar/2007/207. [hm,fr]=frmag(fircoeff,1000); subplot(4,1,4); plot2d(fr’,hm’); SOURCE xtitle(‘’,’’,’Actual transfer function’); Scilab software halt(); xdel(); INRIA www.scilab.org

78 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 79.qxp 9/6/2007 12:50 PM Page 1

WWW.GiURUMELE.Hi2.RO 2710003-Cantrell.qxp 9/4/2007 5:02 PM Page 80

SILICON UPDATE by Tom Cantrell

I Sense, Therefore I Am As Tom has said in the past, “Sensors are as key to embedded control applications as the controllers themselves.” Read on to learn about the hot new sensor technologies that he encountered at the 2007 Sensors Expo in Chicago.

As West Coast editor, I usually find book computer (fall/theft detection), balance back in the digital direction. plenty to write about close to home. and even toys (Nintendo Wii). Keeping in mind that I don’t have a But I’ll hit the road when duty, and I covered the new-age, three-axis real datasheet, judging from the press technology, calls. So it was on my MEMS accelerometers a little more pack, the ’7450L also smartens up to recent trip to Chicago for the 2007 than a year ago (“Three-Axis better serve the novel applications Sensors Expo. Hey, it’s the “West Foursome,” Circuit Cellar 191, 2006), mentioned earlier with features like Coast” of Lake Michigan. but second-generation parts are programmable threshold and offset cal- Actually, I hadn’t been to the already being introduced that reflect ibration, single- and double-click detec- Sensors Expo for a few years, and I last the latest application trends. tion, and low-power (5-μA) Standby covered it way back in 2002 (“Sensors The new Freescale Semiconductor mode with free-fall alarm interrupt. and Sensibility,” Circuit Cellar 148). MMA7450L is a three-axis part with a When it comes to packaging, tradi- In the old days, the Expo used to selectable g-range (2/4/8 g) similar in tionally it’s “board space” (i.e., x and y rotate locations through various cities, most respects to last year’s parts, but dimensions) that matters most, and including ones on the real West Coast. with the notable difference of providing the ’7450L consumes just 3 × 5 mm of But for the past few years, it’s stayed a digital interface rather than an analog precious PCB real estate. But, these in Chicago. If the show won’t come to voltage output (see Photo 1). And “digi- days, with anorexic gadgets like iPods Tom, Tom’s going to the show. tal” in this case means a real SPI and I2C and cell phones all the rage, thin is As I’ve always said, sensors are as key interface, not the dumb “duty/cycle” also in. Freescale puts the ’7450L on a to embedded control apps as the embed- output of older parts. Ironically, it was diet by laying the two dice under the ded controllers themselves. What good the cumbersome nature of that “duty hood (MEMS pendulum and CMOS is an MCU without any input to work cycle” scheme, not to mention the pro- logic) next to each other instead of with? The development of new sensors liferation of ADC-equipped MCUs, stacking them, thereby cutting the fat plays a pivotal role in growing the which have enabled analog output (i.e., thickness) to a mere 0.8 mm. embedded business by cutting the costs accelerometers to hold their own. I sus- of existing applications and, better yet, pect the emergence of smarter and easi- TOUCH ME enabling totally new ones. er-to-interface digital units like the Look no further than the aforemen- A classic example is the MEMS ’7450L will, pardon the pun, tilt the tioned iPods and cell phones to see accelerometer. Originally, these were another major trend, the switch away designed simply to reduce the cost of from switches. automotive airbag systems, which Now, don’t get me wrong. they did quite WWW.GiURUMELE.Hi2.ROhandily. That’s why Mechanical switches and buttons still today even an econobox has more bal- have their place, notably when it loons than a birthday party, and we’re comes to delivering power or routing a all the safer for it. But beyond airbags, signal. But, for basic user interfaces, the technology evolved (i.e., low-g capacitive touch sensors have funda- units) to grow the market far beyond mental reliability and cost advantages expectations with unforeseen applica- over their mechanical counterparts. tions. Nowadays you’re just as likely After all, when your “switch” is just a Photo 1—Thanks to the creativity of designers able and to find an MEMS accelerometer in pad on a PCB, what can go wrong? willing to think outside the box, MEMS accelerometers, your toolbox (e.g., electronic level), such as the Freescale MMA7450L, now serve a myriad Actually, plenty. The capacitive cell phone (tilt user interface), note- of applications far above and beyond their airbag roots. switch itself isn’t the problem, but

80 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 81.qxp 8/30/2007 9:12 AM Page 1

NINETEEN CONSECUTIVE YEARS

A complimentary coast-to-coast technology exhibition

Join Arrow experts, manufacturers, and industry professionals at this free coast-to-coast technology exhibition where you will learn about the latest products, solutions, and developing technologies while building valuable business relationships.

Visit the Arrow services booths and speak with Arrow representatives and engineers regarding the following innovative technical solutions and services: • Arrow Consulting Engineering Services • Custom Logic Solutions • Supply Chain Solutions • Power Supplies Solutions • TestdriveSM Tool Evaluation Program • Arrowdevtools.com™ Development Tool E-Store • Global Programming • Embedded Computing Solutions • Lighting Solutions • Arrow Technical Solutions Forums • ARM® Solutions • …and More

Visit WWW.ARROWFEST.COM for the latest []listing of seminars at a location near you!

Enjoy Arrowfest’s informal atmosphere: • Face-to-face networking • Technical seminars relevant to your local marketplace 2007 • Up to 65 manufacturer booths • Demonstrations of the latest products and solutions • Festivities, music, giveaways, and food

Arrowfest 2007WWW.GiURUMELE.Hi2.RO Locations and Dates Orange County Philadelphia Minnesota Chicago Silicon Valley Portland Dallas Boston Phoenix 08/23 09/06 09/13 09/20 10/04 10/11 10/18 10/25 11/01

To register for Arrowfest or to get more details, visit www.arrowfest.com 49.qxp 8/7/2007 8:59 AM Page 1

USB Mixed Signal Oscilloscope

Inventing the future requires a lot of test gear... Analog + Digital ...or a BitScope Digital Storage Oscilloscope NEW Dual Channel Digital Scope with industry 9 standard probes or POD connected analog MODEL inputs. Fully opto-isolated. Mixed Signal Oscilloscope Capture and display analog and logic signals 9 together with sophisticated cross-triggers for precise analog/logic timing. Multi-Band Spectrum Analyzer Display analog waveforms and their spectra 9 simultaneously. Base-band or RF displays with variable bandwidth control. Multi-Channel Logic Analyzer Eight logic/trigger channels with event capture 9 to 25nS. BS100U Mixed Signal Storage Scope & Analyzer DSP Waveform Generator Innovations in modern electronics engineering are leading the new wave of Built-in flash programmable DSP based function inventions that promise clean and energy efficient technologies that will 9 generator. Operates concurrently with waveform change the way we live. and logic capture. It's a sophisticated world mixing digital logic, complex analog signals and Mixed Signal Data Recorder high speed events. To make sense of it all you need to see exactly what's Record to disk anything BitScope can capture. going on in real-time. 9 Supports on-screen waveform replay and export. BS100U combines analog and digital capture and analysis in one cost User Programmable Tools and Drivers effective test and measurement package to give you the tools you need to Use supplied drivers and interfaces to build navigate this exciting new frontier. 9 custom test and measurement and data acquisition solutions.

Standard 1M/20pF BNC inputs Smart POD Connector Opto-isolated USB 2.0 12VDC with low power modes

BitScope DSO Software for Windows and Linux BS100U includes BitScope DSO the fast and intuitive multichannel test and measurement software for your PC or notebook. Capture deep buffer one-shots, display waveforms and spectra real-time or capture mixed signal data to disk. Comprehensive integration means you can view analog and logic signals in many different ways all at the click of a button. The software may also be used stand-alone to share data withWWW.GiURUMELE.Hi2.RO colleagues, students or customers. Waveforms may be exported as portable image files or live captures replayed on another PC as if a BS100U was locally connected.

www.bitscope.com 2710003-Cantrell.qxp 9/4/2007 5:02 PM Page 83

without the headaches. Both of these chips incorporate an ACSHIELD VCC GND BIAS 8 11 10 9 Both Analog Devices and MCU alongside the radio, but each

CIN0 19 Power-on Freescale were showing company’s choice delivers a decidedly CIN1 20 reset logic new touch controllers at different option for designers. The TI

CIN2 21 Excitation the Expo (see Figure 1). CC2431 integrates an IEEE 802.15.4 CIN3 22 source On one side you put your radio with a lean and mean 8/16-bit Calibration CIN4 23 RAM touchpad layout compris- controller that is primarily suited for CIN5 24 ing buttons, sliders, scroll radio housekeeping. By contrast, the CIN6 1 16-Bit Calibration Σ−Δ wheels, and the like. On Freescale MC13224 is a multichip CIN7 2 engine

matrix 2 Switch CDC the other is a simple I C module that combines the radio with CIN8 3 or SPI to your favorite a fully-loaded 32-bit MCU (128 KB of CIN9 4 Control and data AD7147 MCU. The touch con- flash memory, 96 KB of RAM, 80 KB CIN10 5 registers CIN11 6 troller chips handle all of ROM, and a bunch of I/O) to deliver CIN12 7 the gory details behind an additional measure of application

Interrupt the scenes so that you capability. As an aside, you might Serial interface and GPIO VDRIVE 12 and control logic don’t have to (see Figure imagine the MSP430 and Coldfire to logic 18 GPI0 2). The Freescale part be the MCU cores that got the nod 13 14 15 16 17 even has a “Sounder” out- from Texas Instruments and Freescale, SDO/ SD1/ SCLK *CS *INT SDA ADD0 /ADD1 put to generate an audible respectively. For some reason, the fact “keyclick.” that TI uses a ’51 core while Freescale Figure 1—The 16-bit capacitance-to-digital converter (CDC) at the heart of Touch input is a huge went with ARM7 makes me smile. the Analog Devices AD7147 hints at the technical challenge posed by touch applications. Other features of note are single-electrode per switch market, but it isn’t the Beyond ZigBee there are plenty of configuration, AC shield output for long-trace/cable layouts, and an SPI/I2C only thing measuring other protocols vying for your attention. interface with a separate power supply for easy interface with any MCU. capacitance is good for. Typically, these combine IEEE 802.15.4 These chips can also be radios with non-ZigBee stacks, such as reading it reliably is. A mechanical used for applications, such as liquid-level Microchip Technology’s MiWi (T. switch needs little more than some sensing or frost detection. This is an Cantrell, “Be All You Can Bee,” Circuit debouncing to work reliably (at least opportunity for designers to put on Cellar 202, 2007) or TinyOS, the latter until it gets flaky or breaks altogether). their thinking caps and come up with favored by startups spun from the By contrast, capacitive sensing is chal- some creative applications. University of California (Berkeley) lenged by a variety of electrical (e.g., “Smart Dust” project where it origi- stray capacitance) and environmental CAN WE ALL GET ALONG? nated. Another trend finds historic (e.g., threshold variation and drift) con- Wireless sensor networks were out industrial automation leaders (e.g., cerns. in full force. As I’ve said before, the Emerson and Honeywell) leveraging For example, with a mechanical good news is that different wireless their installed base with the siren call switch the situation is real simple (i.e., networks can coexist. The bad news is of one-stop shopping. Google it’s open or it’s closed). By contrast, a that this means there is a bewildering “Wireless HART” or “SP100” if you capacitive switch can drift somewhere array of choices. want to follow that thread. in between if, for example, your finger The one-upmanship even extends to And what the heck is this is “hovering” over it. Similarly, a ostensible standards like ZigBee. The “6LoWPAN” stuff Arch Rock (another mechanical switch doesn’t care if it ink is barely dry on the 2006 draft of UC Berkeley spinout) is hyping? In was actuated by an adult, a kid, or for that spec and folks are that matter, a dog or cat. But with a already embellishing Sensor 1 *INT 3 capacitive switch, each user’s touch it. For example, the asserted 2 Stage_High_Threshold may be different (e.g., finger size). latest chip from Texas 1 (post calibrated register value) Mechanical switches have other Instruments offers a

taken-for-granted advantages that measure of location CDC ambient shouldn’t be overlooked.WWW.GiURUMELE.Hi2.RO For instance, capability (3- to 5-m value drifting users are comforted by some reassur- accuracy) by exploit- 6 ance that their inputs are being noted, ing the received signal 5 Stage_Low_Threshold (post calibrated register value) which is inherent in the tactile feed- strength indicator 4 CDC output codes back of a mechanical switch. (RSSI) feature of the Sensor 2* INT Similarly, a mechanical switch offers a radio. Not to be out- asserted t measure of false input protection in done, Freescale’s Changing environmental conditions that it takes more than an inadvertent newest part adds an swipe of a finger to actuate. optional “turbo” high- Figure 2—Unlike a mechanical switch, the definitions of “on” and “off” aren’t that clear-cut for a capacitive switch and can vary in operation (e.g., finger Fortunately, there are chips designed to speed (2-Mbps) trans- size) and over time. Thus, the latest touch controller chips, such as the deliver the benefits of capacitive touch fer mode. AD7147, incorporate lots of smarts, such as automatic threshold calibration.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 83 2710003-Cantrell.qxp 9/4/2007 5:02 PM Page 84

Yes, standards are a good thing, but de facto standard for hardware/software 6Lowpan specific application (socket interface) not if spec bloat and feature creep tie development tools and bench gear (e.g., designers hands. My take is that scopes, data loggers, etc.), replacing the Transport (UDP) somewhere along the line, IrDA bit off slow and buggy serial and parallel lash-

IPv6 more than the market could chew in a ups of yore. The delivery of power misguided attempt to offer big-ticket along with the signal is a huge blessing Adaptation LAN features. To work like a real for those of us drowning in wall warts. Frag./reassembly Load/ LAN, IrDA comes with a lot of bag- It’s also great that USB automatically HiLow DYMO-low Adtl formatting gage (e.g., discovery, negotiation, accommodates both low- and high- addressing, etc.), stuff that’s just a bur- speed devices for the optimal mix of IEEE 802.15.4 MAC den for a designer who simply wants performance when you need it and

IEEE 802.15.4 PHY to get a few bits from here to there. low cost when you don’t. A brochure caught my eye at the I did a double take when I walked Figure 3—When it comes to the issue of wireless proto- Vishay Semiconductors booth: “Courier- by the Loadstar Sensors booth. What’s cols, Arch Rock says that when the Internet engineering 115—Compact and Quick Infrared this hefty steel hockey puck with a task force (IETF) talks, designers should listen. The result is “6LoWPAN,” a scheme that hopes to layer an Internet Wireless Communications.” Hmm, USB port (see Photo 2)? It looks like a protocol (IP) veneer on top of IEEE 802.15.4 radios. once more with feeling for infrared? mouse for RoboCop. Turns out it’s a Turns out “Courier-115” is a stan- precision (0.15% standard, 0.05% case you’re wondering, it’s pro- dard that Vishay says “adapts key fea- option) heavy-duty (10-, 50-, 100-, 250-, nounced “Six-Low-PAN.” Gee, that tures of IrDA, but leaves the bulk and and 500-lb version) load sensor. rolls off the tongue doesn’t it? Where complexity behind.” Oh yeah, it also In the old days, designers had to the heck is a marketing guy when you leaves behind the IrDA licensing fee interface to the low-level (i.e., milli- need him? I’m calling it “GlowPAN” (i.e., the Courier-115 protocol and driv- volts) output of the raw sensor (e.g., because it’s easier to say and that’s er library is royalty-free for the taking). strain gage) itself. In modern times, what it looks like if you squint. With the proliferation of cheap radios, If the goal is an “Internet of things,” some might argue Courier-115 is too lit- then why not go right to the source, tle, too late, but I’m a bit more opti- that keeper of the Internet keys mistic. Infrared won’t replace other A/D interrupt known as the Internet Engineering wired and wireless schemes, but it could Use Clarke transform Task Force (IETF)? As you may recall, serve a variety of niche applications that to convert phase currents the IETF is the outfit responsible for all exploit its unique advantages. For exam- from three-axis to two-axis of those requests for comment (RFCs) ple, infrared is impervious to electrical that define the inner workings of the interference, something that’s already a Use Park transform to convert Internet (e.g., IP, TCP, DHCP, etc.). concern for radios. It’s also immune to two-axis currents It may be hard to pronounce, but eavesdropping, at least in the sense to rotating coordinate system the premise of 6lowPAN is simple that if the bad guys can’t see you, they enough, namely come up with a bite- can’t hear you. Use slide mode controller to estimate sized version of IP that an IEEE Infrared may yet have the last laugh. motor position and speed 802.15.4 radio can swallow without Vishay was also showing off the choking. Note that since there will be TSOP98200 wideband IR sensor that Run PI controllers for a lot of “things” in the “Internet of is said to cover the entire remote con- currents and speed things,” the larger address space of IP trol bandwidth (30 to 455 kHz) for version 6 is a must (see Figure 3). “code learning” applications. If PC Use inverse park transform makers hope to succeed with their liv- to convert rotating coordinate system CAN’T GET NO RESPECT ing room “media center” aspirations, two-axis stationary system Whatever happened to IrDA, the they will have to accommodate IR

infrared data standard promulgated by remotes. It’s hard to teach an old Use inverse Clarke transform the aptly namedWWW.GiURUMELE.Hi2.RO Infrared Data couch potato new tricks. to convert two-axis to three-axis Association? It’s ironic that in all the hoopla over wireless, the infrared THE MOUSE PORT THAT ROARED option is completely overlooked. Anybody remember when USB got Use space vector modulation to update That, despite the fact it’s one of the its start as a lowly mouse port? PWM duty cycle most popular short-range wireless Nowadays USB is a huge success. technologies, proven on a daily basis Even with the proliferation of radios, I End of A/D interrupt by legions of couch potatoes and their expect good old wired USB will be one quivers of IR remotes. of the last wires left standing. Figure 4—Microchip exploits the number-crunching I wonder if the IrDA itself didn’t I like USB as a consumer, but I love capabilities of their dsPIC to bring the benefits of field- hurt as much as help infrared’s cause. it when I’m in the lab. It’s become the oriented control to mass-market motors.

84 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 2710003-Cantrell.qxp 9/4/2007 5:03 PM Page 85

once a control scheme only cost- justifiable for big and expensive motors is now feasible for little and cheap motors. Thank you once again, Mr. Moore.

HARVEST TIME Energy shortage? There’s no energy shortage. Photo 2—USB puts on a hard hat, in this case the Loadstar Look at the world around you. heavy-duty load sensor, for blue-collar applications. It’s one of the It’s filled with wasted energy, first products to bring USB to traditional big-iron sensors, but I’m whether light from the sun or the pretty sure it won’t be the last. movement of wind and water. To be sure, solar, wind, and the signal conditioning has been inte- hydro power are well understood. But, grated to deliver a high-level output that’s just the low-hanging fruit. For (e.g., 0 to 5 V). Now, having USB as an instance, consider all of the energy option not only eliminates analog wasted as heat from friction, or pouring interface issues altogether, but also out of tailpipes, or steaming from cups the need for a power connection (the of hot coffee and tea. For that matter, sensor gets its power over USB). imagine how much energy is generated USB is a hit in the home, office, and each day by the pounding feet of 6.6 lab. I guess the message is now it’s billion humans wandering the planet. headed for the field and factory too. There’s plenty of energy. What’s in short supply are ways to efficiently FIELD OF DREAMS gather and recycle it. But, that’s all A stop in at the Microchip booth starting to change with the emergence reminded me that “Moore for Less” is of new “energy harvesting” techniques why I love this business. Over time, that take advantage of sensor-derived chips inexorably deliver more features technology. Consider that a piezoelec- and performance for less cost. That tric accelerometer and a thermocouple means the game for designers is can both be considered “generators,” always changing. The typical “Do it the former driven by acceleration and the same as last time, but charge the latter by thermal differential. more” approach won’t cut it. But that’s just half the story. The For instance, you might imagine challenge is that the amount of energy blue-collar apps like motors and generated is small, historically too lit- power supplies are rather mature and tle to do anything useful. And don’t staid. But, instead the virtually “free forget the “harvester” itself requires MIPS” delivered by Moore’s Law are energy, which is a showstopper if it sparking a renaissance in the redesign consumes more than it harvests. of these blue-collar stalwarts. At the booth Microchip was pitch- ing their dsPIC for motor control apps (see Figure 4). Thanks to the chip’s mini-me DSP features (MAC, barrel shifter, dual-operand bus, etc.), it’s able to handle WWW.GiURUMELE.Hi2.ROthe complicated matrix math required to implement a Field Oriented Control (FOC) algorithm.[1] The desirable features of the algo- rithm (e.g., efficiency and responsive torque control to compensate for vary- Photo 3—The Perpetuum PMG “microgenerator” is a ing loads) are proven by its widespread clever way to capture energy from the vibration of a use in pricier motor setups. motor, energy that would otherwise go to waste. It’s more than a matter of the cost of the energy itself, but FOC is interesting stuff, worthy of eliminating the need for a power supply as well. an entire article. For now though, the Eliminating wires and batteries enables compelling important message is this: what was applications, such as tire pressure monitoring.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 85 2710003-Cantrell.qxp 9/4/2007 5:03 PM Page 86

a) b) Harvest and Field Oriented Control of PMSM hoard you may, but Motors,” DS01078A, Microchip there will Technology, Inc., 2007, inevitably come a ww1.microchip.com/downloads/en time when an /AppNotes/01078A.pdf. external energy boost is required. RESOURCE Traditional battery Photo 4—MEMS “nanograss” isn’t a pipe dream. As shown here, it enables “elec- backup is of course Sensors Expo & Conference 2007, trowetting” applications, such as the mPhase “Smart Nanobattery.” Imagine a future an option, but one June 9 to 11, Donald E. Stevens with batteries that extend shelf life with on-demand incremental (i.e., all or a por- Convention Center, Rosemont, tion) activation. Such batteries might be integrated into the same package with that suffers from chips, or ultimately perhaps even on the same die. the fact that batter- Illinois, www.sensorsexpo.com. ies run down even What’s changed is that ever-greener if they aren’t used. Enter mPhase (i.e., low-power) silicon has reached an Technologies and their “Smart SOURCES inflection point where useful things can Nanobatteries.” The secret recipe is Energy harvesting module be done with tiny amounts of energy. “Electrowetting,” which electrically Advanced Linear Devices, Inc. For instance, we’ve all heard about controls electrolyte dewdrops sprinkled www.aldinc.com the forthcoming wireless light switches on blades of MEMS “Nanograss” (see AD7147 Capacitive touch controller that, thanks to low-power radios (a la Photo 4). It’s still rather blue sky, but if Analog Devices, Inc. 802.15.4), will offer “many years” of the promise is fulfilled, we’ll have bat- www.analog.com battery life. Well, one outfit I came teries that can be incrementally activat- across at the Expo, EnOcean, is upping ed on demand, extending shelf life from IP Radio the ante. They’ve got a wireless light years to decades. Better yet, the manu- Arch Rock Corp. switch that doesn’t need a battery at facturing process and form factor of a www.archrock.com all! That’s because they’ve figured out “Smart Nanobattery” is rather IC-like, No-battery wireless switch a way to eke just enough power from raising the future prospect of chips EnOcean, Inc. the motion of the switch itself to fire that ship with “batteries included.” www.enocean.com up a radio and launch a few bits. Perpetuum had their PMG17 accelera- SENSATIONAL MC13224 ZigBee module, tion-driven “microgenerator” on display New sensors drive the volume of exist- MMA7450L MEMS accelerometer, (see Photo 3). It mounts to electrical ing applications by reducing cost and and MPR801 and MPR802 capacitive motors and powers a wireless sensor adding features. Better yet, they invari- proximity sensors with energy extracted from the vibration ably spark the creation of new and Freescale Semiconductor, Inc. of the motor itself. It may seem odd to unforeseen applications. Just remember www.freescale.com bother harvesting energy when there’s a the example of the MEMS accelerometer: iLoad USB load sensor high-power motor supply nearby. But in it was designed to make airbags cheaper Loadstar Sensors, Inc. fact, tapping into the motor’s wired sup- and smarter, which it did, but now it’s www.loadstarsensors.com ply, especially for a temporary or retro- also in the Wii, cell phones, toys, etc. fitted installation, is a hassle that the So what are the latest trends? DSPic and Field Oriented Control PMG17 eliminates. In a typical setup Sensors that were once analog will go (FOC) algorithm (i.e., fraction of 1 g to work with), the digital. Those that have gone digital Microchip Technology, Inc. PMG17 might squeak out a milliwatt or will get smarter. Wireless sensor net- www.microchip.com so (e.g., 0.8 mW at 0.025 g RMS). But, works, the more the merrier. Energy: Smart nanobattery get it rocking and rolling with a full 1 g find more, use less. mPhase Technologies, Inc. and it cranks out a beefy 40 mW. I enjoyed my time at the Sensors www.mphasetech.com You can harvest energy an electron at Expo. I figure I better plan on going a time, but just WWW.GiURUMELE.Hi2.ROlike a real crop, you need again next year to keep up. “West PMG17 Microgenerator a place to store it. Advanced Linear Coast” here I come! I Perpetuum Designs has an energy “silo” that http://perpetuum.isonlinehere.com Tom Cantrell has been working on stores each grain of energy until you’ve chip, board, and systems design and CC2431 ZigBee chip got enough to do something useful. marketing for several years. You may Texas Instruments, Inc. Basically, you can feed it any voltage you reach him by e-mail at tom.cantrell www.ti.com happen to scrounge (i.e., up to 500 VAC @circuitcellar.com. or VDC) and it stores it in a capacitor. Courier-115 IR protocol, TFDU4300 IR When the stored charge reaches a use- transceiver, and TSOP98200 IR sensor ful threshold (e.g., 3.3 V), the output REFERENCE Vishay Semiconductors, Inc. turns on to power the load. [1] J. Zambada, “AN1078: Sensorless www.vishay.com

86 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-207.qxp 9/5/2007 10:19 AM Page 87 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet. ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. Call for current rate and deadline information. Send your disk and digital submission sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail [email protected]. For more information call Shannon Barraclough at (860) 875-2199.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/ is your guide to a variety of engineering products and services.

UUSSBB phyCORE® OEMable Single Board Computers Add USB to your next XScale: PXA270, PXA255

project—it’s easier than you ARM: LPC3180 (ARM9); LPC22xx, LPC229x, AT91 (ARM7)

might think! PowerPC: MPC5554, MPC5200B, MPC565, MPC555 v USB-FIFO up to 8 mbps ColdFire: MCF5485 x86: Elan SC520 CAN v USB-UART up to 3 mbps C166/XC16x/ST10/8051 v USB/Microcontroller boards Blackfin: BF537 Faster-to-Market: Save time by pre-programmed with firmware integrating a PHYTEC Single Board Computer Module into v 2.4GHz ZigBee™ & 802.15.4 your target circuitry. Make -or - Buy: Why make v RFID Reader/Writer your own when you can buy PHYTEC off-shelf solutions, Absolutely NO driver software cost-effective to 1000s units/year? Integrated Support Services: Let PHYTEC assist you in the design of your end product: from tools and RTOSes to production. Our hardware is development required! bundled with leading compilers (Keil, IAR, CodeWarrior), RTOSes (WinCE, Linux) and debuggers. Immediate Support: Talk to PHYTEC technical staff with every call. No www.dlpdesign.com waiting for answers. Your OEM solution: With 20 years design, production, and integration experience, PHYTEC is your OEM partner.

PHYTEC America, LLC I 203 Parfitt Way SW, G100 I Bainbridge Island, WA 98110 USA www.phytec.com I (800) 278-9913 I www.phycore.com

4HEDS0)#š0)#š-#5 ##3##OMPILER ISNOWAVAILABLEFORPURCHASE

3&'&RPSLOHU%XLOWLQ)XQFWLRQV ‡6WDQGDUG&3UHSURFHVVRUV ‡0DWK/LEUDULHV ‡,QWHUUXSW+DQGOHUV ‡'LVFUHWH,2 ‡&RQVWDQWVLQ520 WWW.GiURUMELE.Hi2.RO‡DQGELW)ORDW ‡,&63DQG,Q&LUFXLW'HEXJJLQJ ‡/LQNLQJWR0LFURFKLS/LEUDULHV ‡LQWLQWLQWLQWLQW LQW

$GGRQ‡8SJUDGH‡3ULFLQJ‡,QIRUPDWLRQ ZZZFFVLQIRFRPGVSLFF [ 3&','(

3,&‹GV3,&ŠLVDUHJLVWHUHGWUDGHPDUNRI0LFURFKLS7HFKQRORJ\,QFLQWKH86DQGRWKHUFRXQWULHV

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 87 ib-207.qxp 9/5/2007 10:20 AM Page 88

SpectraPLUS 5.0 Audio Spectrum Analysis Features Sound Card based I/O FFT sizes to 1048576pts, 1/96 Octave Up to 24 bit, 200kHz sampling rates 3-D Surface and Spectrogram Digital Filtering, Signal Generation THD, IMD, SNR, Transfer Functions DDE, Macros, Data Logging, Vibration Analysis, Acoustic Tools FREE 30 day trial! www.spectraplus.com

Pioneer Hill Software 360 697-3472 voice PHS [email protected]

High-speed USB 2.0 + Xilinx FPGA Complete Software API

75mm x 50mm 3.5“ x 2.0” $399.95 $199.95 XEM3010-1500P: XEM3001: Š 1,500,000-gate FPGA Š 400,000-gate FPGA Š Programmable PLL Š Programmable PLL Š Over 110 I/Os Š Over 80 I/Os Š 32 MB SDRAM Š 0.1” expansion headers Š Configuration PROM Š Business-card size Š 0.8-mm expansion Š $199.95 / Qty 1 Š $399.95 / Qty 1 Š $174.95 / Qty 10 Š $349.95 / Qty 10 FrontPanel Software API: Š Windows XP, Mac OS X, Linux Š C/C++, Python, Java Š Configure FPGA and communicate with your design Š The easiest way to integrate USB into your product Š Use for image capture, control, test equipment, etc. Š Up to 38 MB/s transfer rate! 5% off with Coupon Code: CKTCLR73*

* Valid for first order only. Void 30-days after issue publication.

Visit us online at: m Opal Kelly www.opalkelly.com

WWW.GiURUMELE.Hi2.RO

88 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-207.qxp 9/5/2007 10:20 AM Page 89

Radio Modules

t Reliable Range -- 150’ indoors -- 315 or 868 MHz t -- Solar operates for days without light t Easy-to-use -- Easy configuration t -- No batteries or external power is needed NowonSale! t Wireless Sensor Development Kits

t t AdHocControls.com t (801) 225-2226

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 89 ib-207.qxp 9/5/2007 10:20 AM Page 90

extend 100’s feet tens miles

16IO-SSRT

SAVE 5% SAVE 5% SAVE 5% ABACOM ABACOM ABACOM

ABACOM ABACOM ABACOM Technologies Technologies Technologies

WWW.GiURUMELE.Hi2.RO

90 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-207.qxp 9/5/2007 10:20 AM Page 91

ANYONE Can Now Easily Hand Solder Surface- Mount Components! Even A 10 Year Old!

www.schmartboard.com

QScreenTM - Low Cost Versatile Instrument Controller

$359/100s

Touchscreen Operated GUI 128x240 CCFL- Backlit Graphic Display Programmable in C or Forth Hundreds of Screens, Buttons, & Menus A/D and Two RS232/485 ports 8 Timer-Controlled Digital I/O Lines Up to 1 MB Flash, 512KB RAM Wide Selection of Plug-in I/O Mosaic Industries Inc. tel: 510-790-1255 fax: 510-790-0925 www.mosaic-industries.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 91 ib-207.qxp 9/5/2007 10:20 AM Page 92

Low Cost CAN USB Adapter

Simple configuration & use

$99.95 Qty 1

+1 630-245-1445 Naperville, Illinois USA www.c-a-n.com

Order online at: Phone: (719) 520-5323 microEngineering Labs, Inc. Fax: (719) 520-1867 www.melabs.com ® Box 60039 Development Tools for PIC Microcontrollers Colorado Springs, CO 80960

® USB Programmer $89.95 LAB-X Experimenter Boards BASIC Compilers for PICmicro for PIC® MCUs (as shown) Pre-Assembled Boards Easy-To-Use BASIC Commands Available for 8, 14, 18, 28, Windows 9x/Me/2K/XP Interface RoHS and 40-pin PIC® MCUs PICBASIC™ Compiler $99.95 Compliant 2-line, 20-char LCD Module BASIC Stamp 1 Compatible Programs 9-pin Serial Port Supports most 14-bit Core PICs PIC MCUs Sample Programs Built-In Serial Comm Commands includingWWW.GiURUMELE.Hi2.RO Full Schematic Diagram low-voltage PICBASIC PRO™ Compiler $249.95 (3.3V) devices Pricing from $79.95 to $349.95 Supports Microchip PIC10, PIC12, PIC14, PIC16, PIC17, and PIC18 microcontrollers Includes ™ Direct Access to Internal Registers Windows PICPROTO Prototyping Boards Supports In-Line Assembly Language 98, Me, NT, With Accessories for $119.95: Interrupts in PICBASIC and Assembly 2K, and XP Includes Programmer, Software, USB Cable, Double-Sided with Plate-Thru Holes Built-In USB, I2C, RS-232 and More Software and Programming Adapter for 8 to 40-pin DIP. Circuitry for Power Supply and Clock Source Level Debugging Large Prototype Area Parallel Port Programmer Boards Available for Most PIC® MCUs See our full range of products, including starting at $59.95 Documentation and Schematic books, accessories, and components at: Serial Port Programmer Pricing from $8.95 to $19.95 www.melabs.com EPIC™ starting at $79.95

92 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 9/5/2007 10:22 AM Page 93

CROSSWORD

1

2 3

4

56

7

8

9

10

11

12

13

14 15

16

17

Across Down 1. A device whose resistance decreases with exposure to light 1. A cellular station designed to cover a small 2. An Apple web browser first released in 2003 area 4. The ability of an electrically isolated isolated conductor to 3. An electrical transformer with a single store charge tapped winding 7. The flow of binary data as an unstructured sequence of bits 5. VoIP network used for talking via a broad- 9. Space shuttle; Hint: lost continent band Internet connection 11. The range of frequencies transmitted (with minimum relative 6. An IC that incorporates the functions of a loss or maximum relative gain) by a band-pass filter CPU on a single chip 14. A device WWW.GiURUMELE.Hi2.ROthat combines many analog or digital inputs and 8. The name of MIT’s mascot outputs into a single channel 10. A timer used to “unhang” a system and 16. A device that controls the flow of data packets between restore it to normal operation different networks 12. The Brooklyn-born scientist (1946–) who 17. The famous singer/songwriter who played Nikola Tesla in coinvented the Ethernet and founded 3Com the 2006 film The Prestige 13. A standard file format used to draw patterns for circuit boards. The file controls a photo- plotter. 15. Photovoltaic The answers are available at www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 207 October 2007 93 94-advertiser's index.qxp 9/6/2007 1:33 PM Page 94

INDEX OF ADVERTISERS The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page Page Page Page 91 AAG Electronica, LLC 8 e-PCB 30 Loadstar Sensors, Inc. 88 Radiotronix – DComponents

90 Abacom Technologies 33 ExpressPCB 90 MCC (Micro Computer Control) 89 Reach Technology, Inc.

8, 89 Ad Hoc Electronics 57, 92 ezPCB 24 Maxstream 49 Renesas Technology

24 Aimtec – DComponents 87 FDI-Future Designs, Inc. 28 Microbridge Technologies Corp. 20 SoC Conference

91 All Electronics Corp. 88 Front Panel Express, LLC 88, 92 Micro Digital, Inc. 50 Saelig Co.

90 Apex Embedded Systems 89 General Circuits, Inc. 15 Microchip 91 Schmartboard

29 Arcturus Networks 91, 92 Grid Connect 92 microEngineering Labs, Inc. 48 Sealevel Systems

81 Arrowfest 79 HI-TECH Software LLC 91 Mosaic Industries, Inc. 9 SEGGER Microcontroller Systems LLC

7 Atmel 17 Holtek Semiconductor, Inc. 95 Mouser Electronics 23 Signum Systems Corp.

90 BestHomeLEDLighting 89 IMAGEcraft 89 Mylydia, Inc. 13 Silicon Laboratories, Inc.

82 Bitscope Designs 88 Intec Automation, Inc. C2 NetBurner 53 Systronix

65 CWAV 92 Intrepid Control Systems 77 Nurve Networks LLC C3 Tech Tools

42 CadSoft Computer, Inc. 90 Ironwood Electronics 88 Ontrak Control Systems 72, 73 Technologic Systems

89 Cam Expert LLC 64, 91 JKmicrosystems, Inc. 88 Opal Kelly Inc. 87 Technological Arts

34 Comfile Technology, Inc. 63 Jameco 25 PCB-Pool 89 Tern, Inc.

3, 87 Custom Computer Services, Inc. 85 Jeffrey Kerr, LLC C4 Parallax, Inc. 58 Tibbo Technology, Inc.

1 Cypress Microsystems, Inc. 66 Keil Software 87 Phytec America LLC 92 Trace Systems, Inc.

87 DLP Design 85 LabJack Corp. 88 Pioneer Hill Software 87 Triangle Research Int’l, Inc.

77 Decade Engineering 85 Lakeview Research 12 Pololu Corp. 88 WCSC (Willies Computer Software Co.)

77 DMM Technology Corp. 90 Lawicel AB 91 Pulsar, Inc. 39 Wiznet

53 EMAC, Inc. 32 Lemos International 21 R4 5 Wiznet iEthernet Design Contest 2007

89 Earth Computer Technologies 2 Link Instruments 31, 57 Rabbit Semiconductor 91 Zanthic Technologies, Inc.

41 Efficient Computer Systems 64 Linx Technologies 90 Rabbit Semiconductor

Preview of November Issue 208 ATTENTION ADVERTISERS Theme: Analog Techniques December Issue 209 Embedded IP-PBX: Switch Analog and VoIP Calls Deadlines Hybrid Computing on an FPGA Space Close: Oct. 10 iEthernet Bootcamp: Get Started with the W5100 Material Close: Oct. 19 NimbleSig: A Compact DDS RF Signal Generator SMT Manufacturing:WWW.GiURUMELE.Hi2.ROTake a Board from Prototype to Production Theme: Resilience in Embedded Designs (Part 3): Software Graphics & Video Communication Protocols

Call Shannon Barraclough LESSONS FROM THE TRENCHES A Flash in the Pan now to reserve your space! FROM THE BENCH Motor Driving for a Robotic Arm 860.875.2199 SILICON UPDATE Thanks for the MEMS e-mail: [email protected]

94 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com 95.qxp 8/27/2007 4:48 PM Page 1

3-in-1 PWM Dual Buck and MCP100, 101, 120, and 130 System Linear DDR Power Controller Supervisor Products

Complete power solution for System supervisors protect from brown-out MCH and DDR memory. conditions when supply voltage drops below safe operating levels.

mouser.com/onsemiconductor/a mouser.com/microchip/a

High Side Current Sense Monitor

Requires a single, low-value sense resistor to accurately measure high side currents.

mouser.com/zetex/a

AH180 Power Management MicroPower OmniPolar Hall-effect Solutions for Your Sensor Switch New Designs Subminiature sensor switches with two Hall-effect plates and an open-drain output driver for battery-operated, handheld equipment. mouser.com/diodesinc/a

• The ONLY New Catalog Every 90 Days TinySwitch® III

• NEWEST Products & Technologies Tight I2f parameter WWW.GiURUMELE.Hi2.ROtolerance reduces • Over 850,000 Products Online system cost and • More Than 335 Manufacturers minimizes maximum overload power, • No Minimum Order The Newest Products reducing cost of For Your Newest Designs transformer, primary • Fast Delivery, Same-day Shipping clamp, and secondary components.

mouser.com (800) 346-6873 mouser.com/powerintegrations/a

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

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.

Mouser_CircuitCellar_10-1.indd 1 8/20/07 5:22:23 PM steve_edit_207.qxp 9/6/2007 1:30 PM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director The Law of Unintended Consequences

The Law of Unintended Consequences says that every undertaking, however well intentioned, is generally accompanied by unforeseen consequences. As well meaning as our intentions are in passing laws, starting projects, or instilling goodness, because of the complexity of the world and our usual over- confidence, no good deed goes unpunished. A significant example of such consequences is the Internet. Invented in the early 1970s as a more efficient means for international academic commu- nications, the Internet was immediately embraced by everyone with little regard for structural securities. E-mail was developed with virtually no safeguards because everyone on the Internet knew each other. False headers? Anonymous originators? Cryptic subject lines specifically designed to avoid filters? Why would anyone want to do that? BTW, what is an e-mail filter and why would we even need it? That naivety has resulted in many of the Internet con- sequences we face today. Like many things in our lives, we understand its significance only when it is no longer available. We don’t realize how much we need a car until ours is in the shop.We don’t appreciate electricity until a natural disaster kicks us back into 1880s settler mode without power. Unfortunately, we can’t stock “extra Internet” on the shelves for emergencies. I recently had a little taste of web-less living for a day and a half and I’ll tell you it wasn’t pretty. All morning I was having intermittent service problems and at about noon my home office DSL line went belly-up. A quick check of the four landlines into the house (yes, still four, and I’m not exactly sure why I need that many) revealed that two were working, one was totally dead, and one was all static. The latter was my DSL line. A frantic call to AT&T result- ed in a repair truck pulling into my driveway about three hours later. Of course, with four hours of my life already on hold, I was getting a bit antsy. I missed the constant stream of e-mails from the office, real-time updates of news events, webcams and monitors at the cottage, VoIP conference calls with editors and friends, and just plain surfing. More significantly, however, I think I was suffering from withdrawal from the adrenaline high that comes when dealing with such an attention-addictive device. At first, the AT&T repairman said that the buried line from my house to the telephone pole might be bad. He couldn’t string a temporary wire or swap out the DSL wire with one of the two lines that did work. I’d have to wait up to a week for their “wiring contractor” to bury a new wire. Being antsy didn’t even come close to describing the horror caused by that explanation. I went back and sat down in front of my laptop and just stared at the blank IE7 page. A little while later, I was on my way out to the garage to fire up the backhoe when the AT&T guy drove back into the driveway. I had already concluded that waiting a week wasn’t going to happen. I was going to dig up the damn line and patch it myself. “If they want to bury it all again next week, that’s fine,” I thought to myself. “I’ve dug more holes on this property than the moles. I just have to watch out for the power line buried in the same utility trench.” ;-) I was ready to do some real diesel-powered damage when the repairman matter-of-factly said that it seemed like it was a wire from the pole back to the DSL box a half-mile down the road instead of to the house. He said they would let me know the following day if it could be fixed within 24 hours or whether it would be a job for their “pole wiring” contractor that could take another week. My communications-withdrawal symptoms only worsened as he drove out. At 2 P.M.the next afternoon, my anxiety wasn’t any better. Having lots of land is fine until you need to hack the neighbor’s Wi-Fi and that wasn’t hap- pening either. I was still dead in the water and staring at the IE white screen of “duh!” So, I decided to call AT&T and see if they had made any progress. After 20 minutes of automated DTMF Q&A and three live operators, I ended up with the repair department. Since a “repair ticket” was still open at their end, they concluded that work must still be proceeding. I never got to ask what “proceeding” meant because at that moment another AT&T truck pulled into my driveway. I quickly signed off and went to meet the repairman. “Well, we had a little burned spot in the wiring a quarter mile down the road a piece. It should be fixed in about a half hour.You guys get a little thun- derstorm actionWWW.GiURUMELE.Hi2.RO around here every once in a while?” he asked. I pointed at one of my out buildings and traced a finger line from it across the tops of a few more out buildings and ended up pointing to the top of the main house as I said, “Nothing that hundreds of pounds of 0.5" braided copper cable and 24 lightning rods along with buried braided cable around every foundation connected together as a 1-acre ground plane doesn’t fix! I guess AT&T got the lightning bolt that missed me.” He got the message. A half hour later my life resumed schedule as all of my communication-intensive activities came back into sync. I turned on Outlook and e-mail mes- sages streamed in. And, for the first time in my life, I didn’t even mind getting a little spam.

[email protected]

96 Issue 207 October 2007 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 3/30/2007 1:38 PM Page 1

WWW.GiURUMELE.Hi2.RO C4.qxp 8/28/2007 11:54 AM Page 1

WWW.GiURUMELE.Hi2.RO