Cover - 232.qxp 10/6/2009 11:47 AM Page 1

Energize a Circuit with an SMPS, p. 26 • Wireless Power Delivery, p. 60 www.circuitcellar.com

CIRCUITTHE MAGAZINE FOR COMPUTER CELLAR APPLICATIONS #232 November 2009 ANALOG TECHNIQUES Low-Distortion FSK Generation Explained Build a Precision Linear Encoded Display Embedded -Based Vehicle Tracking Device Management via the SNMP Repurpose a Development Platform Parameter Passing in C Language

$5.95 U.S. ($6.95 Canada) C2.qxp 7/8/2009 8:41 AM Page 1

A Low Cost Solution for Industrial Serial to Ethernet with Digital I/O and Analog to Digital Converters

Hardware Features t5XP55-TFSJBMQPSUT t.CQT&UIFSOFU t6QUPEJHJUBM*0 t'PVSCJU"%DPOWFSUFST t0QFSBUJOHUFNQFSBUVSFUP$ t%JNFOTUJPOTwYw tCJUQFSGPSNBODF Software Features t/PQSPHSBNNJOHSFRVJSFE t5$16%15FMOFU)551NPEFT t%)$1TUBUJD*1TVQQPSU t8FCCBTFEDPOöHVSBUJPO

w $19.95 Qty. 1000

w

The all-new NetBurner SBL2e INDUSTRIAL SERIAL TO ETHERNET SOLUTION A NetBurner Complete Hardware & Software Solution

Board Part Number | SBL2e-200IR Information and Sales | [email protected] Web | www.netburner.com Telephone | 1-800-695-6828 19.qxp 9/10/2009 1:38 PM Page 1

Connected. Versatile. Cost-effective.

Stellaris LM3S9B90 Stellaris LM3S8962 Stellaris LM3S3748 Ethernet Evaluation Kit Evaluation Kit Evaluation Kit featuring USB, Ethernet featuring integrated Ethernet featuring USB Host/Device and CAN and CAN $99 $89 $109

s$ETERMINISTIC!2-® Cortex™ -CORES ® Stellaris Means: s2EAL TIMEMULTI TASKING-#5S s!DVANCEDINTERRUPT DRIVENSOFTWAREWITH3TELLARISWARE® software

Stellaris LM3S6965 Stellaris LM3S811 Stellaris LM3S2965 CAN Ethernet Evaluation Kit Evaluation Kit Evaluation Kit demonstrating an embedded featuring basic embedded demonstrating a CAN network web server out-of-the-box control out-of-the-box $69 $49 $79 2-3.qxp 10/13/2009 9:37 AM Page 1 2-3.qxp 10/13/2009 9:37 AM Page 2 Task_Masthead_232.qxp 10/8/2009 12:09 PM Page 4

ASK ® CIRCUIT CELLAR TMANAGER THE MAGAZINE FOR COMPUTER APPLICATIONS FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER You’re Covered Steve Ciarcia Jeannette Ciarcia MANAGING EDITOR MEDIA CONSULTANT C. J. Abate Dan Rodrigues If you need it, we’ve got it. Whether you are looking for solutions WEST COAST EDITOR CUSTOMER SERVICE to design problems, helpful programming tips, ideas for exciting Tom Cantrell Debbie Lavoie new projects, or insight on the new technologies coming down the CONTRIBUTING EDITORS CONTROLLER pipe, Circuit Cellar has you covered. That is our main objective, and Jeff Bachiochi Jeff Yanco it always has been. Ask any staffer who has been around since Issue Robert Lacoste ART DIRECTOR 1 and you’ll find that we’ve always considered ourselves a “one-stop George Martin Ed Nisley KC Prescott shop” for everything embedded. But this month we’ve outdone our- GRAPHIC DESIGNERS selves. How? We literally have something for everyone. Linux NEW PRODUCTS EDITOR John Gorsky Grace Chen lovers, C language devotees, surveillance enthusiasts, power-hungry Carey Penney design engineers, innovative embedded network developers, signal PROJECT EDITORS Gary Bodley STAFF ENGINEER theory buffs, and do-it-yourselfers who love popping open MCU- Ken Davidson John Gorsky based gadgets and repurposing them for exciting new applications— David Tweed we’ve got you covered! Heck, we even have a project for those of you who have metal lathe shops next to your circuit cellars! In “Embedded Linux-Based Location System,” James Stephanick explains how to build a vehicle location device (p. 16). An ARM- based USB network storage link, a prepaid GSM cell phone, and a ADVERTISING 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise USB-GPS device comprise this handy location system. Turn to page 26, where Noel Rios presents a switched-mode PUBLISHER Sean Donnelly power supply design. With it, he can adjust voltage from 1 to 20 V Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] and current from 0 to 1 A. He does this by entering the values on a ADVERTISING REPRESENTATIVE keypad. Shannon Barraclough When precision matters, consider a linear encoder. Carl Stoesz Direct: 860.872.3064, E-mail: [email protected] explains how he mounted an optical linear encoder to a metal lathe ADVERTISING COORDINATOR that he uses to create small precision parts (p. 36). He uses the setup Valerie Luster E-mail: [email protected] to send speed and displacement information to an LCD. There’s a big difference between “hacking” and “repurposing.” Hacking is about deconstruction and investigation. Repurposing Cover photography by Chris Rakoczy—Rakoczy Photography www.rakoczyphoto.com takes things a bit further: you take apart a design and use its features PRINTED IN THE UNITED STATES to create something new or improved. On page 44, Cyrille de Brebisson explains how to repurpose an HP financial calculator and CONTACTS SUBSCRIPTIONS use it for a variety of embedded design apps. Information: www.circuitcellar.com/subscribe, E-mail: [email protected] Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Check out George Martin’s “Passing Parameters” for yet anoth- Hanover, NH 03755-5650 er lesson from the trenches of C coding (p. 50). He makes a con- Address Changes/Problems: E-mail: [email protected] GENERAL INFORMATION vincing argument for passing parameters in the first place, and then 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] describes how to do so and get results. Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] Do you remember Dennis Seguine’s 2006 Circuit Cellar 194 arti- AUTHORIZED REPRINTS INFORMATION 860.875.2199, E-mail: [email protected] cle titled “Simplified FSK Signal Detection”? There he presented an AUTHORS efficient method for detecting FSK signals. This month he describes Authors’ e-mail addresses (when available) are included at the end of each ar ticle. how to to generate FSK modulation with low-distortion and low- transition phase error (p. 54). CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices . One-year (12 issues) On page 60, Tom Cantrell presents a truly exciting concept: wire- subscription rate USA and possessions $29.95,Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- scription rate USA and possessions $49.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in less power on a microelectronic scale. That means wireless power U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders delivery! The future is now. and subscription-related questions to Cir cuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call 800.269.6301.

And lastly, we arrive at a topic important to everyone: device Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. management. Jeff Bachiochi explains how to monitor networked Circuit Cellar® makes no warranties and assumes no responsibility or liability of an y kind for errors in these programs or schematics or for the devices via the simple network management protocol (SNMP). With consequences of any such errors. Furthermore, because of possible variation in the quality and condition of mater ials 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 the SNMP, you can keep build an MCU-based managed device to from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to build things based upon these ideas under patent or other rele vant intellectual property law in their jurisdiction, or that readers have a right to monitor numerous networked modules and log critical data (p. 66). construct or operate any of the devices described herein under the relevant patent or other intellectual proper ty law of the reader’s jurisdiction. The reader assumes any risk of infringement liability for constructing or operating such devices.

ember 2009 – Issue 232 Entire contents copyright © 2009 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 par t without written consent from Circuit Cellar Inc. is prohibited. Nov

4 CIRCUIT CELLAR® • www.circuitcellar.com 3.qxp 8/11/2009 11:31 AM Page 1 INSIDE ISSUE BONUS CONTENT Measuring Propagation Delay with a Universal Counter

2November3 2009 • Analog Techniques2

Vehicle Location Made 16 Embedded Linux-Based Location System Simple, p. 16 James Stephanick

26 Energize a Circuit An Innovative Switched-Mode Power Supply Design Noel Rios

36 Precision Linear Encoder Display Carl Stoesz

44 How to Repurpose a Development Platform Cyrille de Brebisson

54 Low-Distortion FSK Generation Dennis Seguine

Wireless Power Delivery, p. 60

TASK MANAGER 4 Linear Encoder You’re Covered Display, p. 36 C. J. Abate

50 LESSONS FROM THE TRENCHES NEW PRODUCT NEWS 8 Passing Parameters edited by John Gorsky George Martin TEST YOUR EQ 15 60 SILICON UPDATE Power Pitcher CROSSWORD 74 Wireless Power on a Microelectronic Scale Tom Cantrell INDEX OF ADVERTISERS 79 December Preview 66 FROM THE BENCH Device Management PRIORITY INTERRUPT 80 Monitor Networked Devices Via SNMP Keeping the Lights On

November 2009 – Issue 232 November Jeff Bachiochi Steve Ciarcia 6 CIRCUIT CELLAR® • www.circuitcellar.com /11/

Hammer Down Your Power Consumption with picoPower™!

THE Performance Choice of Lowest-Power Microcontrollers

Performance and power consumption have always been key elements in the development of AVR® microcontrollers. Today’s increasing use of battery and signal line powered applications makes power consumption criteria more important than ever. To meet the tough requirements of modern microcontrollers, Atmel® has combined more than ten years of low power research and development into picoPower technology.

picoPower enables tinyAVR®, megaAVR® and XMEGA™ microcontrollers to achieve the industry’s lowest power consumption. Why be satisfied with microamps when you can have nanoamps? With Atmel MCUs today’s embedded designers get systems using a mere 650 nA running a real-time clock (RTC) and only 100 nA in sleep mode. Combined with several other innovative techniques, picoPower microcontrollers help you reduce your applications power consumption without compromising system performance!

Visit our website to learn how picoPower can help you hammer down the power consumption of your next designs. PLUS, get a chance to apply for a free AVR design kit!

http://www.atmel.com/picopower/

Everywhere You Are® © 2008 Atmel Corporation. All rights reserved. Atmel®, logo and Everywhere You Are® are registered trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.

picoPower 2008ad indd 1 8/8/2008 8:35:17 AM npn232.qxp 10/6/2009 12:00 PM Page 8

LPC314x DEVELOPMENT KIT The LPC3141 Developer’s Kit is a ready-to-use platform that will let you explore the many features of NXP’s LPC314x microcontroller series in general and the LPC3141 in particular. The kit is perfect for running Linux with its large on-board RAM and flash memory, network and graphics capabilities. Using the kit as a prototyping platform makes it pos- sible for you to focus on the value-added application. The kit includes all the software components needed to get up and running with software development on day one. It is easy to transfer the application and the OEM boar d from the prototyping environment into your final target application. The following resources are available at the kit’ s support site: a user’s manual, LPC3141 OEM board schematics, LPC31xx base board schematics, LPC31xx base board component placement, links to datasheets for key components, a multimedia presen- tation about how to get started with the boar d, and USB DFU drivers for Windows. NXP’s Common Driver Library framework has been used to develop a number of sample applications for the LPC3141 OEM board. Included in the kit are an LPC3141 OEM boar d, an LPC31xx base board v2.0, a USB cable, and a headset with microphone. Also included is a serial number that gives you access to the support site. The developer’s kit costs about $ 260.

Embedded Artists AB www.embeddedartists.com

COST-EFFECTIVE, TWO-CHIP PLATFORM FOR SMALL ENGINES Faced with world-wide emissions regulations and rising gas prices, the small engine market is migrating from mechanically carbureted systems to cleaner, more efficient electronic control and electronic fuel injection. To address the global need for these eco-friendly designs, the MCZ33812 combined with a 16-bit MCU pro vides a cost-effective platform solution that’s ideal for small engine control. A reference design consisting of the MCZ33812, an advanced analog integrated circuit optimized to control fuel and spark in EFI and electronic carburetion (e-carb) systems, and a Freescale S12 MCU is now available. This comprehensive small engine control platform helps lower harmful emissions and reduces system complexity , bill of materials, and manufacturing cost, while accelerating time to market. The device combines a voltage regulator, fuel injector driver, and ignition pre-driver, as well as a relay and lamp driver , a watchdog timer, and a reset generator—all optimized for small engine control. This exceptional integra- tion eliminates up to a dozen discrete components and reduces the circuit board area for engine mak- ers while also helping customers enhance the qual- ity and reliability of their products. The off-the-shelf MCZ33812 reference design allows developers to evaluate a two-chip solution based on the MCZ33812 and S12P MCU and emulate a complete small engine electronic control unit. The S12P delivers the performance benefits of a 16-bit MCU while supporting the entry-level pricing, low power, electromagnet- ic compatibility, and code-size efficiencies of an 8-bit MCU. The MCZ33812 is a commercial-grade device available now for production at a suggested resale price of $1.70 in 10,000-unit quantities.

Freescale Semiconductor www.freescale.com RODUCT NEWS NEW P Edited by John Gorsky November 2009 – Issue 232 November

8 CIRCUIT CELLAR® • www.circuitcellar.com npn232.qxp 10/6/2009 12:00 PM Page 9

USB MOTOR CONTROLLER WITH FEEDBACK The jrk line of USB motor controllers includes highly configurable, versatile devices that make it easy to add open- or closed-loop control of brushed DC motors to your computer- or microcontroller-based project. The jrk supports four interface modes: USB for PC-based control, logic-level (TTL) serial for use with embedded systems, analog voltage for simple potentiometers and joysticks, and RC pulse for radio con- trol systems. It can perform open-loop speed control, closed-loop position control with analog voltage feedback to make your own serv os, and closed-loop speed con- trol with frequency feedback from a tachometer. The jrk 21v3, the smaller of the two units currently available, has an operating range of 5 to 28 V and can deliver 3-A continuous output (5 A peak). The jrk 12v12, which is the more powerful of the two, has an operating range of 6 to 16 V and can deliver a continuous output of 12 A (30 A peak). Both devices can handle transients of up to 40 V . A free configuration program (Windows XP and Vista compatible) is available for calibrating your system. Real-time plots of variables—such as control input, feed- back, motor output, and current draw—make it easy to fine-tune settings, such as PID constants, acceleration, and current limit for your application. The unit price is $49.95 for the jrk 21v3 (item #1392) and $99.95 for the jrk Pololu Corp. 12v12 (item #1393). www.pololu.com

HIGH-VOLTAGE LINE DRIVER WITH MAGNETIC ROTARY IC INTEGRATED DC-DC CONVERSION The AS5215, a new dual-die, high-precision, analog sine The ZIOL2401 is a high-voltage line driver with IO-Link and cosine output, magnetic encoder IC tar gets redundant functionality. The first member of a family of high-vo ltage motion-sensing solutions for automotive microcontroller- line drivers, the chip offers two independent I/O-channels based systems. The IC is also ideal for safety-challenging that meet the physical layer requirements of sensor and applications such as electronic power steering systems. actuator systems used in factory automation applications. The amplitude of the AS215’s output signal is program- The ZIOL2401 combines an advanced two-channel IO-Link mable via sensitivity and gain settings. Due to its selec- driver with a DC-DC converter capable of producing up to table output mode signals—raw, inverted, or DC-refer- 15 V. This can power external sensors, as well as the enced—the AS5215 can fit a variety of conventional ZIOL2401, and it saves space and cost in boar d designs. motion-sensing systems which require measurement The IO-Link drivers are fully programmable, including slew redundancy for safety reasons. rate and current limitation, and off er complete diagnostics Based on a patented stacked-die solution, the dual die as well as over temperature protection. AS5215 provides excellent phase matching and very low The maximum current driven by the output stages can sensitivity drift over the full ambient temperature range of be set to a value that best fits the customer ’s application. –40° to 150°C. The AS5215 is available in a small TSSOP All configuration parameters are stored in an on-chip EEP- 14 package and operates at a 5-V supply vo ltage. ROM and automatically loaded during power-up. The The AS5215 is priced at $6.40 each in 1,000-unit ZIOL2401 reports all status information, such as an over- quantities. load condition or over-temperature. A SPI supports the access to configuration and status registers. In addition to austriamicrosystems IO-Link device and master ports, the device supports stan- www.austriamicrosystems.com dard I/O and works with both 3.3- and 5-V systems. It also offers wake-up detection and fast direct-event signaling. Unit prices start at $5 in vol- umes of 1,000 devices or more.

ZMDI AG www.zmdi.com

S NPN November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 9 npn232.qxp 10/6/2009 12:00 PM Page 10

8-BIT MICROS ON ULTRA-LOW-POWER TECHNOLOGY PLATFORM The STM8L product family comprises 26 devices in three lines spanning a broad spectrum of performance and function. They combine high-performance 8-bit architecture with ultra-low-power inno vations to save power in active modes as well as when idle. The lines are built on an ultra-low-power technology platform using a dedicated, proprietary 130-nm process optimized for ultra-low leakage. Unique advantages include full CPU performance up to the maximum operating frequency throughout the entire supply voltage range, from 1.65 to 3.6 V. Moreover, using an on-chip regulator, power consumption is independent of supply voltage, thereby providing extra flexibility and simplifying design. Other innovations include low-power embedded nonvolatile memory and multiple power-management modes including a 5.4-µA Low-Power Run mode, 3.3-µA Low-Power W ait mode, 1-µA Active Halt with full RTC, and 350-nA Halt mode. The device can wake from Halt within 4 µs, enabling frequent use of the lowest-power mode. Low-power peripherals include the sub-1-µA RTC and Automatic Wake-Up. Overall, this platform enables dynamic current consumption as low as 150 µA/MHz. The STM8L101 line is the entry point of the STM8L ultra- low-power 8-bit portfolio. Two other product lines making up the product range are scheduled for production in early 2010. The STM8L15x line adds extra features, including up to 32 KB on-chip flash and up to 2 KB SRAM, external crystal/clock capability, enhanced reset features, and support for DMA. There are also additional peripherals, on-chip EEPR OM with true Read While Write (RWW) capability. The third line, the STM8L152, features an integrated LCD controller. Family pricing starts with the STM8L101 4-KB flash version in QFN20 3 × 3 mm low-profile package at $0.68 in 10,000- unit quantities.

STMicroelectronics www.st.com NPN November 2009 – Issue 232 November

10 CIRCUIT CELLAR® • www.circuitcellar.com npn232.qxp 10/6/2009 12:00 PM Page 11

PROPELLER PROTOTYPING SYSTEM Parallax has partnered with SchmartBoard to create an easy Propeller prototyping system in the form of a kit. The P8X32A-Q44 SchmartBoard Kit (part number 27150) allows you to easily work with the surface mount Pro- peller chip. This kit is a perfect starting point. The SchmartBoar d technology makes surface-mount soldering easy. Once completed, the board will host the powerful microcontroller on this convenient development platform, allowing access to all 32 I/O pins of the multicore chip. The kit includes surface-mount and through-hole package types for some components, offering a soldering choice and challenge. The kit features the Propeller P8X32A-Q44 microcontroller along with header sockets for easy access to the Propeller I/O pins. Also included is 512 KB of EEPR OM for program and data storage, 3.3- and 5-VDC on-board regulators, surface-mount and through-hole components to populate the board, a barrel jack for a 2.1-mm cen- ter-positive 6- to 9-VDC power supply (not included), and a four-pin programming header for the Prop Plug (also not included). The P8X32A-Q44 SchmartBoard kit costs $39.95.

Parallax, Inc. www.parallax.com

NPN November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 11 npn232.qxp 10/6/2009 12:00 PM Page 12

TOUCH AND MOTION SENSING USB STARTER KIT The MPLAB Starter Kit for PIC18 Microcontrollers (part Hardware debugging and programming come integrated number DM180021), contains all of the components, docu- with the kit, meaning an additional debugger or programmer mentation, schematics, debugging, and programming capa- is not required. The kit is completely USB-powered, so a bilities needed to evaluate the high-performance PIC18 8-bit separate power supply does not need to be purchased. Pre- microcontroller (MCU) family in low-power USB and touch- programmed touch-sensing code, as well as a free USB sensing applications. The kit includes a development boar d application stack and bootloader, eliminate the need for featuring a 44-pin PIC18F46J50 MCU, mTouch capacitive engineers to develop their own code. Additionally, the board touch sensing, accelerometer, 64-KB flash program memo- includes demo application software that enables it to read ry, and much more. from the memory card (MSD), or function as a USB mouse or joystick (HID), or a simple COM port (CDC). By simply scrolling through code options using capaci- tive-touch buttons, you can demonstrate the PIC18 MCUs with a MicroSD memory car d, potentiometer, acceleration sensor, and OLED display. The Starter Kit includes the BMA150 digital triaxial accelerometer, which enables the board to detect acceleration in three perpendicular axes for sensing the board’s tilt and motion. The boar d ships with demo code that enables it to function as a USB mouse or joystick using the accelerometer. The accelerometer allows the cursor to mo ve slowly when the board is tilted a small amount, and quickly when there is a steeper tilt. The evaluation kit is available today for less than $60.

Microchip Technology, Inc. www.microchip.com

16-BIT ADC FOR INDUSTRIAL AND CONSUMER APPLICATIONS The ADS111x is a new family of 16-bit analog-to-digital converters packaged in a leadless QFN measuring 2.0 mm × 1.5 mm × 0.4 mm—70% smaller than the nearest competition. In addition to significant system space savings, the ADS1115 family pro- vides product options for scalable integration to reduce component count and simplify design. This family supports battery monitoring, portable instrumentation, industrial process control, smart transmit- ters, medical instrumentation, and other industrial and consumer systems. Designed for precision, power efficiency, and ease of implementation, the devices perform conversions at programmable data rates up to 860 samples per second, con- suming just 150 µA (typical) of supply cur- rent and operating down to 2 V. The ADS1115 is the most highly integrated member of the new family, incorporating an oscillator, low-drift reference, program- mable gain amplifier, comparator, and four- channel input multiplexer into a tiny pack- age. This family also includes 12-bit ver- sions for increased flexibility. Pricing for the ADS1115 starts at $2.25 in quantities of 1,000 units. The ADS1114 starts at $2 and the ADS1113 starts at $1.85.

Texas Instruments www.ti.com

November 2009 – Issue 232 November NPN 12 CIRCUIT CELLAR® • www.circuitcellar.com npn232.qxp 10/6/2009 12:01 PM Page 13

CHIP FERRITE BEADS OFFER 60% LO WER DC RESISTANCE The BLM15AX_SN series is an advanced ferrite bead that lowers DC resistance by up to 60% compared to previous models. As part of an expanding electromagnetic interference filter (EMIFIL) line, the chip ferrite bead was developed with new ceramic materials and processing technologies that improve performance and reduce size in order to provide power and space sav- ings in portable electronics. Compared to its predecessors, the BLM15AX_SN chip ferrite bead has a DC resistance as low as 0.02 Ω, a reduction of 60%, while the corresponding maximum rated current has increased from 1,000 to 1,740 mA. The series’s low DC resistance also helps reduce power consumption for battery-powered applications. Developed in a compact 0402-size package (1.0 mm × 0.5 mm × 0.5 mm), it is ideal for designers seeking to reduce board space without performance degradation in portable equipment. The ferrite bead’s wide impedance ranges from 10 to 1,000 Ω, with an operating temperature range of –55º to 125ºC. The BLM15AX_SN series is available for $0.016 and lead times are approximately six to eight weeks.

Murata Electronics North America www.murata.com

INDUSTRIAL-OUTPUT SIGNAL CONDITIONERS The MAX15500/MAX15501 industrial analog-output signal condition- analog outputs, distributed I/O, embedded sys- ers offer the industrial market a unique combination of higher func- tems, and industrial control and automation. Their tionality, greater integration, and smaller total solution size than com- high integration adds flexibility for designs. Use a petitive devices. They feature unprecedented integration: a program- single device for channel-isolated applications or mable voltage-output amplifier and a current-output amplifier; ±10 V multiple devices for group-isolated applications. and 4- to 20-mA outputs operating directly from a 24-V field supply; Typical competitive signal conditioners need pre- ±35-V circuit protection; extensive error-reporting capability; and cision-matched resistors to track voltages well over daisy-chain flexibility. temperature. The MAX15500/01’s integrated volt- The devices save board space and design time in 4- to 20-mA and age amplifier and voltage-to-current converter elim- bipolar/unipolar voltage-output applications. They are ideal for PLC inate the need for those additional resistors. Only the current gain-setting resistor is external to the device. The devices offer extensive fault detection, including open-circuit load in current mode, short- circuit load in voltage mode, over-temperature, and supply brownout. Both intermittent and permanent load faults can be detected. If a fault occurs, the open-drain fault-interrupt pin will be pulled low . The status of the fault bits is available through the SPI interface. With a higher ±24-V supply v oltage, the MAX15500/01 can handle a typical load of 750 Ω in current mode. With ±32.5-V supplies, this increases to 1,000 Ω. Additionally, the MAX15500/01 outputs, power-supply inputs, and sense inputs are protected against o vercurrent conditions, a short to ground, or supply v oltages up to ±35 V. Prices start at $2.96 (1,000-up, FOB USA).

Maxim Integrated Products www.maxim-ic.com

NPN 2009 – Issue 232 November www.circuitcellar.com • CIRCUIT CELLAR® 13 npn232.qxp 10/6/2009 12:01 PM Page 14

FANLESS FLEXIBLE CANbus WINDOWS CONTROLLER The CANatomBOX is a versatile, compact embedded con- troller targeted for embedded CANbus control applications. Based on Intel’s 945GME 1.6-GHz Atom processor, this con- troller box is application-customizable even in small quanti- ties, with a wide variety of har dware and software options. With 512-MB SD-RAM and 2-GB in CompactFlash, this sys- tem boots quickly, has passive cooling, with no mo ving parts at all. DIN-rail mounted units can be placed almost anywhere, due to the very small dimensions: (3.7 ″ × 6.3″ × 9.0″ for standard version; 5.7″ × 6.3″ × 9.0″ for two-PCI slot version). Standard interface connections for CANatomBOX are pro- vided on the front panel, and Windows Vista/XP/CE, Linux (or other choices such as QNX or VxW orks) can be preinstalled together with other application software to exactly fit cus- tomer needs. The CoDeSys SoftPLC runtime environment is also supported on this platform. RIGHT-ANGLE HIGH-DENSITY INTER- CANatomBOX features front-panel availability for two inde- CONNECTS The SEARAY high-density open-pin field-interconnect family pendent 10/100MBit/s Ethernet ports, status LED’s, an RS- is a new line of right-angle sockets for perpendicular and high 232 serial port, two opto-isolated CAN ports, two USB2.0 speed micro backplane applications. The SEAF-RA series ports, I/O lines, etc. Units are 10- to 28-VDC-powered, mak- have a 0.050″ × 0.050″ grid array for maximum grounding ing them ideal for battery-powered operation. All inputs fea- and routing flexibility and are optimized to reduce skew and ture ESD protection of 2 kV. impedance mismatch. They feature rugged Edge Rate con- Made in Europe by Janz AG, a leading industrial control tacts, which are designed for superior signal integrity , and CANbus manufacturer, the CANatomBOX is now avail- reduced broadside coupling and crosstalk, and high cycles. able exclusively in North America from Saelig Company , with SEARAY right-angle sockets are currently available in four - units starting at $1,399. row (up to 200 contacts) and six-row (up to 300 contacts) configurations. Eight-row (up to 400 contacts) and 10-row Saelig Co. designs (up to 500 contacts) along with a right-angle termi- www.saelig.com nal (SEAM-RA series) are in the final stages of development. This system mates with SEARAY surface mount terminal series, which has optional guide posts for blind mating, and a choice of tin-lead or lead-free solder char ged termination. Press-fit tail terminations are currently in development. SEARAY surface-mount systems with up to 500 single- ended or 125 differential I/Os, coax cable assemblies with 180 or 240 I/Os, and high-density flex jumpers are also available. Pricing begins at $0.05/pin in 1,000-piece quantities.

Samtec, Inc. www.samtec.com

NPN

STATEMENT REQUIRED BY THE ACT OF AUGUST 12, 1970, TITLE 39, UNITED STATES CODE SHOWING THE OWNERSHIP, MANAGEMENT AND CIRCULATION OF CIRCUIT CELLAR, THE MAGAZINE FOR COMPUTER APPLICATIONS, published monthly at 4 Park Street, Vernon, CT 06066. Annual subscription price is $29.95. The names and addresses of the Publisher, Editorial Direc- tor, and Managing Editor are: Publisher, Sean Donnelly, 4 Park Street, Vernon, CT 06066; Editorial Director, Steven Ciarcia, 4 Park Street, Vernon, CT 06066; Managing Editor, Carmine J. Abate, 4 Park Street, Vernon, CT 06066. The owner is Circuit Cellar, Inc., Vernon, CT 06066. The names and addresses of stockholders holdi ng one percent or more of the total amount of stock are: Steven Ciarcia, 4 Park Street, Vernon, CT 06066. The average number of copies of each issue during the preceding twelve months is: A) Total number of copies (net press run) 19,292; B) Paid/Requested cir- culation (1) Mail subscriptions: 7,211; (3) Sales through dealers and carriers, street vendors and counter sales: 4,974; (4) Re quested through other USPS classes: 211 C) Total paid/requested circula- tion: 12,396; D) Nonrequested distribution (by mail and outside the mail) (1) Outside county nonrequested (sample copies): 1,76 4; (4) Nonrequested copies distributed outside the mail (trade shows, other sources) 1,666; E) Total nonrequested distribution: 3,430; F) Total distribution: 15,826; G) Copies not distributed: 3,46 6; H) Total: 19,292; (I) Percent paid/requested: 78%. Actual number of copies of the single issue published nearest to filing date (October 2009, Issue #231); A) Total number of copies (net press run) 18,0 10; B) Paid/Requested circulation (1) Mail subscriptions: 6,656; (3) Sales through dealers and carriers, street vendors and counter sales: 5,105; (4) Requested through other USPS classes: 187; C) Total paid/requested circulation: 11,948; D) Nonrequested distribution (by mail and outside the mail) (1) Outside county nonrequested (sample copies): 1,714; (4) Nonrequested copies distributed outside the mail (trade shows, other sources) 995; E) Total nonrequested distri- bution: 2,709; F) Total distribution: 14,657; G) Copies not distributed: 3,353; H) Total: 18,010; (I) Percent paid/requested: 82%. I certify that the statements made by me above are correct and complete.

November 2009 – Issue 232 November Sean Donnelly, Publisher. 14 CIRCUIT CELLAR® • www.circuitcellar.com eq-232.qxp 10/6/2009 12:02 PM Page 15

Test Your CIRCUIT CELLAR Edited by David Tweed EQ

Problem 1—While reverse-engineering an LCD Problem 2—What is the purpose of R1, R2, module with LED backlight, a colleague came and Q1? across this circuit and had tr ouble figuring it out. Let’s see if we can help him out. Problem 3—What can you say about the LED current with respect to the actual voltage on point A?

Problem 4—What can you say about the LED current with respect to ambient temperature?

Point A connects to one of the external pins of Contributed by David Tweed the module and appears to be used for switching the backlight on and off. First of all, what is the purpose of R4?

What’s your EQ?—The answers are posted at www.circuitcellar.com/eq/ You may contact the quizmasters at [email protected] November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 15 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 16

by James Stephanick EATUREARTICLE F Embedded Linux-Based Location System

You can build your own vehicle location device without br eaking the bank. This article details how to use a few r eadily available parts—an ARM-based USB network storage link, a pr epaid GSM cell phone, and a USB-GPS device—to build an easy-to-configure location system.

fter the second time my car was stolen APRS installation. When the car was on, a ham radio out of my driveway, I began looking for and GPS unit were used to beacon the car ’s location anA inexpensive way to track my vehicle’s location. every 3 minutes. Random, privately-owned receivers The first solution I implemented was a ham radio located seemingly everywhere picked up the beacon and forwarded the car’s location to the Internet. By tapping into the APRS network or using a publicly available website, I could view the car’s location (and even its path over the pre- vious 24 hours) on Google maps. This worked well. But due to the cost of all the com- ponents—including the radio, radio installation, antenna mount, antenna, electronics to modulate the digital data, and the smart controller to turn on/off the radio—it wasn’t the most affordable solution (and it requires a ham license). When searching for commer- cial vehicle-tracking solutions, I typically found expensive hardware, service contracts, fairly high monthly fees, and devices that were not particu- larly versatile. At one point, I

Photo 1—The assembled vehicle locator includes a Linksys NSLU2 USB Network storage link, a Motorola GSM phone, and a Deluo USB-GPS device. November 2009 – Issue 232 November

16 CIRCUIT CELLAR® • www.circuitcellar.com 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 17

stumbled across an inexpensive GPS GSM modem targeted at just this type of appli- cation. However, its fixed set of features and inability to enable custom processing were shortfalls. After experimenting with embedded USB controllers for a while, I finally determined that an off-the-shelf Linux solution would be far cheaper, faster to prototype, and easier to modify than microcontroller code. Instead of develop- ing and fabricating a custom solution for vehicle tracking, I used an affordable off- the-shelf Linksys unit I found on the Internet to construct a highly versatile, easy-to-configure, embedded Linux-based vehicle locator. In addition to a 5-V power supply, three devices connected with USB cables complete the setup: a Linksys NSLU2 USB Network storage link (i.e., a Photo 2—I installed a 100-µF electrolytic capacitor between pin 4 of U15 and ground. network-attached storage, or NAS, device), The placement was not critical, so I put the capacitor on the top of the board. a Motorola V195 prepaid T-Mobile GSM phone, and a Deluo USB-GPS device (see Photo 1). The only requirements for this project’s mobile phone were that it support AT-style modem commands (for SYSTEM OPERATION sending and receiving text messages) and that it be able Although my design is simple, it achieves its objec- to connect to a host via a USB cable that also doubles as tive. It has three primary features. One, every time my a phone charger. The Motorola V195 worked nicely. The car starts, the design sends an SMS message to a default only requirements for the GPS device were that it con- phone number with a Google Map link to the car ’s cur- nect to and receive its power from the host via a USB rent location. Two, if the car is r unning, I can locate it cable. The Deluo USB-GPS device I used is based on a by sending an SMS message (with a password) from any Motorola SiRFstarIII chipset. phone. When the unit receives the SMS message and v er- Assembling this project is simple. Plug the phone’ s ifies the password, it responds with a Google Map link USB cable and the USB GPS device into the two USB that indicates the car’s current location. Three, I can ports of the NSLU2. After that, you’re almost done. modify basic configuration parameters using a network There’s only one assembly-related catch. Out of the box, connection and an Internet browser. Configuration param- the NSLU2 device won’t automatically power-up when eters include the default phone number (to notify me via power is supplied. For unattended operation, this is an an SMS message when the car star ts), the ability to enable absolute requirement. Luckily, the NSLU2 can be easily or disable start-up SMS notifications, and the ability to reworked to automatically power-up by soldering in a set the authorization password for SMS location requests. 100-µF electrolytic capacitor between pin 4 of U15 (i.e., When using an Internet-connected phone—such as an R94) and ground. Since placement is not critical, it can Apple iPhone or Google gPhone—it is quick and easy to be installed in a convenient hole at the cor ner of the read the SMS message. You can then see the car ’s loca- board. This enables it to be installed on the top of the tion on a Google map. board where there is enough case clearance (see Photo 2). If you want to make the unit “stealthy” and not beep COMPONENTS & ASSEMBLY when booting up, you can tr y to cut off the buzzer. The NSLU2 USB network storage link has 8 MB of flash memory and 32 MB of SDRAM. It uses an ARM- EMBEDDED LINUX & SlugOS based Intel IXP420 processor and r uns at either 133 or The secret and the magic to using Linux and the 266 MHz. By removing a sur face-mount resistor, the older NSLU2 device as a controller comes from an open- 133-MHz version can be modified to r un at 266 MHz. The source project: www.nslu2-linux.org. The NSLU2-Linux device contains two USB ports and one network jack. development group and user community “discuss, devel- Connection points are available for adding a JT AG port, op, and modify the fir mware and hardware of the an additional USB port, and serial ports. After it is re- NSLU2.” In addition, with a complete binar y (SlugOSBE- flashed with an embedded Linux image, the original 4.8-beta-firmware.zip) from the website and re-flashing NAS functionality is replaced and the device can the NSLU2 firmware with “SlugOS/BE,” the road to an become an embedded controller. embedded controller is very straightforward. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 17 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 18

Start

Initialize variables Figure 1—This is the flowchart for the main control loop.

Attach port 80 monitor

Network New config connection on parameters? Yes port 80?

Update config parameters No Output HTML status

GPS Device Yes Able to read Yes Desirable GPS known? GPS? sentence?

No Yes No No

GPS Device Yes Able to open attached? GPS device? No

Yes

Configure GPS TTY Port

No GPS Device GPS Device Record position now known not known

Modem Modem still Something to Correct known? Yes available? Yes read? Yes password? Yes

No No No No Send SMS with position

Modem Yes Able to initialize attached? modem? No Power-up SMS send? No

Yes

Yes GPS Device now GPS Device not Send one No known known power-up SMS November 2009 – Issue 232 November

18 CIRCUIT CELLAR® • www.circuitcellar.com 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 19

After pulling the NSLU2 out least four concurrent log-ons of the box, the network param- enabling the one-device editing eters and administrative pass- of multiple script files and a words need to be configured. shell from which to execute the Then you must put the NSLU2 scripts. To simplify editing, I into Upgrade mode by holding in used the “nedit” mouse-based the Reset button (requires a source editor and edited the files paper clip) for approximately 10 s using the Ubuntu virtual and pressing/releasing the machine. The Ubuntu virtual Power button once. In Upgrade machine had the scripts located mode, either “Sercomm’s in a network share to which the Win32 tool” (Windows) or NSLU2 had executable access. “UpSlug2” (Linux) can be used After debugging and completing to transfer the SlugOS image the scripts, I copied them to the and re-flash the firmware on NSLU2 using “scp.” the NSLU2. Although designed to work TCL IMPLEMENTATION with an external disk, the pre- SlugOS on the NSLU2 is a compiled SlugOS image is a complete embedded computer minimal Linux configuration with a multitasking operating Photo 3—This is the web interface for status and that can run entirely from configuration. I used Mozilla Firefox, but you can use system, an impressive array of internal flash memory without the browser of your choic e. development tools, and signifi- a disk or network share. The cant driver support for hard- minimal configuration takes up ware. As such, multiple pro- about 75% of the 8-MB flash memo- The easiest way to configure and gramming languages are available ry, leaving sufficient room to add an operate the NSLU2 reconfigured (e.g., C, C++, Perl, and TCL). available TCL script interpreter with SlugOS is to use secure-shell I chose to use TCL for several rea sons. (package “tcl”), a USB driver (pack- (“ssh”). The SlugOS will allow at One, it is an interpreter. Writing, age “kernel-module-usbserial”), a USB-to-serial port driver (package “kernel-module-pl2303”), and a com- munications modem driver (package “kernel-module-cdc-acm”).

DEVELOPMENT ENVIRONMENT Having a complete Linux desktop environment makes the NSLU2 con- figuration and programming task much easier. It allows easy access to main pages, editors, development environments, windowing systems, and a host of other tools. Instead of building up a machine to host the Ubuntu Linux distribution, I used Sun’s xVM VirtualBox and ran Ubun- tu as a virtual machine on top of Vista. (Make sure you have 3 or 4 GB of memory.) This provides the best of both worlds, having two computers operating with the same mouse and keyboard. For network connectivity, the virtual machine should be config- ured to use the local subnet by put- ting in the host network controller into Bridge mode. If the vir tual machine is using NAT instead of being bridged, access to the vir tual machine from the NSLU2 is difficult. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 19 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 20

testing, and debugging is quick. stand code written by expert Perl remote configuration. Highly optimized and efficient object coders). code is not necessary. Two, it greatly The one issue I stumbled across CONTROL LOOP & CODE simplifies string processing with with TCL was the legacy convention TCL is not necessarily rich in data access to high-level constructs such of interpreting numbers with leading structures, but that is not necessary as regular expressions. Three, there zeros as base-8 numbers. Because the in this small application. I wrote this is easy access to shell commands. code pulls parameters out of fixed- project old-school style, with a heavy Four, it has constructs making it length strings, there is a function to dependence on a handful of global trivial to listen for TCP/IP conn ec- strip leading zeros so as to not mis- variables and only a single threa d. As tion and communicate with the net- interpret the integer’s value. such, it is not difficult to under- work. The fifth reason is that I’ ve I completed this project using less stand, debug, or enhance. found the TCL syntax easier to than 400 lines of TCL code. This The control loop comprises three understand than Perl (especially for included simulating a web server to top-level functions: monitoring con- new programmers trying to under- provide network-based status and nections to the mini web ser ver, monitoring the GPS device, and monitoring the mobile phone modem (see Figure 1). Monitoring port 80 of the network connection to simulate a mini web server takes only a couple lines of code. socket –server websocketproc 80 sets up the callback routine websocket- proc to handle any port 80 connec- tions. Inside the main control loop, update relinquishes the processor to address any outstanding network connections and to call websocket- proc when appropriate. The func- tion websocketproc (contained in the source code posted on the Circuit Cellar FTP site) reads any data from the connection, looks for parameters to update, and then dumps HTML status information back to the port. With this technique, the device can be configured and queried for status information from any web browser (see Photo 3). To query the device sta- tus, simply use its IP address as the URL (e.g., http://192.168.100.4). To update a parameter, put the parameter name and new value between ques- tion marks (e.g., http://192.168.100.4/ ?sendonesms=1?). Monitoring the connection and dis- connection along with the GPS device’s datastream is also straightforward. This is a fixed-purpose embedded device and not a general-purpose computer, so the simplifying assumption was made that any USB device detected by the system (/dev/ttyUSB?) must be the GPS. Once detected, the device serial connection is configured to interact nicely with the expected data rate and buffering options . The process of monitoring the con- nection and disconnection, along with incoming SMS messages, from November 2009 – Issue 232 November

20 CIRCUIT CELLAR® • www.circuitcellar.com 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 21

the mobile phone modem uses essen- port is put back into non-blocking deleted with the AT+CMGD command. tially the same techniques as reading mode and the control loop proceeds The previously read message is in the GPS datastream. Any devices to loop normally. then searched for the password and detected by the If the control loop detects an originating phone number. If the (/dev/ttyACM?) are assumed to be incoming message from the mobile password is found, the last known phone modems. If an unexpected read phone, the incoming string is tested position (encoded in a web URL) is error occurs when accessing the to see if it is a “+CMTI” message used as the SMS payload for the device, the device is assumed to be indicating an incoming SMS. If it is, return message to the originating disconnected. The next time through, the SMS message number is extract- phone number. the top-level loop will try to detect ed from the sentence and used to and reinitialize. query the actual SMS text by using LINUX DAEMON the AT+CMGR command. After the In the same way, the device needs to SENTENCE PARSING message is read, it is immediately automatically power-up when the The Deluo GPS device conveniently adheres to the National Marine Elec- tronics Association (NMEA) standard of position reports. Typing “nmea gps for- mat” in a search engine produces a large quantity of reference material. All the characters in the standard are print- able ASCII text (plus carriage return and line feed). The characters are sent at 4,800 bps and comprise sentences whose fields are delimited with com- The Next Generation of Character Display mas. One of the most interesting asso- ciated with this project is the sentence that starts with: $GPGGA (global-posi- tioning system fix data). The fields of a All New Y Series $GPGGA sentence provide the UTC time Vacuum Fluorescent Display of the fix, the latitude, the longitude, the altitude, and the number of satel- lites being tracked. In one statement, the TCL code uses a regular expression to match to the $GPGGA sentence prefix characters and extract the above data. With this accomplished, the data is massaged slightly and put into web URL form that works with Google Maps. On an Internet-connected phone (e.g., an iPhone or gPhone), it is easy to click through to the Google Maps from the received SMS.

SEND & RECEIVE COMMANDS Highlight Characters The modem TTY port is generally configured in a non-blocking Read Wide Temperature Range (-40 °c - +80 °c) mode. This enables the control loop to poll the mobile phone asking for any Display More Characters new data. If data is not available, it continues on to its other tasks. Selectable Font Sizes When the controller wants to send “AT” messages to the phone, it tem- International Font Table porarily puts the port into Blocking mode. In this way, the control loop Serial Interface stalls, waiting for the mobile phone to reply with its standard “OK” or 1 ( 800)8 0 0 ) 7797 7 9 - 58465 8 4 6 “ERROR” response. Once the expected response is received, the www.noritake-elec.com November 2009 – Issue 232

www.circuitcellar.com • CIRCUIT CELLAR® 21 2911017_Stephanick.qxp 10/6/2009 12:05 PM Page 22

engine is switched on. The TCL V195 has an impressive battery life time zones (instead of simply repor t- script must automatically start to with a quick recharge cycle. As a ing UTC time). I also want the execute when the Linux device fin- result, I haven’t dealt with this fail- design to temporarily shut off the ishes booting. A Linux daemon ure mode because I drive the vehicle power-up SMS capability at certain accomplishes this. I created an exe- nearly every day. And since I expect times of the day. I cutable shell script that launches and an SMS with every vehicle trip, I can forks the primary TCL script detect a dead battery right away. James Stephanick (BSEE, MSEE, MBA) (/bin/sh /root/main.tcl &) and The second shortcoming is a tem- began designing and programming placed it in the /etc/init.d direc- porary failure mode. The capacitor real-time embedded image-processing tory. With that complete, I created a solution to automatically power-up systems to automatically analyze cytol- file system link to it in the f ollowing the Linux device may not work if t he ogy specimens. Later, his career path manner: power is not removed long enough. took to him to the mobile phone indus- Specifically, if the car ignition is set try where he led the Tegic engineering ln –s /init.d/executableshellscript to “accessory” and then you turn the team. James is now leading the engi- /etc/rd3.d/S99executbleshellscript key to start the car, the transient neering team at Cequint, a Seattle- power loss may turn off the Linux based start-up company that provides DESIGN REVIEW device without discharging the enhanced caller ID solutions for North The programmed vehicle locator capacitor and therefore not restart American mobile phones. You may con- design is working reliably in one of the device. However, the next time tact him at [email protected]. my vehicles. However, this off-the- the car is left off for 5 minutes, it shelf hardware solution has two pri- will proceed to boot nor mally. Note mary shortcomings. The first is that that there are other power-on hacks P ROJECT FILES if the vehicle is not operated fre- available to get around this short- To download the code, go to ftp:// quently enough, the mobile phone coming. They completely disable the ftp.circuitcellar.com/pub/Circuit_ battery completely discharges Off button should you use this con- Cellar/2009/232. (because the phone doesn’t turn off). troller for other purposes. Eventually, the phone shuts off and I’m considering a few new features for doesn’t restart. Luckily, the Motorola the design. I want it to accom modate RESOURCES Developers’ Home, “Short Mes- sage Service/SMS Tutorial,” keil.com www.developershome.com/sms/. 1-800-348-8051 GPS Info, http://gpsinformation. Development Solutions for net/. NSLU2-Linux development group ARM, 8051 & XE166 Microcontrollers and user community, http://www. nslu2-linux.org/. Microcontroller RTOS and Middleware Development Kits Components TCL Developer Xchange, www.tcl. tk. C and C++ Compilers RTX Kernel Source Code

Royalty-Free RTX Kernel TCPnet Networking Suite SOURCES μVision Device Database & IDE Flash File System USB-GPS Device Deluo LLC | www.deluogps.com μVision Debugger USB Device Interface Ubuntu 8.10 Desktop Edition Examples and Templates Examples and Templates Complete Device Simulation CAN Interface Canonical Ltd. | www.ubuntu.com

Keil PK51, PK166, & MDK-ARM Keil RL-ARM and ARTX-166 Linksys NSLU2 USB Network support more than 1,700 highly optimised, royalty-free storage link microcontrollers middleware suites Cisco Systems | www.linksysby cisco.com

VirtualBox Open-source virtual- ization software Download the μVision4 Beta Version keil.com/uv4 | www.sun.com November 2009 – Issue 232 November

22 CIRCUIT CELLAR® • www.circuitcellar.com 23.qxp 9/25/2009 10:43 AM Page 1

The Newest Semiconductors

New Products from:

Green Mode PWM Controller: UCC28600 www.mouser.com/ tipowermanagement/a

STM6904 / STM6905 Multiple Voltage Supervisor www.mouser.com/st/a

Analog Power Supply / Power Management Devices www.mouser.com/freescale/a

The ONLY New Catalog Every 90 Days

Experience Mouser’s time-to-market advantage with no minimums and same-day shipping of the newest products from more than 390 leading suppliers.

The Newest Products For Your Newest Designs

www.mouser.com Over A Million Products Online (800) 346-6873

Mouser_CircuitCellar_11-1.indd 1 9/14/09 10:24:04 AM 40-41.qxp 8/5/2009 9:53 AM Page 40 40-41.qxp 8/5/2009 9:53 AM Page 41 2911015_Rios.qxp 10/6/2009 12:24 PM Page 26

by Noel Rios EATUREARTICLE F Energize a Circuit An Innovative Switched-Mode Power Supply Design

Energy control is an essential aspect of many electronic applications. If you build a switched-mode power supply (SMPS), you can regulate a design’s current to meet your specific project goals.

a)

ost engineers, technicians, and designers need M power supplies for energizing their cir- cuits. Do you? You can use a power supply instead of batteries. If portability is not a requirement, a power supply is a viable alternative to batteries because it costs less to use. It’s nice if you can adjust the volt- age, but it is even better if you can also modify the current. The switched-mode power supply (SMPS) I recently designed enables you to adjust the voltage from 0 to 20 V and the current from 0 to 1 A (see Photo 1). You can change the voltage and current by entering the value on the keypad and checking the b) output on the 2 × 16 LCD module. As you can see in Figure 1, the SMPS is built around a Maxim Integrated Products DS89C430 microcontroller. Figure 2 shows the digital portion of the design. Figure 3 depicts the analog portion. In this article, I’ll describe the project from start to finish.

FLYBACK REGULATOR A flyback regulator works by storing energy in the core material. The energy is stored while the power switch conducts. The power transformer of a flyback converter is not really a transformer but an inductor. After the power switch stops conducting, the power transformer flies back or reverses in polarity. That is why the phasing of the power transformer of a flyback transformer has the opposite polarity when compared Photo 1a—As you can see, the SMPS’s front panel features an LCD with a to a “forward” converter. The energy stored in the core backlight. b—Take a look inside the DS89C430-controlled SMPS. The two material is transferred to the secondary winding by 60-Hz transformers are for the auxiliary supply of the analog part. The induction. The filter capacitor smoothes the regulator’s other 60-Hz transformer powers the digital part. It’s clear why 60-Hz output. The topology used in this design is a diagonal transformers are needed. November 2009 – Issue 232 November

26 CIRCUIT CELLAR® • www.circuitcellar.com 2911015_Rios.qxp 10/6/2009 12:24 PM Page 27

Control PC and Interrupt SFRs sequencer Internal DPTR AR INC registers DPTR1 AR CPU SP Decoder

IR Address bus

Internal control bus

16 KB/32 KB Timer/ 1 KB x 8 Serial I/O counters 64 KB x 8 I/O Ports RAM Flash memory

Watchdog timer Clock and and Memory ROM power manager reset control Loader

P0 P1 P2 P3 EA RST PSEN XTAL1 XTAL2 ALE/PROG Figure 1—I used a Maxim Integrated Products DS89C430 microcontroller for this SMPS project. I chose it for its speed and because it is i n- system programmable.

flyback for a variable SMPS. It uses two power MOSFET source of the DC Bus voltage. switches and two fast-recovery diodes. The MOSFET, fast- recovery diodes, and the flyback transfor mer’s primary is CIRCUITRY connected in such a way that when no energy transfer is The heart of the circuit is a DS89C430 microcontroller made to the secondary, the energy stored in the primar y (U1), which is an 8051-compatible microcontro ller. It has winding of the flyback transfor mer is returned to the three timers, two serial ports, and 1-KB MOVX RAM. I

Figure 2—This is the digital portion of the SMPS. It dictates the voltage that the analog portion outputs. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 27 2911015_Rios.qxp 10/6/2009 12:24 PM Page 28

Figure 3—This is the analog portion of the SMPS.

chose this microcontroller for its is a SPI peripheral. The DS89C430 has other for voltage setting. C3 (10 µF), speed and because it is in-system no SPI port, so it is done by bit bang- R3 (10 kΩ), and D1 (1N4148) for m a programmable. You don’t need a ing. The MAX550 (U3) is a single seri- reset circuit for the microcontroller. device programmer for programming al DAC. It is an 8-bit device. Its out- As the capacitor charges, a voltage is the DS89C430. All you need is to put is 0 to 2 V. The circuit uses two generated across the resistor and the configure the microcontroller’s pins DACs, one for current setting and the voltage tapers off as the capacitor is and connect a MAX232 so you can fully charged. The diode discharges connect it to a PC’s serial port (see the voltage across the capacitor once Photo 2). You can use HyperTerminal the supply is turned off so the micro- or any terminal software. After you controller will reset again if the sup- have applied the power, you must ply is turned off and on in an inst ant. press the Enter key so that the C1 (30 pF) and C2 (30 pF) act as microcontroller can detect the data load capacitors. They are needed by rate. However, I discovered that the the internal oscillator together with maximum data rate is 19,200 bps. the crystal (Y1) to act as the clock The DS89C430 controls both the for the microcontroller. C12 (0.001 DACs and the ADC. It also reads the µF) and C13 (0.001 µF) act as a filter keypad and processes the numbers for the DAC. C14 (10 µF) and C15 for the proper voltage. Photo 2—I used a Dallas Programmer to act as supply decoupling, while C10 The MAX1111 (U2) is a serial ADC. program the DS89C430. It is merely a (0.1 µF) and C11 (0.1 µF) act as a fil- It has four inputs that can be config- socket with a MAX232. A device programmer ter capacitor. C4 acts as a filter ured as single-ended or differential. I t isn’t needed. capacitor for the entire circuit. November 2009 – Issue 232 November

28 CIRCUIT CELLAR® • www.circuitcellar.com Microchip Direct... Microcontrollers Digital Signal Analog Serial 2nd line Controllers EEPROMs www.microchip.com/ICD2recycle MPLAB® ICD 2 RECYCLE and 2 ICD MPLAB old your Return MPLAB new the off 25% receive 3 PICkit™ or ICE REAL MPLAB 3, ICD Debug Express. For more information please on this offer, visit: s ® Microcontroller In-Circuit Debugging he Next Generation of T ww.microchip.com/ICD3 w In-Circuit Debugging for PIC MCUs and dsPIC DSCs dsPIC and MCUs PIC for Debugging In-Circuit Full-speed, real-time emulation complex breakpoints and debugging, stopwatch, Source in-circuit programming compatible IDE MPLAB upgrade via MPLAB IDE Firmware Overvoltage and undervoltage protection Mbps) (480 2.0 USB Speed High MA 100 to up power, Target speed download increased for memory 1 MB buffer Internal

t t t t t t t t t The NEW MPLAB® ICD 3 ICD MPLAB® NEW The most cost Microchip’s 3 In-Circuit Debugger is ICD The MPLAB PIC Flash Microchip for debugger effectivehigh-speed (MCU) and dsPIC® Digital Signal Controller devices. It debugs and and debugs It devices. Controller Signal Digital dsPIC® and (MCU) yet DSCs with the powerful, dsPIC and MCUs PIC programs Development Integrated of MPLAB user interface graphical easy-to-use (IDE). Environment

PICkit is a trademark of Microchip Technology Incorporated in the U.S.A. and other countries. © 2009, Microchip Technology Inco Technology Microchip 2009, © countries. other and U.S.A. the in Incorporated Technology Microchip of trademark a is PICkit rporated. All Rights Reserved. Rights All rporated.

T he Microchip name and logo, the Microchip logo, MPLAB and PIC are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. other and U.S.A. the in Incorporated Technology Microchip of trademarks registered are PIC and MPLAB logo, Microchip the logo, and name Microchip he 11.qxp 9/2/2009 4:06 PM Page 1 Page PM 4:06 9/2/2009 11.qxp 63.qxp 1/7/2009 3:20 PM Page 1 2911015_Rios.qxp 10/6/2009 12:24 PM Page 31

A TL494 (U1) voltage-mode PWM controller is the heart of this Flyback mode power supply. Inside this IC is an oscillator with a sawtooth wave- form output, two err or amplifiers, a comparator, commutation logic, and a r eference. The PWM principle is “ straightforward.

Diodes D2 and D3 (1N4734) act as if the gate drive circuit is defective. protection components and conduct MOSFET Q12 and MOSFET Q15 when the supply exceeds 5.0 V. It is (04N60C2) act as a power switch for better for the Zener diode to get dam- the supply and conduct at the same aged in the case of reverse polarity or time. It changes the steady DC sup- overvoltage instead of the microcon- ply to a square wave with a varying troller, DACs, or ADC. The LCD duty cycle. To increase the voltage module (U5) is an HD44780-based output, the pulse width is length-” display, which displays the voltage ened. If a smaller voltage i s needed, and current. the pulse width is made shor ter. Capacitor C3, choke T1, and C4 Resistors R58 and R59 (100 Ω) and form an EMI filter so noise will not capacitors C29 and C30 (0.001 µF) propagate to the mains. Because the act as a parallel snubber. It protects MOSFET switches rapidly and the the MOSFET 04N60C2 by absorbing bulk capacitor C2 charges quickly, it the energy as the MOSFET ceases to generates some noise that could conduct. Two recovery diodes (D14 affect other equipment. The choke and D15) connected to the primary has no value since I took it f rom an winding return the energy to the DC old power supply. D1, D2, D3, and bus if there is no energy transfer D4 (1N54007) act as a rectifier for between the primary and secondary. the mains voltage. It converts the IC U8 (IR2117) is a high-side gate AC voltage to DC voltage. C2 acts drive IC, which is the gate d rive for not only as a filter, but also as stor- the high-side MOSFET (see Photo 3). age for the energy to be delivered by Transformer T2 is a power trans- the supply. former with a ferrite core. A power Resistor R19 acts as a series resist- ferrite is needed because of the fre- ance to the gate of the MOSFET Q12. quency the transformer operates. If The resistor prevents the MOSFET you use an iron core, it heats up from oscillating because a voltage is because of eddy currents. This is impressed across the gate and source. why a 60-Hz transformer has a lami- Resistor R26 discharges the voltage nated core because of the losses. By across the gate of the MOSFET and using a laminated core, the circuit source of the MOSFET. This is path is limited to a single laminate. because the gate and the source of The power ferrite transformer con- the MOSFET form a capacitor that verts the high-voltage DC to a small- holds a charge. If there is a voltage er value by making the w indings across the gate and source, this will have a turns ratio according to the leave the MOSFET in the “on” con- voltage you will need. By the way, in dition. It will be damaged if powered Flyback mode converters, the power up, and the Texas Instruments TL494 transformer is not a transformer at PWM controller will also be damaged all but only an inductor. As the November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 31 2911015_Rios.qxp 10/8/2009 12:13 PM Page 32

Schottky diode (D6) converts comparator. The larger the error volt- the square wave AC to a pul- age, the wider the comparator’s sating DC. A Schottky rectifier pulse. The comparator’s output is is needed because of its fast connected to the commutation logic recovery time. As you know, and then to the output transistors. In an ordinary diode does not stop my application, I used a single-ended the flow of current in an output by grounding the output con- instant as the voltage reverses trol pin of the IC. R21 (10 kΩ) and in polarity. C11 (0.001 μF) are connected to the A TL494 (U1) voltage-mode oscillator of the PWM IC, which dic- PWM controller is the heart of tates the switching frequency of the this Flyback mode power sup- power supply. The isolated Flyback Photo 3—This is the close-up view of the MOSFET’s ply. Inside this IC is an oscilla- mode power supply’s switching fre- gate drive at 5 V with a 0.5-A load. The load is tor with a sawtooth waveform quency is 100 kHz. light, so the MOSFET’s gate drive is not regular. The output, two error amplifiers, a R18 (1 kΩ), Q13 (2N3906), R17 (1 kΩ), gate drive is just enough to keep the voltage at 5 V comparator, commutation logic, Q9 (2N3904), Q10 (2N3904), and D1 and the current at 500 mA. and a reference. The PWM prin- (1N4148) form the power supply’s ciple is straightforward. gate drive circuit. A totem pole was MOSFET conducts, it stores energy First, the sample voltage from the used because the MOSFET must be in the inductor. As the MOSFET output of the power supply is fed to switched on and off rapidly. If the ceases to conduct, the energy is the noninverting input of the error switching of the MOSFET is slow, released to the secondary winding. amplifier and the reference of the this will result to switching losses Also note that the power transformer supply is fed to the inverting input of that will heat the MOSFET. or inductor has windings that are out the supply. After the two voltages are R20 (1 kΩ) switches on Q13 of phase. True transformers have compared, an error or control voltage (2N3906). C23 (10 μF), R43 (10 kΩ), and their windings in phase and do not is generated at the output of the R44 (1 kΩ) act as a soft start circuit. store any energy, unlike the power error amplifier. This error voltage is It controls the duty cycle of the transformer of a flyback regulator. A compared to a sawtooth voltage by a PWM IC after it is powered up. The November 2009 – Issue 232 November

32 CIRCUIT CELLAR® • www.circuitcellar.com 2911015_Rios.qxp 10/6/2009 12:24 PM Page 33

duty cycle slowly ramps up after the Frequency 50 kHz conducts as the switch in the capacitor charges. R55 (10 kΩ) and MAX738 opens up. As the 1N5829 BMAX 0.3 tesla R56 (10 kΩ) scale the voltage V to conducts, the energy in the inductor REF A 0.7 cm2 (core area) 2.5 V, which is fed to the error E is delivered to the load. A 1.3 cm2 (core window area) amplifier. R39 (510 Ω), R40 (510 Ω), W I used two 60-Hz transfor mers for the N 268 turns R37 (510 kΩ), and R38 (510 kΩ) gives PRIMARY TL494’s auxiliary supply. I used another

gain to the error amplifier and also NSECONDARY 27 turns 60-Hz transformer for the supply of the makes the error amplifier linear. AWG Primary 30 digital part, which uses the MAX738. I If there are no resistors, the er ror AWG Secondary 26 did this because I couldn’t add separate amplifier will only act like a com- windings from the power ferrite trans- parator, and it will have only two val- Table 1—These are the parameters of the former because the power supply’s out- ues—0 or the maximum output of the power transformer. The operating frequency put drops to zero. As the supply of the power ferrite core should be equal to error amplifier, which is 5 V or V . decreases to zero, the voltage on the REF or greater than 50 kHz. R42 (10 kΩ) and R41 (10 kΩ) pull auxiliary winding also drops to zero. In down the error amplifier’s input so some power supplies, a series pass pre- the error amplifier will function prop- C1 (47 µF) acts as a filter capacitor. regulator makes the circuit run as the erly. Optocouplers U5 (4N35) and U6 R49 (100 Ω) acts as a minimum load power is applied. However, this is good (4N35) isolate the output from the necessary for the stability of the supply. only if the auxiliary supply takes over input. The LED inside the optocoupler D9 and D11 (1N4001) act as a rectifier as the power supply runs. The series lights up if the power supply’s sam- that converts AC to DC. C12 (220 µF) pass preregulator has a low efficiency pled output is greater than the refer- and C21 (470 µF) act as a filter capaci- as a linear regulator, so I decided to use ence—in our case, it is the DAC. tors. Resistors R35 (510 kΩ) and C18 a 60-Hz transformer for the auxiliary R22 (2.2 kΩ) and R23 (2.2 kΩ) limit (0.1 µF) act as a soft star t for the power supply. I used another 60-Hz the current flowing through the opto- MAX738 (U7). C17 (0.01 µF) acts as a transformer to power the digital par t. couplers. A MC34072 (U4) high-per- filter for the MAX738’s reference. C19 formance op-amp acts as an er ror (330 pF) acts as a compensation for the CONSTRUCTION & ASSEMBLY amplifier on the secondary side. C13 MAX738. The D7 (IN5819) Schottky This project involves exposure to (100 pF), C14 (0.0833 µF), and R24 diode acts as a commutating diode that high voltage, which could lead to (317 kΩ) act as a compensation circuit for the op-amp. Compensation is need- ed because the power supply might oscillate at varying load conditions. The compensation circuit varies the op- amp’s gain and decreases at –20 db as the frequency increases. Pole-zero com- pensation is used. It is applicable for discontinuous Flyback mode regulators, and it also alters the phase of the op- amp’s output so that it doesn’t return to 360°. Remember that negative feedback provides a 180° phase shift. Resistors R1 (0.1 Ω), R2 (100 Ω), R3 (1 kΩ), R48 (10 kΩ), and U2 (MC34072) op-amp act as a current detector. Resistor R1 (0.1 Ω) acts as the resistive sensor for the current detector. As current passes through the resistor, a voltage drop is generated across the op- amp’s inputs. The higher the cur rent, the greater the difference at the op- amp’s inputs. This makes the op-amp’s output increase to make the MOSFET (Q14) conduct, which pulls down resis- tor R2 (100 Ω) until the voltage at the op-amp’s noninverting and inverting pins are equal. Resistors R36 (10 k Ω) and R5 (560 Ω) act as a voltage divider to sample the regulator’s output. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 33 2911015_Rios.qxp 10/8/2009 12:14 PM Page 34

electrocution or a fire if you don’t important which is clockwise and use the correct fuse rating and the counterclockwise. Just be sure you proper design. If you are a novice, wind in opposite directions.) The consider switching to a linear power direction of the primary winding is supply using a 60-Hz transfor mer. not important because one of the You can use a presensitized PCB primary’s terminals is connected to for the digital and analog pa rts. I the positive DC bus. The other is made my own PCB layout, b ut connected to the MOSFET’s drain, I’ve since made corrections, so I which switches the transformer to won’t recommend it. It is better if ground. After the power switch you make your own PCB using opens, the terminal of the primary your own PCB layout software. winding connected to the positive The most critical part of this Photo 4—Take a look at the transformer ’s output. DC bus becomes negative, and the The Schottky diode blocks the negative v oltage switch mode-isolated flyback one connected to the MOSFET’s generated when the MOSFET conducts and when power supply is the power trans- the transformer stores energy. The Schottky diode drain becomes positive. former. Whether or not the power is forward-biased when the MOSFET becomes an When the power switch opens on supply functions depends on the open switch, which you can see in the waveform, the secondary side, the polarity of transformer. Table 1 includes the and has a potential of 5 V. The filter capacitor the secondary winding’s terminal specs of the power transfor mer and smoothes the pulsating DC, which becomes a regu- connected to the Schottky diode ferrite E and I core. lar DC voltage and is the power supply’s output. becomes positive, and the other ter- I computed the core area product: minal becomes negative. Thus, the

AP = AE × AW. But I used a larger core, wire neatly and tightly so that the Schottky diode is forward-biased and which enables me to handle more coupling of the primary and secondary delivers the energy stored in the core power, and there is a less chance that is good. Wind the primary clockwise material. The secondary delivers the the ferrite core will saturate. Make and the secondary counter clockwise. stored energy in the core material only sure the power ferrite core is rated for It’s important that you wind the two after the MOSFET becomes an open 100 kHz or else the core will heat up in opposite directions; otherwise, your switch because of the Schottky diode. due to core losses. Wind the magnet power supply won’t work. (It is not The Schottky diode blocks the voltage November 2009 – Issue 232 November

34 CIRCUIT CELLAR® • www.circuitcellar.com 2911015_Rios.qxp 10/6/2009 12:24 PM Page 35

when the transformer is storing ener- construction, such a connection may supply, connect a 10-V potential at gy while the MOSFET conducts (see damage the MOSFET, the 1N5407, or the output of the supply and adjust Photo 4). the power ferrite transformer. R38 (10-kΩ multiple-turn trimmer) so Use the right gauge or a lower First, apply a 12-V DC voltage to that the wiper arm’s output or voltage gauge number for the primary and J7 and use an oscilloscope to monitor reading pin is 10% of the output. secondary to minimize copper losses. the output of the PWM controller Also, make the PCB trace (of the out- TL494. You should see a square wave USING THE POWER SUPPLY put of the transformer) to the power output at pins 9 and 10 on the TL494 For an output of 5 V, simply key in supply’s terminal block wide enough and at the gate pin on the IRF840. If 5.00, or press 5 and then the # key, so that there will be no voltage drop the TL494’s supply drops to a low which acts like an Enter key while across the output. I bolted the power value, check if the totem pol e gate the * symbol acts as a decimal point. MOSFET to the supply’s chassis so it drive circuit is shorted. Also, check The same goes for the current. The runs cool even under full load. If you for a sawtooth output at pin 5 on the power supply’s maximum voltage is can’t make the trace wide enough, TL494. In addition, check for a 5-V 20 V. The maximum current is 1 A. apply solder to it to increase its cur- potential at pin 14 on the TL494. If Please note that there will be no rent capacity. While you’re testing you adjust the voltage from 0 to 2.5 V output if you enter a voltage on the the power supply, never bypass the using a separate power supply at pins keypad and you don’t enter a current fuse or use a breaker with a low cur- 1 and 16 on the TL 494, you should setting because the power supply rent rating. I used a circuit breaker see the duty cycle vary at the output will be in a constant cur rent mode. with a 0.5 A rating. of pins 9 and 10. Also, if the voltage is not reached Check the polarity of bulk capaci- after the load is applied, adjust the TROUBLESHOOTING tor C2 or it will explode. Be sure the current until the voltage is correct. Don’t be discouraged if the sup ply primary winding is connected to th e doesn’t work the first time after con- MOSFET’s drain. The secondary POWERFUL SMPS struction. If it doesn’t work, consider should be connected to D6 (1N5822). My SMPS can be used f or powering the following tips. After performing all of the afore- any circuit that uses up to 20 V and Test the digital and analog parts mentioned checks, look to see if there a current up to 1 A. The voltage separately. Connect a 5-V supply to is 24 V powering U2 (MC34072) and input is 220 V, which is the voltage the digital part. Enter a voltage on U4 (MC34072) and the optocouplers in our country. If your mains supply the keypad. The output of the volt- U5 and U6 4N35 are good, or else is 110 V, close the switch so the volt- age DAC should be from 0 to 2 V, this will cause the PWM controller to age doubler will function. You can and the output of the current DAC is output a maximum duty cycle with also use a 12-V exhaust f an to cool from 0 to 1 V. If the DAC has no out- the control loop not functioning the SMPS in case the ambient tem- put, check if there is a pul sating sig- properly. Before testing your power perature in your area is high. I nal on the SCLK, CS2, CS3, or DIN after the voltage is entered on the Noel Rios ([email protected] and [email protected]) is an electronics design keypad. Also, check for a 2.048 V at engineer who has worked with various semiconductor and electronics companies the reference pin of the DACs. This like Microcircuits, IMI, Allegro, ASTEC, Stratex, Inno vatronix, Applied Systems, and 2.048 V comes from the ADC Micrologic. His interests include computers, embedded control, power conversion, (MAX1111). Check if the ADC and GPIB control, and testing and measurement. Noel accepts C firmware development work and subcontractor jobs that inv olve the 8051 (and 8051 derivatives), digital DAC have their V CC and GND con- nected properly. Apply a voltage to circuits, and analog circuits. the ADC’s inputs from 0 to 2 V and check if the display is cor rect. If not, check for a pulsating signal on the P PROJECT FILES SCLK, DIN, DOUT, CS1, or SSTRB. To download the code, go to ftp://ftp.circuitcellar .com/pub/Circuit_Cellar/ Please note that if the LCD mod- 2009/232. ule is defective, or if the AD C is defective, it will hang the pro gram because it polls the busy flag on the S OURCES LCD module (and if the conversion is DS89C430 Microcontroller finished on the ADC by polling Maxim Integrated Products | www.maxim-ic.com/direct SSTRB). You should also check if the REFOUT pin is connected to the MC34072 Op-amp ADC’s REFIN pin. ON Semiconductor | www.onsemi.com For the analog part, don’t connect to the mains if you are n’t sure of TL494 PWM Control circuit your design. If there is an e rror in the Texas Instruments, Inc. | www.ti.com November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 35 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 36

by Carl Stoesz EATUREARTICLE F Precision Linear Encoder Display

Linear encoders are essential parts in many industrial automation applications. Here you learn how to mount an optical linear encoder to a metal lathe used to create small precision parts. A few affordable parts and some C code enable you to transmit vital displacement and speed data to an LCD.

manual 7″ metal lathe is ideal for creating small began investigating various linear encoders. I was looking precision parts. However, a manual lathe does for something that could match the resolution of the Anot come with any means of m easuring the shape of a compound and cross-slide indicators. part while it’s being worked. Typically, the machinist must measure, cut, remeasure, and then repeat the LINEAR TRANSDUCERS process until the desired dimension is reached. Linear transducers come in all sorts of styles. One When using a manual lathe, you have three mea ns of commonly used linear transducer is the linear variable controlling the cut. The first i s with the cross-slide that’s differential transformer, or LVDT. The LVDT has three mounted to a carriage (see Photo 1a). The cross-slide sets of coils placed end to end around the tube. The cen- controls the cutting bit perpendicular to the work piece. ter coil is the primary, and the outer two coils are the It allows a machinist to faceoff the en d of a part and secondaries. A ferrometalic core is attached to an object move the cutting bit in and out for turning the diameter. and run through the tube. An alternating current is driv- The second way to control the cut is with the com- en through the primary causing a voltage to be produced pound rest or top slide. This sits atop the cross-slide and in the secondary that is proportional to that of the pri - holds the cutting bit. The c ompound rest can be used to mary. These devices had the precision I required; howev- cut angles and make fine depth a djustments in turning er, when I began investigating them, I f ound out that operations. Both the cross-slide and the compound rest they were just plain too long. For example, an LVDT have vernier indicators stamped in a ring for deter mining with an 8″ stroke had a 31″ body, which was longer than their movement with a 0.001″ resolution. Driven by the my lathe. They were also quite expensive, so I moved on. need for accuracy, I installed inexpensive electronic indi- I remembered scrapping an HP DeskJet printer and cators that perform the same task with more conven- finding inside a strange plastic str ip just behind the print- ience and have a resolution of 0.00 01″. er cartridges. An optical encoder strip! When I scrap ped The third option is to control the car riage travel. The the printer, I saved both the encoder strip and the reader . carriage travels axially along the part and thus controls The optical reader was an Agilent HEDS-970 0 quadrature the axial placement of the cutting tool mounted on it. encoder with a TTL output. A quick Internet search gave The carriage travel on my lathe is less than 12 ″. A com- me technical data, so I promptly hooked up the reader and mercially available means of accurately determining car- encoder strip to my counter and a micrometer . I was disap- riage travel is expensive, costing several times what I pointed that the resolution was only about 0.007 ″—good paid for the lathe in t he first place! enough for a printer, but not quite enough for this project. So, driven by the need for precision on all fronts, I I carefully tucked the encoder strip away for another day . November 2009 – Issue 232 November

36 CIRCUIT CELLAR® • www.circuitcellar.com 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 37

Up Down

A tQ1

B

x4_CLK (see note)

x2_CLK (see note) tQ2 x1_CLK (see note)

Note: x1, x2, and x4 CLKs are internal up/down clocks derived from filtered and decoded quadrature clocks.

Figure 1—These are A and B quadrature signals and options of X1, X2, and X4 decoded outputs. Using X4 gives the highest resolution.

Another option would have been to us e what is some- have been only 0.0039″ per bit. That wouldn’t have been times referred to as a “yo-yo,” or a pot string encoder . good enough. I would have had to go up to a 16-bit ADC This is a string or wi re wound around a spring-tensioned to get good enough resolution. I considered purchasing a drum attached to a multi-turn potentiometer. As the chip, but I still wasn’t quite satisfied. I kept looking. string is pulled off the pulley and tur ns the potentiometer, One day while browsing on e-Bay, I found the solution: a ratiometric voltage is produced that can be conver ted a 12″ optical linear encoder with a 1-µm resolution man- into displacement. Would this work? If I used, s ay, a 0.5- ufactured by RSF Elektronik. Typically, an optical linear to 4.5-V range with the built-in 10-bit ADC in a Microchip encoder uses a glass scale with a light source on one side Technology PIC microcontroller, the resolution would and a set of four photosensors on the other. A scanning reticle with four windows sits in front of the photo- IR. The IR is an 8-bit register that fetches instruction bytes from B2 B1 B0 = XXX (Don’t care) sensors. The reticle and the received datastream and executes them to perform such B5 B4 B3 = 000: Select none functions as setting up the operating mode for the chip (load the = 001: Select MDR0 photosensors are spaced to MDR) and data transfer among the various registers. = 010: Select MDR1 = 011: Select DTR give signals that are 90° B7 B6 B5 B4 B3 B2 B1 B0 = 100: Select CNTR apart. The signals are then = 101: Select OTR = 110: Select STR combined to produce two = 111: Select none B7 B6 = 000: CLR register symmetrical sinusoidal out- = 001: RD register = 010: WR register puts 90° out of phase. Some = 011: LOAD register encoders output this signal

The actions of the four functions — CLR, RD, WR, and LOAD — are elaborated below. directly. My unit converts it to a TTL quadrature signal. Number of bytes OP Code Register Operation The optical encoder fit 1 CLR MDR0 Clear MDR0 to zero MDR1 Clear MDR1 to zero perfectly on the back of the DTR None bed (see Photo 1b). The unit CNTR Clear CNTR to zero OTR None was ideal, but I couldn’t STR Clear STR to zero afford the display. At work, 2 to 5 RD MDR0 Output MDR0 serially to TXD (MISO) I’ve purchased quadrature MDR1 Output MDR1 serially to TXD (MISO) DTR None displays for about $500, CNTR Transfer CNTR to OTR, then output OTR serially on TXD (MISO) OTR Output OTR serially to TXD (MISO) which is way outside my STR Output STR serially to TXD (MISO) budget. So, I set out to

2 to 5 WR MDR0 Write serial data at RXD (MOSI) into MDR0 make my own with what I MDR1 Write serial data at RXD (MOSI) into MDR1 had on hand. I came close. DTR Write serial data at RXD (MOSI) into DTR CNTR None OTR None DESIGN OVERVIEW 1 LOAD STR None The optical encoder out- MDR0 None MDR1 None puts a TTL quadrature sig- DTR None nal (see Figure 1). A quadra- CNTR Transfer DTR to CNTR in “parallel” OTR Transfer CNTR to OTR in “parallel” ture signal has an A and a B component that are 90° out Figure 2—These are IR register commands and the ef fects of the four functions: CLR, RD, WR, and of phase. This arrangement LOAD. The register to be operated on is specified in B5–B3. The action to perform is contained in B6 works well to convey dis- and B7. (Source: LSI Computer Systems) placement by counting the November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 37 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 38

transition edges and direction by Listing 1—Communicating with the LS7366R is simple. The write_register8() func- determining which signal comes tion is used to set up the counter . It is also used to mo ve the count contents to buf fer first, A or B. Each cycle of data con- OTR immediately prior to a read to prevent missing counts. tains four transitions, two on A and two on B. void write_register8(int cmnd, int data) There are three ways the transi- {// Examples: // write_register8(CNTR_CLR, 0); clear counter tions can be counted that determine // write_register8(MDR0_WR, CNTR_AB | FREE_RUN | CNTR_OTR); set the resolution of the measurement // MDR0 as a free counter, on index transfer CNTR to OTR (see Figure 1). The first way is the 1 × // write_register8(OTR_LD, 0); move CNTR contents to OTR for OTR read method, where the count is obtained RA5=1; RA5=0; only on the transition of A for each SPI_WRITE(cmnd); // set IR to write to specified register full cycle. This gives the coarsest reso- SPI_WRITE(data); // send data lution. Alternatively, the 2× way is to RA5=1; count the transition on A and the } transition on B for each cycle. This is twice the resolution of 1×. The finest loop (PLL) to increase the cl ock The back of the specification sheet resolution is the 4× mode where each speed to 40 MHz. As it tur ned out, I for the serial counter contains assem- transition of A and B is counted. I had an old compiler version that did bly code for the serial interface to a wanted the finest resolution, so I was not support the PLL option. Purchas- PIC18Cxxx. I prefer to work in C lan- looking to implement the 4× mode. ing a new compiler for this p roject guage. So, using the assembly code as My first approach was to use a was not an option. a guide, I wrote my own driver com- Microchip Technology PIC18F2320 For my final approach, I br oke patible with my CCS compiler. because I had several on hand. I was down and purchased an LSI Comput- The serial interface is a synchro- thinking of decoding the signal er Systems LS7366R 32-bit quadra- nous four-wire SPI bus controlled by directly using the interrupt on ture counter with a serial interface. (I the microcontroller’s SCK clock. change available for Port B. Then I bought two for about $30.) This put Each transmission is organized in thought about the carriage travel all of the processing burden on the blocks of 1 to 5 bytes of data. Com- speed. In a hurry, I can move the car- LS7366R and left the PIC18F2320 munication is initiated by a high-to- riage several inches per second. At 2″ with almost nothing to do. There is low transition of the SS pin. The per second, I would need to decode a more than one way to skin a cat. first byte received is always an total of 101,600 pulses and then dis- instruction byte. The second play the results in real-world units. COUNTER through fifth bytes are data. The Running at the maximum of 40 MHz, The LS7366R quadrature counter communication is terminated by a I would need to decode to di splay in has loads of features for all sorts of low-to-high transition of the SS pin. 98 instructions. With a floating-point comparator, counting, or quadrature Data is shifted into the MOS I pin multiply required, that approach interface operations. It can use the most significant byte (MSB) first on went right out. index signal from the encoder to out- high-transition leading edges of the My second approach was to use an put two marker flags that can be SCK clock. Data is shifted o ut of the LSI Computer Systems LS7084 quad- used as alarms or trigger microcon- MISO pin MSB first on low tra nsi- rature clock converter, which I had troller interrupts. These can also be tion trailing edges of the SC K clock. on hand. The LS708 reads the qua d- used for over travel or set point trav- Write commands cannot be com- rature signal and outputs a clock and el indication. At 5-V operation in bined with read commands. a direction, thus simplifying the single-count mode, it has a maxi- The counter can be configured as a interpretation. All I had to do was mum counting frequency of 40 MHz. 1-, 2-, 3-, or 4-byte counter. All the monitor the direction and then incre- It is configured with read and wri te registers will automatically adjust to ment or decrement a counter in operations over the SPI to function the specified byte width. For exam- interrupt. Four times a second, the in the desired mode of op eration. In ple, if the counter is configured as a PIC performed a floating-point mul- quadrature mode, it has ×1, ×2, or ×4 2-byte counter, it expects 2 bytes in tiply and displayed the results o n an mode decoding with a filter. It can be reading and writing operations fol- LCD. I thought everything was fine set to Modulo-N, Non-recycle, or lowing the instruction byte. If 3 bytes until I hooked up a bench-top count- Range-limited operation. It can be set are sent to a 2-byte configured chip, er to the LS7084 and compared the to 8-, 16-, 24-, or 32-bit configura- then the third byte is ignored. results to the PIC18F2320 output. I tions. A status register stores count- The LS7366R uses five registers: was missing counts, so I changed the related events such as carry, borrow, DTR, CNTR, STR, MDR0, and crystal and upped the processing index latch, power loss, direction, MDR1. DTR is an input data register speed. I was still missing counts and sign. The counting register can for storing values to be written to the when I moved the carriage too fast, be zeroed or an initial value can be CNTR. It is also used for Modulo-n so I tried the inter nal phase-locked placed in it. and Range-limit comparisons. CNTR November 2009 – Issue 232 November

38 CIRCUIT CELLAR® • www.circuitcellar.com 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 39

a) b)

Photo 1a—This is a typical manual metal-working lathe. Y ou can see the cross slide with indicator (1), the compound top slide with indic ator (2), the carriage hand-wheel for axial travel (3), a tool post (4), and a spindle with chuck (5). b—I mounted the optical linear encoder (6) to the back of the bed. It is mounted upside down to prevent debris from entering the slide.

is the counter, which tracks up and encoder index, count enabled, power to really see how simple it is to con- down counts from the quadrature loss, count direction and sign. figure and read a count (see Listing 1). clock signal at A and B. In non-quad- MDR0 and 1 set the operating mode Let’s first clear the counter. I set up rature operation, it counts each up for the counter. the driver defines so I didn’t have to and down pulse on input A. The The IR command byte controls the constantly transfer instructions to CNTR can be cleared, loaded from the LS7366R (see Figure 2). The appro- hex. The IR command for clearing DTR, or transferred out to the OTR. priate register is selected with bits 3 CNTR is 0x20 or CNTR_CLR. We The OTR serves as a buffer for CNTR. to 5. One of four o perations on that want to write a single byte. Using To prevent missed counts, the CNTR register is selected in bits 6 and 7. my driver interface, the program line data is transferred to the OTR and The four operations are Clear (CLR), is simply write_register8(com- then the OTR is output to the MISO Read (RD), Write (WR), and LOAD. mand, data), or write_regis- pin. STR is the status register indicat- All those specifications are pretty ter8(CNTR_CLR,0). Diving into ing carry, borrow, compare event, dry. There is nothing like an example the routine, you see what happens. First, the SS pin (RA5 in this case) is toggled high (just to make sure it Listing 2—Read_register32() is used to obtain a 32-bit count value. The SS line actually is high) then low. Using the (RA5) is toggled low, followed by setting the IR register to read. The counter value is CCS compiler’s built-in then read in a loop and assigned to the return variable. SPI_Write() function, the com- mand is written followed by the data. signed int32 read_register32(int reg)// Read 32-bit counter The SS pin is then toggled high. I { // Examples // write_register8(OTR_LD, 0); software request to move used multiple write_register8() // counter to OTR for a read commands to configure everything // counter = read_register32(OTR_RD); read counter from OTR the way I wanted. // to avoid missing counts Now let’s try a counter read (see int i; int temp; int32 data=0; RA5=1; Listing 2). The first thing to do i s to RA5=0; move the counter data to the OTR SPI_WRITE(reg); // Set IR to read register register so you can read it at your for(i=0;i<4;i++) leisure and not lose any count s. This { temp=SPI_READ(0x55); // Send 0x55 with read to // generate clock for counter is done by the line write_regis- data = data<<8; ter8(OTR_LD, 0). You next read all data= data | temp; 32 bits with counter = read_reg- } ister32(OTR_RD). Again, stepping RA5=1; return data; into the routine you see what hap- } pens. First, SS is toggled low and the read command is sent using November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 39 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 40

SPI_WRITE(OTR_RD). We then loop in handy if you are doing any com- returns the remainder of a division. through four SPI_READ() cycles to parisons. I wasn’t, so I left it for For example, 38 ≡ 2 (mod 12), or in read each byte. Notice that I had to another day. English, 38 mod 12 = 2. T his feature send 0x55 with each read to generate While I was setting up the dri ver, I can be used to count the number of a clock for the counter. That took played around with some of the events in a cycle. This is like count- some time to debug. In fact, it drove other modes. In single-cycle counter ing in base 12. Say you want to me nuts for a week. I ’m not sure if it mode, you quickly discover that i t count only from 0 to 11 in a cycle. is a compiler thing, a P IC thing, or counts each transition, so be careful Set the DTR register to 11. The an LS7366R thing. It worked, s o I with that. The range limit counting LS7366R then returns count ≡ x used it. The data is ORed together allows you to count only so high. It (mod n + 1). An example of this and then returned. Finally, SS is tog- then stops until you reverse direction. would be for counting the hours in a gled back high, ending the command. The Modulo-n counting was some- day and tracking AM and PM from a I started a 32-bit write command thing I haven’t seen before in quadra- free-running counter. but never finished it. It would come ture displays. The Modulo-n operation THE PROGRAM The program is written in C lan- guage. It displays displacement on the first line and carriage bed travel speed on the second line. I wanted to zero the display at any time and convert the readings and display metric or English units. I also want- ed to have it come up in units previ- ously used when the display was turned on. Take a quick look at the program posted on the Circuit Cellar FTP site. Variables are set up, ports are configured for proper I/O, and the LCD and counter are initialized. A unit flag is read from EEPROM and the display units are set before entering the main loop. Here you look for the Zero button and the Change of Units button to be pressed. You then read the counter, convert to real-world units, and dis- play. Nothing fancy. There is one thing to note on the conversion of units: 1 µm = 0.00003937″. This means that at 9 µm you have 0.000354″, which will be displayed as 0.0004″ and 10 µm will also be displayed as 0.0004″. Thus, we have a loss of resolution in the English units. I’ve run into this problem before. It is even more pro- nounced when converting tempera- ture units of Celsius to Fahrenheit. For example, 25.1°C converts to 77.1°F, while 25.2°C converts to 77.4°F. If you are trying to display 0.1°F, you have a real problem! For my application, I can live with miss- ing a few ten thousandths of an inch. This also falls within the accu- racy of the system. There was one calibration that had November 2009 – Issue 232 November

40 CIRCUIT CELLAR® • www.circuitcellar.com 5.qxp 9/2/2009 4:24 PM Page 1 Ja eco_CC_ _Oct09 8/ /09 : 5 age

What is the missing component?

Industry guru Forrest M. Mims III has created a stumper. Video game designer Bob Wheels needed an inexpensive, counter-clockwise rotation detector for a radio-controlled car that could withstand the busy hands of a teenaged game player and endure lots of punishment. Can you figure out what's missing? Go to www.Jameco.com/unravel to see if you are correct and while you are there, sign-up for our free full color catalog.

1-800-831-4242 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 42

Photo 2—Take a look at the completed project box. The green PCB board contains the PIC18F2320. The board at the top contains the LS7366R. There is plenty of room for a sec- ond daughter board.

to be performed for accurate bed for a PIC16F873. All the pins travel speed display. During the mapped over to the PIC18F2320, development stage, I used a pin to which was quite nice. That board toggle an LED on and off. I use this was one of my first and there were as a heartbeat to indicate that the lots of errors. I didn’t include a pic- PIC is in the do loop and function- ture of the underside where I made ing. To calibrate the bed travel speed, all my corrections. I simply hooked up my data acquisi- I used a separate prototype board tion card to the heartbeat and deter- for the LS7366R and connected it to mined the time per loop. This value the PIC with a header and cable. I was then hard-coded into the soft- then placed both boards inside a proj- ware. I wasn’t too concerned with ect box and tacked them in place bed travel speed accuracy. Bed travel with a spot of glue. There is no speed is an indication of the feed rate power switch. Simply plug in the when making an axial cut by hand. It wall wart to turn it on. If I use this is used for reference only. more than anticipated, I’ll end up installing a power switch. PROJECT BOX Refer to the circuit diagram (see PERFORMANCE: STOP TO STOP Figure 3). The encoder inputs A and How does it all perform? The only B are connected to LS7366R input way I could think of to compare the pins 12 and 11, respectively. The two signals was to connect the clock connected to fCKi and fCKO is counter to the A channel of the required for the filter when in quad- encoder, multiply by two, and then rature mode. The serial SPI commu- divide by 1,000 to get the LCD when nications are on pins 4 to 6 and con- in metric units. This was as good a nect directly with the PIC18F2320 method as I could think of to com- SPI pins with the exception of SS, pare. It is not perfect because the which is connected to RA5. counter cannot work with a quadra- The assembled project box is shown ture signal. I then ran the carriage in Photo 2. I used a prototyping from stop to stop manually as fast as board I had made several years ago I could and then very slowly. November 2009 – Issue 232 November

42 CIRCUIT CELLAR® • www.circuitcellar.com 2911014_Stoesz.qxp 10/6/2009 12:36 PM Page 43

Figure 3—This is the entire system. The counter chip sits on a separate board and is connected to the main board with a cable.

I noted a typical stop-to-stop er ror Carl Stoesz ([email protected]) is a mechanical engineer who works as a of six to 10 counts between the research and development engineer for Baker Hughes. His focus is on the integration of bench-top counter and the display. fiber optic sensors into oil wells for the company’ s Intelligent Well Systems group. Carl At least two of those counts can be enjoys playing in the electrical engineering sandbox in his spare time. attributed to the lack of channel A signal when changing directions. I purchased my counter on e-Bay for P PROJECT FILES $10 so it is not likely to be a highly To download the code, go to ftp://ftp.circuitcellar .com/pub/Circuit_Cellar/ accurate piece of equipment. A 2009/232. sticker on it says the last time it was calibrated was 1987! Either way, I can certainly live with a ±10 µm RESOURCES accuracy. Agilent Technologies, “Small Optical Encoder Modules, Technical Data, The LS7336R is a sweet li ttle chip HEDS-9700 Series,” http://content.honeywell.com/sensing/sensotec/. with more than enough muscle for Microchip Technology, “PIC18F2220/2320/4220/4320 Data Sheet,” this project, so much so that the DS39599G, 2007, www.microchip.com/stellent/idcplg?IdcService= SS_GET PIC18F2320 is not working hard at _PAGE&nodeId=64. all. I even had to inser t a delay loop to slow down the update rate on the The Sensors Reference, “Input/Output Devices: Linear E ncoder Information & display. With extra processing avail- Linear Encoders,” Machine Design, www.sensors-transducers.machinedesign. able, what else can be don e? At some com/guiEdits/Content/bdeee4/bdeee4_3.aspx. point, I would like to add a rotar y encoder to the spindle to determine the spindle RPM. I would also like to SOURCES read a spindle angle with 0.5° accura- HEDS-9700 Quadrature encoder cy (or better) to accurately place Agilent Technologies | www.agilent.com angular marks on a project for cir- LS7366R Quadrature counter cumference division. I have plenty of LSI Computer Systems | www.lsicsi.com room for a second board in my proj- ect box and more than enough pro- PIC18F2320 Microcontroller cessing power to accomplish this. I Microchip Technology | www.microchip.com November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 43 2911016_deBrebisson.qxp 10/6/2009 1:04 PM Page 44

by Cyrille de Brebisson EATUREARTICLE F How to Repurpose a Development Platform

With some knowhow and little bit of cr eativity, you can pop open an HP financial calculator and use its electr onics to develop a variety of special- purpose applications. This article shows you how to use the calculator ’s screen, keyboard, and PCB as a development platform.

ast year, Hewlett-Packard (HP) introduced a new HP also introduced a new version of the venerable calculator. By itself, this could be of great interest HP12C based on the same Atmel microprocessor . Like toL a Circuit Cellar reader; however, this is not the point of this ar ticle, especially as the HP 20b Business a) b) Consultant happens to be geared toward financial calculations. No, what is important to a Circuit Cellar reader is that this calculator is rela- tively inexpensive (around $40 retail price), it has a screen, it has a keyboard, and it has a connector on the PCB that gives access to a serial or RS-232 port, eight GPIO lines, four ADC channels, and the JTAG programming interface of a 36-MHz Atmel AT91SAM7L128 ARM-based system on a chip (SoC) with 128 Kb of flash ROM and 6 KB of RAM (see Photo 1). In other words, HP created a calculator that is also a versatile development platform. Thus, you can use this calculator for small- or medium-quantity special-purpose devices. Applications could range from software-only modifications (e.g., a device designed to help implement a company’s specific processes or calculations) to a soft- ware/hardware hybrid with the cal- culator connected to external hard- ware (e.g., a weather station or automation controller). The possi- Photo 1a—This is the HP20b calculator. b—The HP20b, inside out! The Atmel microprocessor bilities are endless! is hiding under the Bakelite “blob” and the JT AG connector at the bottom. November 2009 – Issue 232 November

44 CIRCUIT CELLAR® • www.circuitcellar.com 2911016_deBrebisson.qxp 10/6/2009 1:04 PM Page 45

sign that it was opened. The last step in opening the calcula- tor involves separating the top and bot- tom cases. The two parts are held together with 10 “clips,” three on each side and two at the top and bottom. The best way to open the calculator is to start by popping the middle clip on the Photo 2—The HP20b screen has both a numerical display and a matrix area for text or left side, located between the Input and graphic display. the CashFlow keys. Insert a small flat screwdriver between the black and grey the 20b, it has a serial por t, but it does not h ave the plastic, push outward, and the clip should pop out. You JTAG and other exposed inputs and outputs. can then use your thumb an d press down and out on the grey plastic to pop the two other clips located next to the PLATFORM OVERVIEW screen and Shift keys. Use the screw driver to remove the The calculator by itself is about 15 cm × 8 cm × 1.5 cm bottom two clips. After that, you should have no problem and weighs around 110 g. Two 3-V CR2032 lithium bat- opening the calculator with your hands alone. (Decreas- teries—which are expected to last for one year—power ing the use of the screwd river reduces the chances of the calculator. In addition to a 37-key keyboard, the cal- damaging the calculator’s finish.) culator has a 400-segment screen that has a 15-digit, seven-segment display area at the bottom (12 large num- PROBE THE PCB bers and three smaller ones), a couple of indicators on the The AT91SAM7L128 is a low-power ARM7 SPU/SoC top right, and a 6 × 43 pixel matrix that’ s suitable for dis- that can run at up to 36 MHz. It has 128 KB of flash playing text or small graphics (see Photo 2). ROM, a 400-segment screen driver (as far as I know, this If you remove the battery door, you will see a small six- is the first commercially available ARM7 CPU with a pin connector. The connector is designed primarily for direct LCD driver), 6 KB of RAM, and the standard slew software updating. (You can update any calculator with a of peripherals. Refer to Figure 1 for more details.[1] new version of software without having to open it.) This is The AT91SAM7L128 has a lot of advantages for this possible because the microcontroller is flash memory-based application: it has a built-in LCD controller, it’s low- and not ROM-based. But you can also use the “serial port” as power; it has its own power supply (allowing it to work part of an application that needs a serial communication for directly from the 3-V battery without any external debugging. HP has a cable that plugs into this port. It is avail- power-regulation circuitry); it has a charge pump for driv- able provided your project is accepted by the person at HP in ing the LCD; and it has quite a lot of flash ROM for charge of distributing the cables (that’s me for the moment) application storage and future upgrades. It also has its and that you agree not to do anything that could harm HP or own internal 32-kHz and 2-MHz oscillator. Thus, if your the sales of the calculator. You need to use Atmel’s SAM Boot application doesn’t rely on accurate timing (i.e., less than Assistant—which is referred to “SAM-BA” for short, and 10%), you don’t need to use an external oscillator, which is also called the “AT91-ISP” for AT91 In-System Program- simplifies the system even more. However, you can con- ming—software to perform software upgrades using the cables nect an external crystal to achieve high accuracy if nec- (www.atmel.com/dyn/products/tools_card.asp?tool_id=3883). essary. The AT91SAM7L128 is all about options! When you open the calculator, you have access to the You will notice other things on the PCB—mainly, PCB, which contains less than 40 sur face-mounted resis- unused pads. The most important of them is the 16-pad tors, capacitors, and diodes. You also can access the bat- connector at the bottom of the PCB, which is the JTAG tery connectors and the Atmel AT91SAM7L128 interface. JTAG is an industry-standard system for devel- CPU/SoC (in die form) that’s wire-bonded to the PCB and opment. You can simply connect a standard 2.54-mm protected under a blob of black resin. SMT header to the pad and start developing! In addition, the JTAG connector is placed exactly at the center of the OPEN THE CALCULATOR recessed area of the HP 20b’s plastic case located below To open the calculator, you must first remove the five the battery door. (That area was designed as a place for screws that hold the top case to the bottom case. Three your engraved name.) You can easily remove the of them are easily spotted behind the batter y cover, two recessed area with a cutting tool (e.g., an Exacto knife). at the top and one located between the two batteries. This enables you to have a closed unit with the JT AG The last two screws are located under the “no-slip” pad pin sticking out for development purposes. Basically, at the bottom of the calculator. You can use an Exacto instead of using one of the traditional large shabby-look- knife or your fingernail to lift 5 mm of the material on ing (when not on an engineer ’s desk) development each side and gain access to the screws without having boards, you can perform development on a small device. to remove the no-slip pad. This enables you to close the Once you are done for the day (or need to excuse your- calculator when you are done without leaving a visible self for a little while), you just unplug the JT AG and November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 45 2911016_deBrebisson.qxp 10/6/2009 1:04 PM Page 46

CAPP1 TDI CAPM1 TDO ICE Charge CAPP2 TMS JTAG ARM7TDMI Processor pump CAPM2 TCK Scan VDDINLCD JTAGSEL VDD3V6

System controller LCD VDDLCD Voltage 2-MHz regulator VDDIO2 TST RCOSC FIQ 1.8-V VDDIO1 IRQ0-IRQ1 AIC Voltage GND

PIO regulator VDDOUT PCK0-PCK2 VDDCORE CLIKIN Memory controller VDDIO2 SRAM PMC PLLRC PLL Embedded Address 2 KB (back-up) XIN flash decoder 4 KB (core) XOUT OSC memory

32k Abort Misalignment RCOSC status detection VDDCORE Flash VDDIO1 BOD memory ERASE 64/128 KB VDDIO1 POR Supply Peripheral NRST controller bridge ROM NRSTB Peripheral data (12 KB) PGMRDY controller PGMNVALID 11 channels Fast flash PGMNOE FWUP PGMCK programming PGMMO-PGMM3 VDDIO1 interface PGMD0-PGMD15 PGMNCMD PGMEN0-PGMEN2 APB SAM-BA RTC

PIT

WDT PWM0 PWMC PWM1 DRXD PDC PWM2 DTXD DBGU PWM3 PIO PDC TCLK0 Timer counter TCLK1 PIOA (26 I/Os) TCLK2 TC0 TIOA0 TIOB0 TIOA1 PIOB (24 I/Os) TC1 TIOB1 TIOA2 TC2 PIO TIOB2 PIOC (30 I/Os) PDC TWI TWD TWCK SEG00-SEG39 PDC COM0-COM9 PDC NPCS0 LCD Controller NPCS1 NPCS2 SPI NPCS3 RXD0 PDC MISO TXD0 MOSI SCK0 USART0 PDC SPCK RTS0 PDC ADTRG CTS0 PDC

PIO AD0 RXD1 PDC AD1 TXD1 ADC AD2 SCK1 AD3 RTS1 CTS1 USART1 ADVREF DCD1 DSR1 DTR1 RI1 PDC

Figure 1—On the outside, the HP20b looks like a normal calculator . But when you look inside, you see a very open platform. The ARM7 under the Bakelite is yours to reprogram as you see fit.

play/test your progress. clock, so it is dependent on the slow response. The system tracks the There are four other unused pads. clock, which is inaccurate if you received data and calculates its Let’s review. don’t use a crystal.) Thus, if you speed based on it. Source code for One pad is a spot for an optional want to send serial data, you must the speed tune-up algorithm is avail- crystal. (You need to connect a 32-kHz set the serial speed parameters for able from Atmel.) crystal if you are trying to develop each calculator to a value that works Another pad is centered at the bot- an application that needs a real-time with its specific master clock speed. tom where you can place an optional clock or serial communications that The other alternative is to create a RS-232 transceiver. This enables you have to be “spot on” with no communication protocol that auto- to have the aforementioned six-pin allowance for speed drift.) Because matically detects and tunes the connector use a real RS-232 signal the HP 20b does not have the cr ystal speed parameters. (This is what instead of a 0- to 3-V signal. The mounted by default, the serial com- Atmel did in the SAM-BA boot. The schematics for the HP 20b provided in munication speed setting is not PC program sends known data con- the system development kit give all accurate. (It is based on the master tinuously until it receives a the details, including the RS-232 level November 2009 – Issue 232 November

46 CIRCUIT CELLAR® • www.circuitcellar.com 2911016_deBrebisson.qxp 10/6/2009 1:04 PM Page 47

shifter’s part number (ATM3202AR). In order to program your calculator, you Note that you may also want to “break” two jumpers—JP6 and probably will want to use a JTAG inter- JP5—to disconnect the RX and TX face. Although this is not 100% neces- pins of the serial connector from the main CPU. (If you don’t, sary, it allows you to connect the CPU remember to set the appropriate directly to the development environ- GPIO pins to pure inputs with no ment, which is a great plus because you pull-up.) If you plan to use this chip, you’ll need to turn it on and can have a one-step solution for down- off using port C’s I/O 27. This is loading your program in the calculator used to conserve power, of course. and step-by-step debugging. J7 is located on the left of the “ CPU. It is an eight-pin pad that pro- vides access to the battery voltage/power, ground, and the AT91SAM7L128’s four ADCs. They can be used to connect all sorts of ana- ATTENTION log equipment to the system. They can range from temperature, light, or PRINT MAGAZINE READERS even force of acceleration sensors. (You could turn your calculator into BONUS CONTENT NOW AVAILABLE a two-direction accelerometer for your car! Then you would be able to The following Circuit Cellar bonus content is now available for you to” use it to map your car’s power, 0- to read online or in a downloadable PDF. Just visit Circuit Cellar ’s home 60-MPH time, and more.) page and click on the link to All Bonus Content. The last connector (10 pins) pro- vides battery voltage, ground, and Issue #228: NimbleSig III eight general-purpose I/Os, which A New and Improved DDS RF Generator are also multiplexed with the four Thomas Alldread pulse-width modulation generator channels of the AT91SAM7L128 and Sound Synthesis Made Simple (Full article plus video example) the SPI. This enables control of up A Multi-MIPS Music Box to three peripherals. An IRQ signal Peter McCollum is also available, as well as three Issue #229: USB I/O Expansion CPU wake-up pins that can restart the CPU from Off or Backup mode. Brian Millier For more in-depth information Issue #230: Verification and Simulation of FPGA Designs about these connectors and how to Sharad Sinha use the CPU peripheral, refer to the HP schematics that are included with the system development kit and Issue #231: Buddy Memory Manager the AT91SAM7L128 documentation. Sitti Amarittapark Arduino-Based Temperature Display SYSTEM DEVELOPMENT Mahesh Venkitachalam Now that you’re familiar with the platform, the question is: How do you do something with it? Are you interested in writing for Circuit Cellar? Consider a submission to Circuit Cellar ’s bonus The first thing to do is download section in the Digital Plus venue. As you see from this statement of availability, the bonus sec- tion of Digital Plus is available to all Circuit Cellar readers. Authors are choosing to be published the system development kit. (Refer in our bonus section for a variety of reasons. These reasons include but are not limited to: to the link in the Resources section • Articles of various lengths can be published in the digital venue at the end of this article, or follow • Follow-up articles are published in the bonus section without concern for the impact the software and drivers link from on the current issue’s theme the HP 20b page on HP’s website.) • Articles may include audio or video enhancements The kit includes the HP 20b binary • Speed to publication. Space restrictions in the print magazine can delay publication. (so you can reprogram your calcula- There are fewer restrictions on the digital side. tor with the original firmware if Whether you want to submit an article for print publication or for publication in the bonus section needed), the calculator’s schematics of Digital Plus, please write to [email protected] to present your ideas. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 47 2911016_deBrebisson.qxp 10/6/2009 1:04 PM Page 48

(which are critical if you plan to do and 10,000. The number keys en able off—which is pretty much all the any hardware modification), a readme you to enter a number. Input is used time because most of the time is file with important information, the to find out if the number to guess is spent when the LCD is on but a key source code for a sample application, larger, smaller, or if you won. The isn’t pressed—this memory is lost. and the “simulation” code that you Backspace key is used to erase the These 4 KB are perfect for storing the can use to develop on the PC and the last digit entered. The On key is stack and temporary variables. The LCD artwork. The artwork is useful used to cancel an entry or a game. other 2 KB of RAM (or back-up if you plan to draw directly on the The framework provided by HP RAM) stay powered even when the screen because it will tell you which includes all the drivers and initial- CPU is off, and this is where you bit of the ARM LCD controller mem- ization, as well as the power man- need to store your application state. ory maps to which LCD pixel. agement. Within this framework, I don’t know how to use the IAR Second, in order to program your your main application function is the compiler to indicate that a specific calculator, you probably will want to KeyPress function called each time variable must be in the back-up use a JTAG interface. Although this you press a key. Key codes are given RAM section, so everything is han- is not 100% necessary, it allows you as a two-digit integer (yx), where y is dled with a TApplication structure to connect the CPU directly to the the row of the key an d x is the col- (application.h) that contains the development environment, which is umn. For example, the open paren- application state that needs to be a great plus because you can have a thesis key keycode is 32. kept active. An Application vari- one-step solution for downloading The second function that you need able is then created at address your program in the calculator and to provide is the init function, 0x300000 (the beginning of the back- step-by-step debugging. If you don’t which is called when the memory is up RAM) and is used th roughout the have a JTAG interface, you need to erased or reset. In this framework, program. Note: Do not exceed 2 KB! compile a binary and send it to the your application is implemented as a HP also provides screen-drawing calculator using the serial port. You kind of state machine that updates functions (graphics.h) as part of the can purchase a JTAG interface—from itself each time a key is pressed. SDK source code. The functions Atmel or other retailers—that is This leaves us with the problem of enable you to display text, numbers, priced in the $100 to $200 range where and how to store the state. and graphics on the screen. They also (look for SAM-ICE). The Atmel chip has 6 KB of RAM, give you control of the 11 indicators You will also need a development which is a strange number. But there so you don’t have to handle each environment. HP is using the IAR is a reason for this, and it is linked pixel “by hand.” Systems embedded workbench (you with the power-saving features of the can download a test version at AT91SAM7L128. APPLICATION MODIFICATION www.iar.com), but it should be possi- The CPU has four power modes. Now that you’re familiar with the ble to also use other environments or (Well, this is a simplification. But as application architecture, you can even the gnu toolkit. You can look, far as I’m concerned for the moment, start digging in. I suggest that you for example, at the HP20b repurpos- four power modes of interest.) The first look at the PC version of the ing project group’s wiki at first one is “running” when the CPU application in the debugger. Place a http://hpwiki.fatcity.com/doku.php. is actively calculating. This is the breakpoint at the beginning of the It uses uses the GNU toolchain. mode to use when your application KeyPress function in the applica- Finally, there’s the Visual C++ is “running.” The second mode is tion.cpp file. Then you can perform option. You can use Visual C++ if Idle. In this mode, the CPU is step-by-step debugging to learn how you want to develop your application paused. This is the mode used when the sample application works. on a PC. Although this is not a a key press has been executed, but Moving on, open the IAR project, necessity, doing most of your appli- the key has not been released yet. compile it (F7), and program it on the cation development and debugging The CPU can’t turn off because it calculator (Ctrl+D followed by F5 to on the PC can greatly simplify and needs to poll the keyboard regularly “run”). Next come modifications to speed up the process. to detect a subsequent key press or the example application. For exam- Let’s assume that you will use release. In the third mode, the CPU ple, transform it in an integer-only or HP’s advised setup: JTAG, IAR, and is turned off, but the LCD is still floating-point four-operation calcula- Visual C++. Files called HP20b_c.exe running. This is the mode used as tor. Or just start your own project. and at91sam7l128_flash.bin are soon as all keys are released but the included in the SDK package. This is LCD is on. In the last mode, every- DEVELOPMENT TIPS the application example (PC and tar- thing is off except the back-up mem- Before I finish this article, I want get versions) created by HP in order ory. This is the mode used when you to describe a few tricks for develop- to provide a good starting point for turn off the calculator. ing on the calculator itself. I trust custom application development. Out of the 6 KB of RAM, 4 KB are you’ll find them useful. This is a simple “guess the number” in the CPU and 2 KB are the back-up IAR has some issues. For example, application with a number between 0 memory. So, as soon as the CPU is it doesn’t always properly erase the November 2009 – Issue 232 November

48 CIRCUIT CELLAR® • www.circuitcellar.com 2911016_deBrebisson.qxp 10/8/2009 12:15 PM Page 49

flash ROM before trying to repro- Cyrille de Brébisson ([email protected]) is a French engineer living in Boise, Idaho, gram the flash memory, so it is usu- where he works for Hewlett-Packard’s calculator division. He earned a degree in ally better to erase the flash manual- computer science, electronics, and control from one of the French Grande ly with the cable. (Press and hold Écoles. Cyrille is particularly interested in optimization. Erase, press Reset, press On, and release the Erase key.) Sometimes, the JTAG link/connec- tion “breaks.” You need to unplug the R EFERENCE SAM_ICE and then plug it in again. [1] Atmel Corp., “AT91 ARM Thumb-based Microcontroller,” You can’t debug a CPU when it’s 6257AS–ATARM, 2008, http://atmel.com/dyn/resources/prod_documents/ off. In fact, the debugger closes when 6257s.pdf. CPU contact is lost. This makes it hard to debug in the HP framework because it continuously turns off the R ESOURCE CPU. So, when you are developing, I Hewlett-Packard, HP 20b Business Consultant Financial Calculator , Dri- recommend commenting out the calls vers and Software Download, http://h20000.www2.hp.com/bizsupport/ to TurnCalcOff and PutCalcIdle TechSupport/SoftwareIndex.jsp?lang=en&cc=us&prodNameId=3732535& to avoid entering these modes. I prodTypeId=215348&prodSeriesId=3732534&swLang=8&taskId=135&swE nvOID=54.

Author’s note: If you have questions or need more information, you can contact S OURCES me directly or interact with other knowl- AT91SAM7L128 SoC edgeable HP people in any of the following Atmel Corp. | www.atmel.com public forums: www.hpmuseum.org/cgi- sys/cgiwrap/hpmuseum/forum.cgi, HP 20b Business Consultant Financial Calculator http://hpwiki.fatcity.com/doku.php, or Hewlett-Packard | www.hp.com comp.sys.hp48. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 49 2911013 martin.qxp 10/6/2009 1:50 PM Page 50

LESSONS FROM THE TRENCHES by George Martin Passing Parameters

How do you partition a design problem into manageable modules? With this article, you’ll learn why it’s smart to pass parameters in the first place, and then find out how to pass parameters and receive results with the C language.

would like to talk about passing param- and B are passed to the Avg() routine. That eters and receiving results using the C lan- routine performs an operation on them and Iguage. I plan to cover why you would want to then returns the result of the operation. That pass parameters in the first place and how the result is then saved in the variable Result. The language performs this operation. This is a variables A, B, and Result are defined in the small portion of a larger topic: How do you par- routine Funct1() and are only known to the tition a design problem into manageable mod- scope of the routine Funct1(). ules that can be designed, coded, tested, and For a discussion of scope in the C language, released into the complete system? That topic refer to Tony Zhang’s “Sams Teach Yourself C is at least a master ’s thesis, and probably more in 24 Hours,” which I list in the Resources sec- in the doctoral thesis arena. Let’s start with the tion of this article. The variables total, x, and basics of passing parameters and then take a y are only known to the Avg() routine. This look at design partitioning. design approach makes sense, considering many routines can use the Avg() routine and its PASSING BASICS mechanism remains hidden. This hiding is a While searching the Internet for concisely great feature in several respects. On large com- worded material as background, I came up with plicated projects, you can be working on several discussions on this topic. (An example is Funct1() and I can be working on Avg(). I can S. Joon’s website noted in the Resources section give you my latest version of the routine. Y ou at the end of this ar ticle.) Let’s start with the can use it without a complete understanding of simple rule that C passes parameters by value. the implementation. You don’t have to under- The compiler makes a copy of the value to be stand my work, just use it. On simpler projects, passed and places it on the stack before the rou- this hiding can be used by one designer to tine is called. This is cer tainly straightforward divide the work. The overall problem is divided enough. into smaller operations, and each operation is In Listing 1, I defined two variables: INT16 A designed, coded, and tested. and B. Both variables are passed to the routine INT16 Avg(INT16 x, INT16 y). This routine VARIABLES GLOBAL calculates the average of the parameters passed Let’s stop here for a bit and talk about mak- and returns the average. ing all the variables global. Making them global There are several points to cover in this sim- would expose all the variables to all the routines ple example. Copies of the values of variables A and parameter passing would go away. This November 2009 – Issue 232 November

50 CIRCUIT CELLAR® • www.circuitcellar.com 2911013 martin.qxp 10/6/2009 1:50 PM Page 51

Listing 1—A simple example of parameter passing by value to use. The notation &Avg is the address of variable Avg. The variable Avg is INT16 Avg(INT16 x, INT16 y) { stored in a memory location &Avg. We INT16 total; are giving the address of that location to total = (x+y)/2; // calculate the average the Operation() routine. Now the return(total); Operation() routine gets an address, } // end of INT16 Avg(INT16 x, INT16 y) but an address to what? Well, that’s where the INT16 *Total comes in. void Funct1(void) { That informs the Operation() routine INT16 A,B,Result; that the parameter is a pointer to an //…do some stuff… INT16-type variable. Said another way, Result = Avg(A,B); // get the average of A & B it’s the address of an INT16-type vari- //… do some more stuff able. While c = toupper(c); works } // end of void Funct1(void) with one variable, when you need to change two or more variables the pass- ing by reference is the method to use . seems like a shortcut (and simpler), changed variable. Consider this simple Life is good. But what if we need to but it’s just a good way to lose control code fragment: pass 20 variables to a routine and of your project. Consider Listing 2 receive 10 results? Good point. We where all variables are global. It’s a lot c = toupper(c); would not want to do all that using less code, which can be a plus. But if the stack mechanism. It would be too you want to call Avg() from several In this example, a routine from one of much of a burden on the code and places in your code, with different val- the C libraries is used to conver t a char- CPU time. Well, let’s just make them ues you would have to expose the acter that might be uppercase or lower- all global. Not so fast. All the prob- variables A and B (by declaring them case to a character that is uppercase. So, lems with global variables are still rel- as extern and transfer those values we pass the variable by value and the evant. Take a look at Listing 4. Can into A and B before the call. I hope return value gets stored in the address of you follow the code? Just start at the you can see how cumbersome this the variable just passed. Caution! The C top. The #define defines the size of would be for anything but a trivial routines like toupper() are actually some character array (10 characters) program. Also, realize how fast you passed an int and also return an int. So that’s used in the structure. Remem- would lose control of your variables. be careful to understand C character rep- ber to leave space for the trailing null. Based on the design, you might some- resentation before you start using them. Next, we define a structure naming times have a compelling reason for What if we want to pass a variable that definition as PARAMETER_BLOCK. making a variable global in scope. Per- and have the routine modify the original Remember, it is good practice to use haps a timer variable showing operat- instance of that variable? In Listing 3, uppercase for constants, and the ing hours is a candidate to be global. If we pass two variables by value. W e PARAMETER_BLOCK definition will not this timer were incremented by a also pass the third by value, but in this change as we run the code. timer interrupt routine and all the case that value is the variable’s address. We then save room for one such other uses were to read that variable Knowing the address, the called routine PARAMETER_BLOCK, and name it for information purposes, I might con- can modify the contents of that third MyData. MyData is where the struc- sider making that timer a global vari- variable. With one variable, we could ture is located. MyData.ValueA refer- able so that any routine may use its use the return parameter of the function ences the ValueA variable in the value. to change the variable. If you have two structure. MyData.Definition- Let’s say you want to pass a param- variables to change, then passing the String[2] references the third (arrays eter, operate on it, and retur n the addresses of each would be the method start at 0) element in the character ar ray. Next, we tell the compiler that there is a function somewhere in our Listing 2—Making all variables global code named SomeFunction(), and INT16 total; that the function is passed a pointer to INT16 A,B,Result; the start of a PARAMETER_BLOCK void Avg(void) { structure. In SomeOtherFunction(), total = (A + B)/2; we are working with our data and } have it all loaded in the str ucture void Funct1(void) { MyData before we call the routine that //…do some stuff… operates on the data. Avg(); And finally, TheBestFunctionYet() ;;… do some more stuff } does the same without a lot of overhead. In SomeOtherFunction() I can put November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 51 2911013 martin.qxp 10/6/2009 1:50 PM Page 52

in breakpoints to make sure I’ve got Listing 3—Passing by reference the correct values for the address of the structure. Once I’m sure the code void Operation(INT16 x, INT16 y, INT16 *Total) { is correct, I’ll change to the faster ver- *Total = *Total + x + y; // Keep a running total sion. I hope you find Listing 4 to be } // end of void Operation(INT16 x, INT16 y, INT16 *Total) { straightforward. It might make your head hurt, but when you use it suc- cessfully for the first time, I bet you’ll void Funct1(void) { INT16 A, B, Avg; // declare these variables here have a smile from ear to ear . Let’s review. We can make variables //…do some stuff… global. Fast, but you lose control. W e Operation(A, B, &Avg); //pass 2 variables(A&B) and address of can pass variables by value. This Avg //… do some more stuff makes a copy and then calls the rou- tine. Good, but it slows down when } // end of void Funct1(void) { we have lots of data to pass. W e can also pass by reference. That is a good choice if you want the called routine variables for the input A/D reading data versus how long will it take to to change the variables. And finally, and its timestamp. The routine process that data? I need to r un the we can create a structure to hold the InitWaveIn() does all the initializa- A/D converter as fast as possible, and data and pass the address of that str uc- tion required for my variables, but not then I’ll slow it down by using this ture. Think about passing parameters, the hardware for the A/D conver ter. counter. In the final version, I’ll use and the more you work with the dif- The routine InitA2DHdw() initializes the CPU internal registers to run the ferent methods, the better you’ll all the A/D converter hardware set-up. A/D converter at the rate suitable for understand the benefits of each. The variable A2DCounter is used to the design. But until then, I can easily Now let’s take the next step toward slow down the rate of new readings. speed up or slow down the amount of the deep end of software design. How As I explained, this is ver y early data feed to my processing routines. do you make a module? code. I’m not sure of the timing of all Lines 75 and 76 define the A/D the components. How fast do I need converter interrupt routine. In that MAKE A MODULE Another word for a module is “file.” An actual file from a project I’m working Listing 4—Passing a pointer to a structure on is available on the Circuit Cellar FTP #define MAX_DEF_CHARS 10 site. The module (file) A2D.C contains all the A2D routines for my project . struct PARAMETER_BLOCK { // define a structure Let me explain a bit more about the INT16 ValueA; problem I’m trying to solve. The input INT16 ValueB; INT16 ValueC; to the microprocessor is a full-wave rec- INT16 ValueD; tified signal. I need to find the signal’ s INT8 *PointerToValueE; peaks and valleys and add a timestamp INT8 DefinitionString[MAX_DEF_CHARS]; for each. This project is in an early }; stage, and I can almost guarantee that struct PARAMETER_BLOCK MyData; // declare an instance of that struct the code will change as we move on. Look at the module, the routines it void SomeFunction(struct PARAMETER_BLOCK *PtrToStruct); contains, and the variables and how void SomeOtherFunction(void) { they’re passed. Look how I divided the struct PARAMETER_BLOCK *Ptr2MyData; code—not to copy this code, but to understand my trade-offs and then use // Do something them as a basis for your design. // Fill the MyData structure with appropriate data Ptr2MyData = &MyData; // Point to my data The include statements in lines SomeFunction(Ptr2MyData); // Call a routine 19, 21, and 22 infor m the compiler // Work with the results. about the CPU, general constants, and } A/D constants. The module A2D.h void TheBestFunctionYet(void) { will be used to give other modules needed information about this module’s // Do something contents. Lines 28 and 29 define a // Fill the MyData structure with appropriate data structure that will be used to hold SomeFunction(&MyData); // An even faster call // Work with the results. A/D input data and timestamps. Vari- } ables inpt and tStamp are temporary November 2009 – Issue 232 November

52 CIRCUIT CELLAR® • www.circuitcellar.com 2911013 martin.qxp 10/6/2009 1:50 PM Page 53

routine, Lines 78 and 94 are used to and WaitA2DPeak()—that wait for a toggle an unused output bit on the valley or peak, respectively. CPU. I can then hook up a scope and So here are all the A2D routines I measure the code’s timing. Early in need to do the job. (I hope.) Actually , the A/D interrupt, I read the ADC and I’m sure I’ll need more, and the ones I the CPU clock. Then I star t another defined here will change. Step back conversion. All this code has no condi- and take a look at the routines. What tional execution so it takes the same other variables might be needed? Well, number of CPU clocks to save that data the timestamp variable needs data each time through the code. Line 84 is from the CPU timer, and the A2D of used to slow down the data rate. In course needs to manipulate the A2D this code, I’m using every other A/D hardware in the CPU. But other than reading. When I want to save the data that, this module stands alone. I know Lines 86–92, I save the ADC and time- I’ll need to report the actual peaks and stamp in an array. I do this using an valleys I’ve detected along with their index into that array. Then I incre- timestamps. But perhaps I could put ment the input index to that ar ray. the code that uses these values in this When the index is past the end of the routine to also cut down on parameter array, I reset that index to the star t of passing and minimizing the exposure the array. This manages the rolling of those variables. over of the indexes and creates a circu- lar (never ending) buffer to the data. SPEED OF EXECUTION New! Lines 98–104 define the variables I As I write this and explain the code, think I’ll need to detect the peaks and I realize that all the variables for OSD-232+ valleys. Think about this: you will buffering the A/D data and time- RS-232/TTL controlled on-screen composite video character and graphic only know the peak or valley conclu- stamps are global to this routine. I did overlay in a small 28 pin dip package. sively after you’ve passed it. In the that for speed of execution. This code case of a valley, once the input data needs to read the data, buffer it, and starts increasing, you’re then sure then process the new readings. Global you’ve got a valley. So, I declared variables made the most sense in this these variables to help with the application. process of detection. I hope you take a closer look at your Routine FindA2DZero() contains all modules and consider parameter pass- the code to detect a valley and retur ns a ing and the organization of the rou- Yes or No to report the results. The same tines in those modules. Please drop with FindA2DPeak(). There are two me a line if you have any C topics you Intuitive Circuits www.icircuits.com additional routines—WaitA2DZero() would like me to explain. I (248) 588-4400

George Martin ([email protected]) began his career in the aerospace industry in 1969. After five years at a real job, he set out on his own and co-founded a design and manufacturing firm (www.embedded-designer.com). His designs typically include servo-motion control, graphical input and output, data acquisi- tion, and remote control systems. Geor ge is a charter member of the Ciarcia Design Works Team. He is currently working on a mobile communications sys- tem that announces highway info. He is also a nationally ranked revolver shooter.

P ROJECT FILES To download code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2009 /232.

RESOURCES S. Joon, “How Are Parameters Passed,” 2003, www .comp.nus.edu.sg/~esim/ faq/node13.html#SECTION00071000000000000000. T. Zhang, “Sams Teach Yourself C in 24 Hours,” Macmillan Computer Publishing, http://aelinik.free.fr/c/ch14.htm. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 53 2911019_Seguine-new.qxp 10/6/2009 1:59 PM Page 54

by Dennis Seguine EATUREARTICLE F Low-Distortion FSK Generation

This article demonstrates a means to generate FSK modulation with low- distortion and low-transition phase error. You can use a PSoC’s digital and analog block features and zero run-time software to achieve this goal.

requency Shift Keying (FSK) encodes digital data to The PWM divides the summed output of Counter_freq1 be transmitted in an analog fashion by assigning one and Counter_freq0 by 160 to provide a wavefor m at one or frequencyF to a logical 0 and another frequency to a logical 1. the other of the signaling frequencies. The PWM (a counter Transmitting data in this manner is a simple, robust, and with a controllable output pulse width) has a 50% duty cycle standard method for communicating over telephone lines and in order to guarantee a square wave to minimize even har- a variety of other transmission media. A typical example is monic distortion. shown in Figure 1 with one bit at logic 1 followed by two bits The remaining trick comes in picking which frequency is at logic 0 in a repeating sequence. transmitted. The enable inputs of Counter_freq1 and The design is demonstrated at 1,200 and 2,200 Hz, Bell 202 Counter_freq0 are driven by the common data signal. T ypi- standard 1,200-baud modem frequencies. Common applica- cally, this comes from a UART clocked at the baud rate. tions for these operating frequencies include telephone caller Counter_freq1 is enabled when the data input is high. ID and Highway Addressable Receiver Transmitter (HART) Counter_freq0 has its enable input inver ted, so that it runs modems. HART modems are used for transmission over DC when the data input is low and stops when the enable input power lines, often shared with 4- to 20-mA cur rent loop data. is high. The HART standard waveform, while not enforcing a specific With one of the counter enables inver ted, when the output requirement, has a relatively low distor tion level. A simple of one counter is toggling, the other is static. The outputs are square wave will not do. added together with an exclusive-OR gate. When one input is The design is implemented in a Cypress Semiconductor low and static, the output follows the other toggling input. CY8C29866 PSoC, although it will easily fit in several other When one input is high and static, the output is inver ted PSoC part families. The PSoC programmable mixed-signal from the toggling input. Thus, when one of Counter_freq1 or array has programmable digital blocks for generating timing signals, programmable impedance I/O for creating multi-step waveforms, and switched capacitor analog blocks for imple- menting filters. The resulting FSK generator implementation is all hardware; it takes no r un-time code. The device has an efficient 8-bit CPU and lots of digital, analog, and memor y resources left over to implement a measurement system that uses FSK as a means to transmit data.

DIGITAL FSK GENERATION The basic FSK generation structure uses two counters and a pulse-width modulator (PWM), as shown in Figure 2. Counter_freq1 divides the clock source to provide a fixed multiple of the output frequency at the logical 1 frequency , 160 × 2,200 Hz, or 352 kHz. Counter freq0 divides the clock Figure 1—The FSK waveform encodes digital data as a selectable fre- source to provide a fixed multiple of the output frequency at quency. This example has 1,200 baud data, one bit high at 2.2 kHz, the logical 0 frequency, 160 × 1,200 Hz, or 192 kHz. two bits low at 1.2 kHz. November 2009 – Issue 232 November

54 CIRCUIT CELLAR® • www.circuitcellar.com 2911019_Seguine-new.qxp 10/6/2009 1:59 PM Page 55

Counter_freq0 is static, the output follows the tog- System gling input of the other Counter. The result is a clock square wave output generated without software Counter _freq0 intervention. Data in EN FSK OUT

For an initial evaluation, a PWM with 1,200 PWM baud alternating 1s and 0s is used to provide the EN digital data. The input data, the two 160 times Counter multiples of the output frequencies, and the FSK _freq1 EN encoded signal are shown in Figure 3. The HART modem spec allows up to 20 degrees ENABLE phase error in the transition from one bit to the next. Since the output frequency is derived from a Figure 2—The data input enables one of two counters to generate o verclocked 160× clock, the phase error will be between 0 and replicas of the output frequency. The EXOR selects the valid clock as the source 2.25 degrees. This clean phase transition limits the to the PWM which divides down to the desired output frequencies. inter-symbol error and enables easier detection of the FSK data at the receiving end. What remains is tur ning pull-up and pull-down outputs of the PWMDB GPIO. When that square wave into a respectable sine wave, or something both outputs are high, the strong drive of one drives the out-

with low enough harmonics to meet the intent of the spec. put to the positive rail (V DD). When both outputs are low, the strong drive of the other output drives the summing point to

DIGITAL HARMONIC REDUCTION the negative rail (V SS). When the first PWMDB output is low The square wave output of a PWM has har monics (all (pulled down) and the second PWMDB output is high (pulled ODD) that fall off as 1/n. Thus, the third har monic is down up), the combined output is resistively divided at a point at

10 dB, the fifth down 14 dB, the seventh down 17 dB, the VDD/2, resulting in the three-step wavefor m of Figure 4. ninth down 19 dB, and so on. But why does the three-step wavefor m work so well? This The higher harmonics are easily filtered, but it is difficult waveform has a Fourier series: to attenuate the third har monic because it is very close to ⎛ ndπ ⎞ the useful band. There are several approaches: lots of filter sin ⎜ ⎟ α ⎛ nπ⎞ ⎝ 2 ⎠ sections, elliptical filters with strategically placed notches, or ft() = ∑⎜ ⎟ sin ()2πftSIG ⎝ 2 ⎠ ⎛ ndπ ⎞ n−1 ⎜ ⎟ digital waveform modifications to reduce near-band har mon- ⎝ 2 ⎠ ics before they are filtered. Modifying the PWM to be a PWMDB (with a dead band), a where d is the duty cycle of the half wave pulse. Parsing the

three-step waveform can be generated as shown in Figure 4. equation will help understanding: f SIG is the FSK output fre- The dead band is set to be one-third of each half of the wave- quency (either 1,200 or 2,200 Hz). sin(n π/2) yields zero when form, or 67% duty cycle. n is even, guaranteeing that the wavefor m has only odd har- One of the PWMDB’s outputs is inverted and the two monics. sin(nπd/2) is zero when n × d is an even integer , so PWMDB outputs are added together. This is not done logical- for d = 2/3, sin(nπd/2) = 0 when n = 3, 9, 15 … ly, but rather arithmetically using resistors. One way is to The resultant spectrum is shown in Figure 5. “dBC” refers connect a resistor (10 kΩ is sufficient) from each PWMDB to decibels below carrier. A similar result for d = 0.8 results output to a common point. Easier yet is using the resistive in suppression of harmonics 5, 15, 25 … The best result is

Clock to filter

VDD

160x Clock FSK 3 Step out GPIO PWMDB div by 160 VDD

ENABLE EN

Figure 4—The PWMDB has two complementary outputs. When either Figure 3—The outputs of the data-enabled counters of Figure 2 side is active, the output is pulled to the respective rail. During the clearly show the over-clocked nature of the generator. The PWM PWM deadband time, the outputs are resistively added to form a divider output results in a square version of the FSK-encoded data. third level. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 55 2911019_Seguine-new.qxp 10/6/2009 1:59 PM Page 56

(XORed) of two blocks, but the clock to the filter can only come from a single block selected by the analog clock mul- tiplexer. This signal is derived by connecting the composite clock output to a DigBuf, then using this buffer output as the clock source for the analog column. The completed dig- ital block connection with digital signal generation and fil- ters is shown in Figure 6. Design of the band-pass filter is enabled by using either the filter wizard in PSoC Designer or the design spread- sheet in PSoC Designer/Help/Documentation. The input

to the filter is a 5.0-V PP signal, which is large enough to saturate the filter output unless the filter is designed to attenuate the signal. Narrowband PSoC filters have high gain. This is a mathematical limitation based on the range of capacitor values available. While a filter band- width of 50 Hz would be “nice” in order to reduce har- monics, it is not achievable. At 2.2 kHz, a bandwidth of 800 Hz is achievable. This results in attenuation of the fifth harmonic by more than 20 dB (the third har monic is already attenuated by the three-step wavefor m). Of course, the filter characteristic on the 1.2-kHz signal is the same as the 2.2-kHz signal because the filter per formance is deter- mined by the synchronized over-sample clock. The filter output waveform is shown at 2.2 kHz in the time domain in Figure 7 and frequency domain in Figure 8. Figure 5—The spectrum of a square wave, shown in the upper plot, The harmonics are considerably reduced from the levels has components that fall off as 1/n. A 38-dB reduction of the thir d shown in Figure 5. The highest har monic is the fifth at harmonic can be seen with the three-step waveform. 38.5 dB below carrier, or 1.2% distortion. All others are lower except the lines at 87.8 and 90.2 kHz; these are the sampling aliases of the filter with a level 32 dB below car- attained when the lowest har monics are eliminated. rier. The sum of the low-order har monics and the first pair of aliases results in a signal-to-noise ratio of 29 dB or 3.3% FILTERING OUT HARMONICS distortion. The third harmonic content of the wavefor m is less than For further reduction, the band-pass filter is followed by 0.5%—a good start, but not up to the standard of the a 7.1-kHz LPF with a 1.0-MHz sample rate. The wavefor m HART modem. The output of the three-step generator is looks even cleaner because the first filter ’s sampling alias filtered with a switched-capacitor band-pass filter. The is significantly attenuated, but it is hard to evaluate distor- switched-capacitor low-pass filter (LPF) is clocked at four tion less than 1% with an oscilloscope. times the sample rate. With the clock at 160 times the out- The LPF has aliases at 1.0 MHz – 2.2 kHz and 1.0 MHz + put frequency, the waveform is sampled at 40 times per sam- 2.2 kHz. Sampling aliases follow a sin(x)/x patter n. As the ple. The three-step waveform uses the combined outputs ratio of the over-sample increases, the aliases are closer to

160 x Filter clock System 4 MHz clock VDD Counter Data in _freq0 EN GPIO FSK BPF2 LPF2 OUT 1200/ 7100 Hz PWMDB3 VDD 2200 Hz ENABLE divided by 160 Counter _freq1 ENABLE EN FSK 3 Step

Figure 6—The complete block diagram shows the relatively simple digital structure combined with a tuned band-pass filter . The following low- pass filter removes the sampling aliases from the band-pass filter . November 2009 – Issue 232 November

56 CIRCUIT CELLAR® • www.circuitcellar.com 41.qxp 1/7/2009 3:07 PM Page 1 2911019_Seguine-new.qxp 10/6/2009 2:00 PM Page 58

Figure 7—The three-step waveform is cleanly filtered to generate a Figure 8—The band-pass filter spectrum shows that the dominant decent sine wave, but still with significant steps at the sampling rate “harmonic” components are from the sample rate, not the harmonics (40 times per cycle). of the intended fundamental.

the null points of sin(x)/x and their levels drop. The LPF The input data, three-step wavefor m, and the final out- reduced the aliases from the band-pass filter. The spec- put are shown in Figure 10. The steps in the output wave- trum scan from 0 to 100 kHz in Figure 9 shows that the form are from the resolution of the digital scope, not the first filter’s alias components are reduced to a negligible sampling in the FSK generator. level. The highest harmonic is the third at –44 dB. The total CONSTRUCTION OPTIONS distortion is less than 0.8%. The highest alias is at 998 kHz The FSK generator can be limited to a simple modulator at –52 dB. This is a ver y clean, easily generated wave- driven by externally supplied data, or it can be par t of a larg- form. er system built in the PSoC. A digital-only version with

4FSWJDJOH ZPVS DPNQMFUF 1$# QSPUPUZQF OFFET

ƅ Low Cost - High Quality PCB Prototypes ƅ&BTZ POMJOF 0SEFSJOH ƅ'VMM %3$ JODMVEFE ƅ -FBEUJNFT /&8 GSPN  IST ƅ0QUJPOBM /&8 $IFNJDBM 5JO GJOJTI no extra cost 8BUDI “VS” 1$#® Follow the production of your PCB in 3&"-5* . &

email : [email protected] Toll Free USA : 1 877 390 8541 www.pcb-pool.com November 2009 – Issue 232 November

58 CIRCUIT CELLAR® • www.circuitcellar.com 2911019_Seguine-new.qxp 10/6/2009 2:00 PM Page 59

Figure 9—Adding a low-pass filter clocked at a much higher frequency Figure 10—The final filtered output of the FSK generator driven by results in the significant reduction of the band-pass filter ’s sampling alternating 1 and 0 data shows a clean waveform and smooth phase aliases. transitions when the data changes. The granularity of the sine wave is a function of the scope resolution, not the generated signal.

square wave output can be cons tructed with three digital level, with options summarized in Table 1. blocks. A three-step analog output version takes another digital block, replacing the PWM with a PWMDB. If a ver y SOFTWARE clean waveform is needed, the three-step waveform and The entire code to operate the FSK modulator is l isted both filters are used. This takes a total of five digital below in C: blocks and four analog blocks. This fits best into a 28-pin or larger part, a Cypress Semiconductor CY8C27443 or Counter_freq0_Start(); CY8C29866. If a PGA is used for wavefor m input to the Counter_freq1_Start(); filter instead of Port 2.1, the design will fit into the eight- PWMDB8_Start(); pin CY8C27143 or the 20-pin CY8C27243. BPF2_Start(MEDPOWER); If all that is required is th e FSK modulator, with modest LPF2_Start(MEDPOWER); allowed harmonics and no on-chip data generation, the design can fit easily into an eight-pin CY8C24123, which has Starting and stopping the modulator output is done by con- four digital blocks and six analog blocks. The filter can be trolling the PWMDB8 Enable or Kill input. This design has a either the single band-pass, which will also help limit power significant advantage over direct digital synthesis techniques requirements, or the combined band-pass and low-pass. In using a DAC in that zero r un-time code execution is either case, the pin requirements are 1 for digital data input, required. When implemented as part of a complete system, 1 for square wave FSK data (instead of the three step wave- this leaves the processor available to do what processors do form) to feed the filter, and 1 for FSK sine wave output . best, calculate and control. The PSoC internal main oscillator is accurate to ±2.5% over the full range of voltage an d temperature. While this ASSOCIATED PROJECT is good enough for UART communications, the HART The associated project is built in a CY8C29866. Data is standard requires 1% frequency accuracy. This require- simulated by a PWM16. This can be replaced by a UART ment is met using the PSoC’s 32.768-kHz external crystal and clock generator, or the modulator can be fed digital oscillator with phase-locked internal main oscillator. data through a global input. Resource utilization boils down to the required d istortion This signal-generation technique is useful in many appli- cations, not just FSK transmission. The idea is to reduce # Digital # Analog Current % Distortion the harmonic content prior to filtering and then take blocks blocks mA advantage of the PSoC’s switched-capacitor filters. I Square wave 3 0 0.1 46.7 Square wave 3 2 1.3 5.1 Dennis Seguine (BSEE and MSEE, UC Berkeley) is an applica- +1 Filter tions engineer at Cypress Semiconductor. He has broad expe- 3 Step 4 0 0.1 39.5 rience in system and analog circuit design, and he holds eight 3 Step 5 2 1.3 4 U.S. patents. You may contact him at [email protected]. +1 Filter 3 Step 5 4 2.5 0.8 + 2 Filter S OURCE Table 1—Increasing the digital waveform complexity and adding filter CY8C27xxx and CY8C29xxx PSoCs sections yields steadily lower distortion. Cypress Semiconductor Corp. | www.cypress.com November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 59 2911003-cantrell.qxp 10/6/2009 2:01 PM Page 60

SILICON UPDATE by Tom Cantrell Power Pitcher Wireless Power on a Microelectronic Scale

Nikola Tesla’s century-old dream of wireless power delivery is coming true, at least for chips. This month Tom looks at a system from PowerCast that deliv- ers power via radio waves. Combine it with low-power silicon and you can cut the wires, and ditch the wall warts, once and for all.

t’s no secret that wireless gadgets (I call ’em is the most popular, efficient, and well-under- “wadgets”) are all the rage. Cell and cord- stood approach. But now EH is really getting Iless phones, Blackberries, Wi-Fi, Bluetooth, creative with virtually any and every joule, and a zillion flavors of IEEE 802.15.4 (e.g., whatever the source (e.g., vibration, ther mal), ZigBee, 6LowPAN, and proprietary) all ride fair game for the taking. the airwaves. But there’s a problem. Just like real crops, More power to them. Literally. Virtually sometimes the harvest may not come in. For every wadget must spend example, a solar harvester is at least some time con- subject to the whims of the nected to a wire (e.g., weather (i.e., clouds). One wall wart, car charger) to solution is to over-engineer get its power fix. Sure the design (e.g., larger panel there are some applica- and battery) to account, tions that are so simple hopefully, for the worst and intermittent (e.g., case. garage door opener, key- What if there were a way less remote) that they to have the best of both just run on batteries worlds (i.e., the convenience period. But despite of wireless combined with advances in battery tech- the predictability and relia- nology, truly wireless bility of wires)? Power wadgets are the excep- would be supplied on your tion rather than the rule. terms—when and where you Energy harvesting (EH) want it—and not depend on to the rescue. Thanks the vagaries of nature or the largely to the Moore-for- application. less march of silicon, Wireless power delivery many embedded wireless isn’t a new concept. Fully apps are able to skim the 100 years ago, Nikola Tesla Photo 1—A century ago, Nikola Tesla had energy they need from their science fiction-like visions of wireless power used his parlor trick of illu- ambient environment. delivery that PowerCast delivers as science minating a light bulb in his Solar (more generally, fact today. (Source: The Tesla Memorial hand as the basis for an photovoltaic) conversion Society of New York, www.teslasociety.com) elaborate vision of wireless November 2009 – Issue 232 November

60 CIRCUIT CELLAR® • www.circuitcellar.com 2911003-cantrell.qxp 10/6/2009 2:01 PM Page 61

power transmission on a grand scale Antenna Type Gain Operation (see Photo 1). Dipole 1.5 Omnidirectional Coming down to earth, consider Sleeve dipole 1.4 Omnidirectional your electric toothbrush. Obviously, Short loaded dipole 1.2 Omnidirectional mixing wired contacts and water Flexible dipole 1.5 Omnidirectional isn’t going to cut it. Instead, we find Patch 3.9 Directional (from surface) a transformer-like arrangement with Yagi 6 Directional (from edge) the AC-powered primary cradle Table 1—When it comes to RF, the choice of antenna may not be everyt hing, but it’s a big transferring energy to the secondary deal. Directionality is a key factor, acting like a magnifying g lass to focus the available in the toothbrush across a hermeti- energy. cally sealed gap. PowerCast is an outfit that brings Tesla’s vision of a wireless power the distance from the transmitter. wire) is omnidirectional, radiating in utility to life on microelectronic The black magic of RF is found in a circular donut pattern. Other scale. As their company name the antenna gain factors, which antennas—such as Yagi, patch, or implies, they broadcast power using depends on a variety of factors dish—exhibit various degrees and radio waves. So how much power including both the type of antenna patterns of directionality. They offer can you extract from RF? Bell Labs and implementation issues. You more gain than a dipole, presuming radio scientist H.T. Friis came up don’t have to be a rocket scientist to of course that the transmitter and

P1100 P1200 P2100 Application Rechargeable alkaline Rechargeable lithium Capacitor charge and fire Recommended operating input 0 to 20 dBm 0 to 20 dBm –10 to 10 dBm Voltage output 3.3 V Maximum 4.2 V Maximum 2.8 to 5.0 V Configurable Power output <= 100 mW continuous <= 100 mW continuous 262.5 mW Peak

Table 2—The PowerCast harvester lineup consists of three parts tar geting the most likely applications. The P1100 and P1200 feature outp ut voltage limiting for alkaline and lithium battery char ging, respectively. The P2100 is a bit dif ferent, designed to charge a supercap and then fire a configurable voltage output.

with the answer some 60 years ago. imagine there’s a difference between receiver are properly aimed at each Herewith, the Friis Transmission a trace on a PCB and a satellite dish. other. Equation: PowerCast offers a selection encom- Directionality (and a similar phe- passing everything from a simple nomenon, polarization) directly P λ 2 R ⎛ ⎞ dipole to a more sophisticated Yagi affects the application in ter ms of = G G ⎜ ⎟ P TR⎝ 4πR ⎠ T and patch antenna to match the mobility. A fixed (non-mobile) instal- needs of different applications (see lation can take advantage of di rec- On the surface, the equation is quite Table 1). tional antenna for maximum gain easy to understand. It simply states One key antenna factor is direc- and efficiency. But if the receivers

that the power received (P R) is a frac- tionality. A simple dipole (piece of move around, an omnidirectional

tion of the power transmitted (P T) that’s determined by three factors: the wavelength (λ), distance (R), and the effectiveness (i.e., gain) of the The black magic of RF is found in transmitting (GT) and receiving (G R) antennas. the antenna gain factors, which As you can see from the equation, received power increases for a longer depends on a variety of factors wavelength (i.e., lower frequency). including both the type of antenna That explains why, for example, a and implementation issues. You 900-MHz radio works better (i.e., overcomes interference and obsta- don’t have to be a rocket scientist cles) than a 2.4-GHz radio with the to imagine there’s a difference same power output. And there’s the between a trace on a PCB and a familiar inverse square law in the “ denominator showing received satellite dish. power declines with the square of “ November 2009 – Issue 232 November www.circuitcellar.com • CIRCUIT CELLAR® ” 61 2911003-cantrell.qxp 10/6/2009 2:01 PM Page 62

Pin 1 Mark Pin 1 Mark Pin 1 Mark

1 - Ground 8 - Ground 1 - Ground 6 - Ground 1 - Ground 6 - Ground 2 - RF In 7 - DC Out 2 - RF In 5 - DC Out 2 - RF In 5 - DC Out 3 - Ground 6 - Ground POWERCAST 3 - Ground POWERCAST 4 - Ground 3 - Ground POWERCAST 4 - Ground P2100 P1100 P1200 4 - Cap 5 - Vset

Figure 1—Designing-in the PowerCast harvesters is really simple: hang an antenna (50 Ω) on one side and the load on the other .

antenna is the call. but there’s definitely enough power on tap to do mean- Implementation issues include things like cable and ingful things. The point is that PowerCast is an option connector losses and impedance matching. Maximum when a wire isn’t. power transfer occurs when the transmitter and antenna (including intervening connectors and cable) have the FREE AT LAST same impedance. A mismatch will cause a portion of the Looking at the big picture, on e can imagine a variety of energy to be reflected back to the transmitter rather than wireless power application scenarios. As menti oned sent over the air. Besides loss of efficiency, in the worst above, options include powering a device directly if it can case (e.g., if you forgot to attach an antenna), the amount get by on 100 mW, or recharging a battery or supercap for of reflected energy might actually damage the transmit- higher-power devices. The transmitter could be powered ter. Thus, the PowerCast transmitters include a so-called at all times or on a scheduled basis. Sampling a bunch of Standing Wave Ratio (SWR—i.e., a measure of how much sensors could be as simple as turning on their power (i.e., energy is reflected) shutdown that automatically turns off the transmitter(s)) periodically. Alternatively, a battery- the transmitter before damage occurs. Along the same powered sensor, detecting its battery is running low, could lines, there’s a thermal shutdown feature. radio a request to tur n on the transmitter (i.e., via a radio The PowerCast lineup consists of a radi o/power-gener- receiver controlling the transmitter’s power supply). ating station (i.e., transmitter) and three receivers (see Like a cell phone network, multiple transmitters can Table 2). The transmitter operates in the 900-MHz band be used to provide wide area coverage within which any with the exact frequency selectable (by pressing a button number of receivers is free to move about (see Figure 3). on the unit) in 2-MHz increments between 903 and 927 MHz. Multiple transmitters also provide a measure of redun- The frequency-select capability allows the use of m ulti- dancy (i.e., the system can be designed to deliver an ade- ple transmitters at different frequencies to avoid the quate level of power, even if a single transmitter should wave cancellation that otherwise might occur. fail or otherwise be compromised—for example, in the The receivers are tailored for slightly different applica- presence of moving obstacles). tions (see Figure 1). The P1100 and P1200 o ffer fixed out- put voltage limiting that makes them a good choice for SAFE AND (IN)SANE? designs using rechargeable batteries (alkaline and lithi- Maybe you’ve seen the YouTube video purporting to um, respectively). Design-in is as simple as it c an be, just show cell phones popping popcor n or cooking eggs? Or connect the antenna on one side a nd the load on the maybe you’ve seen the ads for RF-ar mored underwear to other. protect your family jewels. For those of you who believe The P2100 is a bit di fferent. It features a selectable out- put voltage between 2.8 and 5.0 V (set with exter nal 10,000 resistors connected to the VSET pin) and is especially tai- lored for capacitor-based “charge and fire” designs (see Measured at 15' (103 s) Photo 2). The P2100 charges the capacitor (attached to 1,000 Measured at 10' the CAP pin) to 1.2 V and then tur ns on the DCOUT (152 s) (stepped up to the selected output voltage) to t he load. When the capacitor voltage falls to 1.05 V, the P2100 100 Measured at 20'

automatically turns off the DC output and begins anoth- Charge time (seconds) (145 s)

er recharge cycle. Per Friis, Figure 2 shows how the 10 recharge time varies depending on distance and the Sleeve dipole (G=1.5) Air dipole (G=4.1) antenna gain. Yagi (G=6.1) 1 RF power output of the transmitter is specified as 3 W , 5 10 15 20 25 30 40 45 50 while a P1100 or P1200 can deliver up to 100 mW at the Distance (feet) receiving end. (With a supercap to draw from, the P2100 can Figure 2—This graph showing the capacitor rechar ge time for a “fire” significantly higher peak power, up to 262.5 mW.) P2100 demonstrates the influence of key factors (i.e., antenna gain Sure it’s lossy and nowhere near the efficiency of a wire, and distance) in the Friis equation. November 2009 – Issue 232 November

62 CIRCUIT CELLAR® • www.circuitcellar.com 2911003-cantrell.qxp 10/6/2009 2:01 PM Page 63

the future of journalism is For instance, I could “information that wants to clearly see the difference in be free,” all I can say is gain and directionality as I you’ll get what you pay tried each antenna by for. observing the brightness of The fact is, a cell the LED as I varied the dis- phone’s transmit power is tance and orientation. And on the order of 1 W, with indeed, as advertised, the the power dynamically Yagi and patch antenna adjusted to compensate for were quite sensitive in this obstacles (e.g., indoor use) Photo 2—PowerCast offers an evaluation board that uses a P2100 regard. But I also deter- harvester to “charge and fire” the 0.22F supercap located on the and distance from the base mined that calling the lower right side of the boar d. station. So, if you’re wor- dipole antenna “omnidirec- ried about your 1-W cell tional” was a bit of an phone, shouldn’t the 3-W PowerCast transmitter raise overstatement as there were clearly observable “dead concern? But remember the inverse square law. The cell zones” (i.e., positions and orientations where power phone is an inch from your brain. I wouldn’t tape a Pow- delivery was somewhat attenuated). That’s not a knock erCast transmitter to my head; but otherwise, I wouldn’t on PowerCast, just RF reality. get too worried. This has implications for mobile applications—namely, Perusing the PowerCast website and documentation, you wouldn’t be able to presume continuous (i.e., unin- there’s little on the subject of safety, so presumably no terruptable) power in a mobile application without care- is good news. The only precaution I could find is as fully considering limits on the orientation. Chances are, follows: “FCC radio frequency safety guidelines require you’d need to incorporate back-up power (e.g., battery or the device to be operated with the external antenna at supercap) or, alternatively, a multi-transmitter array least 20 cm (8 inches) from the user’s body. The owner of arranged to cover all orientations. Of course, the same the device must ensure this condition is met even if the caveat applies in an environment with transient obsta- device is operated by a third party or the device is incor- cles (e.g., people walking around). porated into another product. The owner of the device Another interesting phenomenon I noticed was that must communicate this information to any subsequent power delivery seemed non-monotonic relative to range. purchaser. Use and maintain the device only as specified For a given orientation, you’d expect the LED would in this manual.”[1] brighten/dim directly with changes in distance. But I Enough of the fine print, time to get hands on. Power- noticed as I increased the range the LED would dim and Cast sent me a selection of components to play with, then brighten a bit before becoming yet dimmer. This is including a transmitter, a selection of antennas, and a likely explained by multipath phenomenon. Since this plug-in LED module (see Photo 3). The antenna modules transmitter was equipped with an omnidirectional anten- each have a built-in P1100 harvester (two P1100s on the na, at a given location reflections can partially reinforce patch antenna) and a header that the LED board plugs into. It’s a simple setup, but nevertheless able to deliver useful insight into real-world application issues.

Figure 3—Like a cell phone network, multiple transmitters can help Photo 3—PowerCast gear shown here includes the transmitter, a ensure full coverage, a must in situations where receivers may selection of antenna modules with built-in harvesters, and a plug-in move around or be blocked by transient obstacles, such as people LED board. wandering around. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 63 2911003-cantrell.qxp 10/6/2009 2:01 PM Page 64

completely, a welcome safety feature common sense to try cooking dinner for the absent minded. with 3 W. Sounds like a good way to lose some weight. POWER TO THE PEOPLE Give PowerCast credit for thinking Just for kicks, I fired up my cell outside the box, and the wire. Photo 4—Needless to say, the PowerCast phone, and sure enough, in close Beyond the technology itself, they transmitter can overwhelm wireless radios on proximity it was able to light up the were smart enough to recognize the the same frequency. Recognizing the poten- PowerCast receiver LED too. Will we convergence of trends (i.e., low- tial problem, the PowerCast transmitter fre- see a time when you use your cell power silicon, embedded wireless, quency can be adjusted (via a push button) phone to wirelessly recharge your energy harvesting, and the green rev- to allow it and the wireless radio to co-exist. pacemaker? Or how about charging olution) that mean the time is right your laptop while you sip a latte at for wireless power delivery. or attenuate energy delivery. A con- the local Wi-Fi hotspot? If Tesla were still alive, he would tributing factor may be that, accord- I’ll leave it as an exercise for any- no doubt be impressed and proud, ing to the datasheet, the har vester body who has more free time than deservedly, to say he told you so. I conversion efficiency varies between 50% and 70% and in some cases is Tom Cantrell has been working on chip, board, and systems design and marketing higher at a lower level of received for several years. You may reach him by e-mail at [email protected]. energy. What about interference? I dug through my pile of gear and found a 900-MHz embedded wireless setup, R EFERENCE the EmbedRF modules I covered i n [1] PowerCast Corp., “Lifetime Power Evaluation and Development Kit,” “Here Come the Wadgets” earlier Rev. D, 2009, www.powercastco.com/PDF/UserManualWeb.pdf. this year (Circuit Cellar 223). The bad, though not unexpected, news is that the PowerCast transmitter com- S OURCE pletely blitzed the radio transmission P1100, P1200, and P2100 Powerharvester modules (see Photo 4). The good news is th at PowerCast Corp. | www.powercastco.com simply pushing the button on the PowerCast transmitter (i.e., shifting its frequency by 2 MHz) solved the problem. The PowerCast documenta- tion notes that many embedded wire- less gadgets (but apparently not the EmbedRF modules) have automatic frequency hopping built-in that might prevent problems. That got me thinking it would be nice if the Pow- erCast transmitter had a computer interface of some kind (e.g., U ART, SPI, USB) that, with the addition of external intelligence, would allow changing frequency, monitoring the alarm conditions (SWR, thermal), and so on. According to the Power- Cast website, they’re open to OEM and customization proposals, so I imagine something could be worked out if a deal made s ense. Speaking of alarm conditions, I noticed the PowerCast transmitter automatically turned off when I touched the antenna (see Photo 5), presumably causing an impedance Photo 5—There’s more to antenna gain than just the type of antenna. A faulty implementa- mismatch and enough reflected ener- tion (e.g., impedance mismatch) can cause a loss of ef ficiency or even damage the trans- gy to trigger the SWR shutdown fea- mitter. Here the red LED on the transmitter indicates it has shut down, having detected ture. Ditto for removing the antenna something is amiss. November 2009 – Issue 232 November

64 CIRCUIT CELLAR® • www.circuitcellar.com 65.qxp 9/24/2009 1:07 PM Page 1

UNIQUE PRODUCTS & SUPPORT www.saelig.com

Color LCD Scopes 2-ch 1GSa/s Scopes Scope + Analyzer Amazing 7 in 1 Scope! $180 CircuitGear CGR-101™ is a unique Best NEW! NEW! RIGOL RIGOL new, low-cost PC-based instrument Seller

which provides the features of seven CGR-101 DS1000E DS1052D devices in one USB-powered compact box: 2-ch + trigger standalone USB 2-ch 1GSa/s (25GSa/s equiv.) 25MHz 2-ch /16 logic scope 2-ch 10-bit 20MS/sec 2MHz oscilloscope, bench scope. $315 / $499 PDS5022S / PDS6062T 50/100 MHz scope. $595 / $795 and logic analyzer. $1195 2-ch spectrum-analyzer, 3MHz 8-bit Handheld Scopes Pen Scopes XP Emb Touchpanel arbitrary-waveform/standard-function “I really like this scope adapter generator with 8 digital I/O lines. It also - it’s meant for teaching electronic functions as a Network Analyzer, a experiments but it’s ideal for engineers too.” Noise Generator and a PWM Output

Touch-input 10.2” LCD 12V-powered CUPC-80 source. What’s more – its’ open-source PS2104/PS2105 20MHz / 60MHz rugged handheld 10/25MHz USB powered scope-in-a- Windows PC. LX800/512MB/4GB/ software runs with Windows, Linux and Alan Lowne www.saelig.com

USB 2-ch scope. $593 / $699 HDS1022MN / HDS2062M probe! Up to 100MS/s. $234 / $369 Ethernet/3xUSB/SD. Mac OS’s! Only $180! Saelig CEO Low-Cost Scopes Scope/Logger Mixed-Signal Scopes microCAM Multichannel DAQ FREE COFFEE Call 1-888-772-3544 to get a free Starbucks Card with your >$50 order! CS328 Mephisto PS2203/4/5 While supplies last 2-ch 40/100/200MS/s 8-bit scope 2-ch DSO 16-bit DSO, FFT, VM, 100MHz Scope, + Spectrum/Logic Compact compressed-serial output 12/16 input 1kS/s 10/12-bit PL1012 / PL1216 - not available with Mention offer# SBW range with 5/10/25MHz. $246 + logic analyzer, standalone + 24 I/O. Analyzer and Signal Generator. $1259+ camera module for any host system. uCAM-232 / uCAM-TTL PC-connected voltage logger. any other offers USB Bus Analyzers 16-Ch Logic Analyzer SPI Bus Analyzer EMC Spectrum Analyzer EMC Spectrum Analyzer Worlds’s Fastest

Best Value PS9200 PSA2701T

Protocol exerciser/analyzer for standard SPI Xpress LAD-16128U Packet-Master™ - USB 1.1/2.0 Intuitive full-featured 16-ch 4MB SPI and non-standard 4-wire and 3-wire RF & EMF Spectrum Analyzer Handheld Palm PC-based 2-ch 12GHz sampling scope for USB12 / 480+ 500AG

analyzers and generators. $699 + 200MHz sampling memory. $279 serial protocol interfaces up to 50 Mbps. 1Hz to 7GHz for WiFi, mikes, etc. EMC RF & Spectrum 2.7GHz Spectrum Analyzer. high-speed electrical signals. Waveform Generator I2C Xpress Automotive Testing CANminiBOX RF Generator RF Testing/EMI Tents I2C Xpress APSIN6000 emPC-x133 Wave Xpress Wave USB2.0 speed 16-bit digital pattern Versatile USB 2.0 I2C protocol Kits turn your PC into vehicle- Embedded controller series: 2 x High-res, extremely low-noise, Portable RF test enclosures & PS3423 / KLARI-MOD or arbitrary waveform generator. exerciser and analyzer. electrics diagnostic tool. CANbus, Ehternet, USB2.0, CF. portable 6GHz RF generator. shielding tents with external frame. Tents / EMI RF Testing Wireless Data Loggers Multiparameter Loggers USB Loggers Electronic DC Load 60/100/120MHz AWG TorqSense

NEW! RIGOL LD300 RTR-50 RWT320 MSR145S Configurable, patented USB-output Log and display temp, hum, volt, Mini-logger with built-in temp/hum/ Standalone USB temp / hum / volt / EL-USB-1/2/3/4 Const. current, resistance, 60/100/120MHz USB 14-bit ARB non-contact SAW digital rotary torque event-time or pulse-counting data pressure/3-axis accel sensors. current loop data logger. $49+ conductance, voltage & power modes with USB RS-232, LAN/GPIB. DG3061A/3101A/3121A transducers with integral electronics. USB to I2C FTDI USB ICs CAN-USB Serial-Ethernet Cable Lorlin Switches Sound Module

owest L Prices NEW! Lorlin FT232RL CAN-USB USBI2CIO SOMO-14D eCOV-110-P “Drop-in” solution connects PC to Popular UART and FIFO chips. Intelligent CAN connection Network serial product easily without Fantastic array of stock and 14-pin module plays back pre- I2C/SMBUS + 32 I/O lines. $89 Upgrade Legacy designs to USB. from PC’s USB port. $299 a PC using this 28” cable. $89 custom switching devices. stored audio files from microSD card Keyboard Simulator Instant Ethernet Ethernet-IO FPGA Systems Wireless Solutions Temp/RH Sensors RTG005 Ether-IO 24 PoKeys55T

USB board adds 55 I/O and 5 x No OS needed. TCP/IP offload, / W5100 WIZ110SR UDP/IP-controlled 24 digital Ready-to-go out-of-the-box FPGA/DSP Analog input, bluetooth wireless Novel ambient sensors & modules EmbedRF / Adeunis UPSICAP / DLP-TH1 UPSICAP 10-bit A/D inputs, 1 x 10-bit analog O/P. ICs improve system performance. I/O board 3 x 8-bit TTL ports. designs for beginners and experts! modules 433/868/915MHz. accurately measure temp/RH. .NET Board Easy OLED Display RF Modules RS232 to 422/485 1/2/4/8/16 x RS232 USB-Serial USBizi CE-USB USB-COM KK Systems uOLED-96-G1 Small (2.2” x 2.2”) lowest cost .NET Compact, economical smart OLED with Simultaneously transmit composite TX/RX AWM6XX 9p-9p or 25p-25p self-pwrd, Add 1-16 COMports via your A complete CP2102 USB-serial Micro Framework dev system. graphics drive from USB or RS232. video and stereo audio signals. isolated RS232-RS422/485 PC’s USB Port easily. converter in a DB9 shell. $26

Above are some of our best-selling, unique, time-saving products - see our website for 100s more: WiFi/910MHz antennas, wireless boards, LCD display kits, Ethernet/IO, USB/RS232/485, USB-OTG, instant Ethernet-serial, CAN/LINbus, USB cables/extenders, line testers, logic analyzers, color sensors, motion controllers, eng. software, wireless boards, SMD adapters, I2C adapters, GPS loggers, automotive testing, security dongles, video motion detectors, crystals/oscillators, custom switches, barcode scanners, DSP filters, PLCs, Remote MP3 players, etc. FREE Starbucks card with your $50 order! Check www.saelig.com often for special offers, bargains, business hints, blog, etc. 2911002-bachiochi.qxp 10/6/2009 2:18 PM Page 66

FROM THE BENCH by Jeff Bachiochi Device Management Monitor Networked Devices Via SNMP

The simple network management protocol (SNMP) enables you to monitor a network’s activity and stock data units in a management information base (MIB). Today, many embedded microcontroller manufacturers pro vide SNMP support in their TCP/stack offerings. You can use this technology to build an MCU-based managed device that monitors multiple networked modules and logs critical data.

ost engineers look through a new how could an application make use of a part’s datasheet before attempting device like this? The key to this problem was toM use it. This might be to simply identify the to have the peripheral identify itself when part’s connections or to fully understand its plugged in. And even though this sometimes working parameters. In general, a datasheet requires a special driver to be installed, provides specific answers that cannot be adding a device is a relatively simple task (for gleaned from just looking at a proverbial, the most part). albeit tiny, black box. You wouldn’t think of Like USB and FireWire, the Internet is just connecting a peripheral to your micro with- another of the many communication medi- out some knowledge of how it will integrate ums available today. The Internet intercon- into the design. With the pinout, you could nects networks throughout the world. It uses connect all of the signals using the proper standardized protocols to allow private/pub- communication bus structure. You might lic, academic, business, and government net- even be able figure out if it is an input or an works to communicate with one another over output device. But without knowledge of a various technologies. The copper, fiber optic, device’s inner-workings, trying to make full or wireless technologies used today offer use of it is futile. something not available from USB or For years, we used serial and parallel ports FireWire—and that is distance. For years, on our PCs without any real knowledge of we’ve been able to pick up a telephone and what was being plugged in. Originally, about connect to anyone else on the planet with all that was available was a printing device telephone service. To do this, you n eed to and driver support was unnecessary. But once “dial” a special number that the telephone manufacturers understood just how useful network uses to route a connection to the these ports could be, peripheral I/O devices appropriate telephone. The Internet uses an started popping out everywhere: document IP address to do the same thing and connect scanners, barcode readers, weight scales, your computer with another on the Internet. mice, modems, and more. One day someone While you may actually use a “domain asked, “Wouldn’t it be nice to have some name,” this is converted into a specific IPv4 kind of universal port that you could plug address. This dotted notation of 4 bytes anything into?” That question lead to USB (x.x.x.x) soon will be eclipsed by a 16-byte and FireWire technologies. USB and FireWire notation IPv6 (x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x). attempted to become everything to everyone. But that’s another story. Without knowing what was being plugged in, You might imagine that Internet traffic November 2009 – Issue 232 November

66 CIRCUIT CELLAR® • www.circuitcellar.com 2911002-bachiochi.qxp 10/6/2009 2:18 PM Page 67

Root

itu-t(0) iso(1) .1 joint-iso-itu-t(2)

(0) (n) (1) (0) (n) Identified-organization(3) .1.3

(0) dod(6) .1.3.6

(0) Internet(1) .1.3.6.1

Private(4) .1.3.6.1.4 (0) Management(2) .1.3.6.1.2

Enterprises(1)

(0) Mib-2(1) .1.3.6.1.2.1 .1.3.6.1.4.1

(0)

Imagine that System(1) Snmp(11) (33764) .1.3.6.1.2.1.11 .1.3.6.1.4.1.33764 Figure 1—You can follow the root (or structure) of the management information base (MIB) down to the SNMP node using the dotted integer path (.1.3.6.1.2.1.11). Note that SNMP(11) is part of the MIB for the simple network management protocol (SNMP) found in RFC3418.

consists of packets of information The structure is made up of data The root node itself is unlabeled, but carrying e-mails, photos, and media objects or object identifiers (OIs) rep- has three children directly under it: files between users—and that would resented by a sequence of integers, one node is administered by the ISO, be true. However, there is other traf- which traverse a global tree identify- with label “iso(1)”; another is fic that doesn’t have anything to do ing a particular node. The tree begins administrated by the International with personal communications: it with a main root connected to a num- Telegraph and Telephone Consulta- carries control and status informa- ber of labeled sub-roots or nodes. Each tive Committee (CCITT), with a tion. This information doesn’t neces- node may, in turn, have sub-roots (or label “ccitt(0)”; and the third is sarily need to be presented in a children) of its own, which are jointly administered by the ISO and viewable fashion; it can be as simple labeled. This process may continue to the CCITT, “joint-iso-ccitt(2).” as a single prearranged value. an arbitrary level of depth. Figure 1 Along the MIB tree’s ISO path, you shows a partial view of the root can find the Department of Defense MANAGEMENT INFO BASE structure. For additional information, (DOD) under the “other-organiza- The Open Systems Interconnection refer to Keith McCloghrie et al’s tion” node. It has authority over a (OSI) is an attempt to standardize “Structure of Management Informa- subtree, which includes the Internet. networking by the International tion Version 2” (SMIv2). In Marshall Rose and Keith Organization for Standardization Most of the OIs are predefined as McCloghrie’s “Structure and Identifi- (ISO) and the International Telecom- labeled pairings of a brief textual cation of Management Information munication Union (IUT). The OSI description and an integer in the for TCP/IP-Based Internets,” the sub- consists of a Management Informa- form of [text(#)]. The integer is a tree of the Internet is defined as hav- tion Base (MIB) that is used to iden- shorthand representation of the node ing four nodes: Directory, Manage- tify all devices in a communications (OI). A dotted sequence of these ment, Private, and Experimental. The network. integers identifies a specific path. Management sub-tree defines objects November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 67 2911002-bachiochi.qxp 10/6/2009 2:18 PM Page 68

used in the management of the Inter- net standard—this path is the way to Data Application the simple network management pro- tocol (SNMP, .1.3.6.1.2.1.11)—while the Private subtree provides nodes to companies requesting a private UDP UDP Transport enterprise number (PEN) from the Header Data Internet assigned numbers authority (IANA) under its enterprises node. For instance, my PEN is 33746. With IP IP Data Internet this assignment, my tree path would Header be “.1.3.6.1.4.1.33746.” This is sig- nificant to me because I can define the sub-tree below this node. More Frame Frame Frame data Link on this shortly. header footer

SNMP Figure 2—The SNMP message (application data) is typically wrapped in a UDP packet (trans- The Hypertext Transfer Protocol port method), which is housed within an IP packet (for use over the Internet). (HTTP) is the application layer pro- tocol you are probably most familiar The agent has local knowledge of the you know where to find this data? with because you use it every day data and is responsible for translat- for interacting with others through ing it to and from SNMP message DATASHEET graphics, audio, video, and plain packets. The key to the location of the data text. The Simple Network Manage- An NMS is an application that is the datasheet—or in this case, the ment Protocol (SNMP) is similar to monitors and controls managed MIB’s OIs. The standards group has HTTP, but it deals directly with net- devices. These systems provide the predefined data objects (OIs) for a work-attached devices and doesn’t bulk of the processing and memory number of standard devices, such as need the fluff required for human resources required for network man- a modem, a cable device, an uninter- readability. The SNMP protocol agement. One or more of them may ruptible power supply (UPS), a printer, includes an application layer (the how), exist on any managed network. and so on. a database schema (the where), and a An SNMP message (see Figure 2) is Let’s take a closer look at the stan- set of data objects (the what). The typically wrapped in a TCP or UDP dard MIB for a UPS. The standard SNMP exposes data objects, which packet, which is wrapped in an IP MIB for a UPS uses OI .1.3.6.2.1.33, describe the device configuration and packet (see Figure 3). There are only “upsMIB” (covered in RFC1628). even status and control values. These seven message types in the present Table 1 includes the first OI in the objects can then be queried (and standard SNMPv2. The Get, Getnext, sub-roots of this MIB. The first even set) by managing applications. and Getbulk messages request data. object in this tree is “[upsIdentMan- An SNMP-managed network con- The Set message writes data from the ufacturer 1]” at sub-root node .1.1.1 sists of at least one managed device, management application. The of the “upsMIB.” Each object is an agent, and a Network Manage- Response message is returned by the described using the Abstract Syntax ment System (NMS). A managed managed device. A Trap message is Notation One (ANS.1). This is a device has its own pool of data relat- used by a managed device to signal an standard notation structure that ed to its function, but it makes this event or condition (there is no ensures data will be presented in a information available to NMS using response). An Inform message is simi- machine-independent way. The an SNMP agent. An agent is a net- lar to a trap, but it results in a Packed Encoding Rules (PER) that work-management software module Response being returned. While SNMP enable this data to be compressed that resides in the managed device. gives you a way to pass data, how do and transmitted is complex and

SNMP Message Type = Sequence, Length = 44

SNMP SNMP SNMP PDU Type = GetRequest, Length = 30 Version Community string Type = Integer Type = Octet string Request ID Error Error index Varbind List Type = Sequence, Length = 19 Length = 1 Length = 7 Type = Integer Type = Integer Type = Integer Value = 0 Value = private Length = 1 Length = 1 Length = 1 Varbind Type = Sequence, Length = 17 Value = 1 Value = 0 Value = 0 Object identifier Value Type = Object identifier Type = Null Length = 13 Length = 0 Value = 1.3.6.1.4.1.2680.1.2.7.3.2.0

30 2C 02 01 00 04 07 70 72 69 76 61 74 65 A0 1E 02 01 01 02 01 00 02 01 00 30 13 30 11 06 0D 2B 06 01 04 01 94 78 01 02 07 03 02 00 05 00

Figure 3—The SNMP data is rolled into the IP packet in Figure 2. November 2009 – Issue 232 November

68 CIRCUIT CELLAR® • www.circuitcellar.com 25.qxp 9/9/2009 5:09 PM Page 1 Pick a Chip Ad 7/29/09 10:03 AM Page 1 Pick a Chip. Any Chip. Find a Solution to your next Embedded Challenge. Do the Research you should, but never had time for.

Embedded Developer’s intuitive research engine helps you speed your chip evaluation time. You don’t have to know the manufacturer, chip family or part number--just select the features you want and let us do the rest.

Part Number AT91SAM7X MCF5208 LPC2923 We help you research your best option. Nowhere else can you compare your best Manufacturer options side-by-side from different Core Variant ARM7TDMI ColdFire V2 ARM968E-S manufacturers. Click on the device you want, Flash 262144 0 262144 and a product page lets you select RAM 65536 16384 16384 Distributor Buy/Quote options, send RFQs, Max. Freq. 55 166 125 download datasheets, and more. Dhrystone MIPS 50 159 156 Plus--Hearst stock check gives you Timer Bits 16 32 32 up-to-date inventory on every device.

Once you have the chip that meets your needs, review and compare the hardware and software development tools that support it from multiple manufacturers, and buy them on-line through our shopping cart.

Shave days off your schedule with Embedded Developer, the only site in the world where you’re only clicks away from finding the chips and tools to get you up and running, quickly. Try EmbeddedDeveloper.com, or EmbeddedDeveloper.cn in Chinese.

The Sites for Engineers with a Job to Do. 2911002-bachiochi.qxp 10/8/2009 12:17 PM Page 70

upsMIB = .1.3.6.2.1.33 Groups Sub-groups Objects Sub Objects .1 upsObjects [upsMIB 1] .1.1 upsIdent [upsObjects 1] .1.1.1 upsIdentManufacturer [upsIdent 1] .1.1.2 upsIdentModel [upsIdent 2] .1.1.3 upsIdentUPSSoftwareVersion [upsIdent 3] .1.1.4 upsIdentAgentSoftwareVersion [upsIdent 4] .1.1.5 upsIdentName [upsIdent 5] .1.1.6 upsIdentAttachedDevices [upsIdent 6] .1.2 upsBattery [upsObjects 2] .1.2.1 upsBatteryStatus [upsBattery 1] .1.2.2 upsSecondsOnBattery [upsBattery 2] .1.2.3 upsEstimatedMinutesRemaining [upsBattery 3] .1.2.4 upsEstimatedChargeRemaining [upsBattery 4] .1.2.5 upsBatteryVoltage [upsBattery 5] .1.2.6 upsBatteryCurrent [upsBattery 6] .1.2.7 upsBatteryTemperature [upsBattery 7] .1.3 upsInput [upsObjects 3] .1.3.1 upsInputLineBads [upsInput 1] .1.3.2 upsInputNumLines [upsInput 2] .1.3.3 upsInputTable [upsInput 3] .1.3.3.1 upsInputLineIndex [upsInputTable 1] .1.3.3.2 upsInputFrequency [upsInputTable 2] .1.3.3.3 upsInputVoltage [upsInputTable 3] .1.3.3.4 upsInputCurrent [upsInputTable 4] .1.3.3.5 upsInputTruePower [upsInputTable 5] … … … …

Table 1—Beginning on the left is the first of three groups below the standar d upsMIB node .1.3.6.2.1.33, “upsObjects.” It has nine sub- groups below it, beginning here with “upsIdent.” Note that “upsIdent” has six objects below it, starting with object “upsIdentM anufacturer.” Each object in the MIB has its own unique path sequence, which is its shorthand dotted identifier . November 2009 – Issue 232 November

70 CIRCUIT CELLAR® • www.circuitcellar.com 2911002-bachiochi.qxp 10/6/2009 2:18 PM Page 71

compact, but it doesn’t lend itself to is responsible for exchanging data NMS uses this MIB again at the human readability. Therefore, each packets with the NMS. Each packet other end of the network. manufacturer prepares an MIB text contains an SNMP message holding file covering the objects supported compressed data. The agent decodes NETWORK MANAGEMENT by their product. The text file an SNMP Get message as a request The management of networks describes each object using ANS.1 for data, grabs the requested data, refers to the activities, methods, pro- notation. Each object consists of five and encodes it into an SNMP cedures, and tools used in the opera- fields describing the textual name, Response packet. Or, if the decoded tion, administration, maintenance, variable type, textual description, message is an SNMP Set message, and provisioning of networked sys- read/write access type, and status. the agents store the data at the tems. Keeping tabs on managed In Listing 1, the read-only object appropriate location and return an devices—such as servers, routers, named upsIdentManufacturer is a SNMP Response message indicating and switches—gives IT personnel a string of up to 32 characters that the status of the request. At the way to monitor a network’s health. contain the name of the UPS manu- managed device, the MIB allows the But today, the SNMP goes beyond facturer. Other information here SNMP agent to know all about the the task of network welfare. identifies this as the first object in data it will be working with. The The SNMP has found its way into the upsIdent group under the upsObjects group of the upsMIB. This object, and all the other objects Listing 1—The read-only object (upsIdentManufacturer) is a string of up to 32 in the RFC1628UPS-MIB.txt file, characters that will contain the name of the UPS manufacturer. aren’t merely for your perusal. The upsIdent OBJECT IDENTIFIER ::= { upsObjects 1 } text file also performs as a template. upsIdentManufacturer OBJECT-TYPE At the managed device end of the SYNTAX DisplayString (SIZE (0..31)) network, the manufacturer uses the MAX-ACCESS read-only MIB.txt file so that the storage loca- STATUS current DESCRIPTION tion of the data variables will be "The name of the UPS manufacturer." known by both the SNMP agent and ::= { upsIdent 1 } the embedded application. The agent 352)(66256 ELECTRONIC The Circuit Cellar college program COMMUNICATIONS puts quality engineering information Op-Amp Design Techniques MATHEMATICS in the hands of your students every IN ELECTRONICS month. Signup now to get Linear IC Technology Circuit Cellar distributed to your class this semester. Introductory Circuit Analysis

To update your professor account or to find out more about our college program, visit www.circuitcellar.com/products/collegeprogram/ November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 71 2911002-bachiochi.qxp 10/8/2009 12:18 PM Page 72

shows the present value (in tenths of a) a cycle) requested from the Tripp Lite UPS. Photo 1b shows a private “Tripplite-MIB.” Remember our ear- lier discussion of a Private Enter- prise Number (PEN)? Tripp Lite’s PEN—“.850”—gives them full con- trol over special objects they want to define in their own Tripplite-MIB.txt file. I highlighted the “tlupsOutlet- State,” which indicates the present state of the Tripp Lite conditioned power outputs. If you look carefully, you can see a number of OIs listed by their dot nodes as opposed to object names. These are objects that are not defined in the Tripplite-MIB, but b) exist in the device as real objects. Tripp Lite chose not to document these and others found using a (dis- covery) operation called “walk” in their Tripplite-MIB. Some of these are proprietary and used by their Power Alert Shutdown Agent appli- cation software.

IT’S YOUR TURN The PEN gives every design engi- neer a way to create a device that can be managed over a network using the SNMP. As long as you follow the rules for declaring objects in your personal MIB—and as long as you support SNMP communication by including SNMP agent support in Photo 1a—MIB browsers can send SNMP messages to a managed device on the network. your product—you will have a pro d- You’ll need to know the network IP address. And it also helps to import the MIB.txt file dis- uct that can be added to the growing tributed with the device. Although you can still access the device, the data will have no con- base of SNMP-managed devices. If text. b—A private MIB.txt file may be used when the device’ s objects don’t conform to one your widget falls within a standard of the standard MIBs. When a private MIB has been produced for a managed device, it should use a private enterprise number allocated by the Internet Assignment Numbers Authority MIB, you won’t even need a PEN. (IANA). This is a free service. However, it’s good to know that there’s a way to define your device if all industries thanks to the common directly with a managed device via it’s nonstandard so that anyone can thread interconnecting our world. SNMP messages, but also have high- use it. And the registration process Not only does a network standardize er functions to help in the discover y for your own private PEN is free. connectivity, but it also removes the of accessible SNMP MIBs (like You’ll find that most of the popu- need for local presence. The industr y walk). The Tripp Lite UPS on my lar embedded micro manufacturers has seen growth in the use of SNMP home network has implemented already provide support for SNMP in monitoring and control of both com- some objects in the standard UPS- their TCP/IP stack offerings. This mercial and residential properties. MIB. These can be accessed using a should also include an MIB Environmental, security, automa- browser like the iReasoning MIB editor/compiler. If you want to write tion, and data-logging applications browser shown in Photo 1a. Here it’s your own applications to make use take advantage of the SNMP. displaying an import of the standard of managed devices, you can find Most network device manufacturers UPS-MIB.txt file in the left panes SNMP support for most languages provide applications that give access to and a subtree search of the related running on almost any OS. their products. You can find free MIB OIs in the right pane. I highlighted SNMP devices keep network traffic browsers that not only communicate one OI—“upsInputFrequency”—that to a minimum. This is especially November 2009 – Issue 232 November

72 CIRCUIT CELLAR® • www.circuitcellar.com 2911002-bachiochi.qxp 10/6/2009 2:18 PM Page 73

useful when multiple devices must be polled in timed periodic fashion. Data- logging applications require the kind RESOURCES D. Bruey, “SNMP: Simple? Network Management Protocol,” RaneNote 161, of continuous access that could be Rane Corp., 2005, www.rane.com/note161.html. vulnerable to network bottlenecks. In the future, I’ll work on a managed D. Harrington et al, “An Architecture for Describing Simple Network device that will have multiple distribu- Management Protocol (SNMP) Management Frameworks,” RFC3411, The tions on a network. This will require Internet Society, 2002, http://tools.ietf.org/html/rfc3411. writing a management application to handle data monitoring and logging, Internet Assignment Numbers Authority (IANA), www.iana.org. and it will include separate alarm K. McCloghrie et al, “Structure of Management Information Version 2 parameters for each device. Let me (SMIv2),” RFC2578, The Internet Society, 1999, http://tools.ietf.org/html/ know if you’re already using SNMP, or rfc2578. if you’re just interested in reading I more about this growing trend. MIB Downloads, ByteSphere Technologies, www.oidview.com/mibs/0/md- 0-1.html. Jeff Bachiochi (pronounced BAH-key-AH- key) has been writing for Circuit Cellar R. Presuhn (ed), “Version 2 of the Protocol Operations for the Simple since 1988. His background includes prod- Network Management Protocol (SNMP),” RFC3416, The Internet Society, uct design and manufacturing. You can 2002, http://tools.ietf.org/html/rfc3416. reach him at jeff.bachiochi@imaginethat- now.com or at www.imaginethatnow.com. R. Presuhn et al, “Management Information Base (MIB) for the Simple Network Management Protocol (SNMP),” RFC3418, The Internet Society, 2002, www.ietf.org/rfc/rfc3418.txt?number=3418. S OURCES M. Rose and K. McCloghrie, “Structure and Identification of Management MIB Browser | iReasoning, Inc. Information for TCP/IP-based Internets,” RFC1155, http://tools.ietf.org/ www.ireasoning.com html/rfc1155. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 73 crossword2.qxp 10/6/2009 4:49 PM Page 78

CROSSWORD

123 4

5 6

78

9

10 11 12

13 14 15

16 17

18

19

20

Across Down 5. + Pole 1. Cot-1 [two words] 8. Instruction to move ahead or back in a program 2. An ALU performs arithmetic and what? 9. Current limiter 3. Spiral 11. GUI widget for item selection 4. The “Board” type at http://bbs.circuitcellar.com/phpbb/ 13. Address for a device on an Ether net network 6. Time from submission to completion 15. Transmit electricity 7. Time from On to Off [two words] 16. Abnormal end 10. Eleven-sided 17. To release gas 12. Doesn’t conduct; insulates 18. An old circuit in use 14. L1 is the first 19. 3,600 Joules [two words] 20. 106 cycles/second The answers are available at www.circuitcellar.com/crossword. November 2009 November – Issue 232

74 CIRCUIT CELLAR® • www.circuitcellar.com ib-232.qxp 10/6/2009 5:12 PM Page 75

DEA THE DIRECTORY OF IBOX 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. E-mail [email protected] with your file and digital submission or send it to IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066. For more information call Shannon Barraclough at (860) 875-2199.

The Vendor Directory at www.circuitcellar.com/vendor/ is your guide to a variety of engineering products and services. November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 75 ib-232.qxp 10/6/2009 5:13 PM Page 76 November 2009 – Issue 232 November

76 CIRCUIT CELLAR® • www.circuitcellar.com ib-232.qxp 10/6/2009 5:13 PM Page 77

Inside great products. Behind great ideas.

phyCORE® System on Modules: tTIPSUFOUJNFUPNBSLFU tSFEVDFEFWFMPQNFOUDPTUTBOEBWPJETVCTUBOUJBMEFTJHOJTTVFTBOESJTLT t8JOEPXT¥&NCFEEFE$&BOE-JOVY#41T QSPDFTTPSEFQFOEFOU tVOJUCFODINBSLQSJDFBU,GPS"3.CBTFE40. t%FTJHO4FSWJDFTBWBJMBCMFUPBTTJTUXJUIEFQMPZNFOUJOUPUBSHFUBQQMJDBUJPOT

ARM11: i.MX35, i.MX31 ARM9: i.MX27, LPC3250, LPC3180 Cortex M3: STM32F103 ARM7: LPC2294 XScale: PXA270 : Z510, Z520, Z530 (Atom®) Blackfin: ADSP-BF537 Coldfire: MCF5485 PowerPC: MPC5554, MPC5567, phyCORE-LPC3250 MPC5200B, MPC565, MPC555

phyCORE® Rapid Development Kits include SOM, Carrier Board, LCD (kit specific), schematics, software, free BSP for applicable kits and a start-up guarantee. The Carrier Board serves as a target reference design, allowing the SOM to easily port to the user’s target hardware. www.phytec.com |800.278.9913| www.phycore.com November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 77 ib-232.qxp 10/6/2009 5:13 PM Page 78

Adapt9S12XDP512 ® Modular Prototyping System 64-BIT * Robotics and Mechatronics FLOATING * Electronic Fuel Injection * Freescale 9S12XDP512 POINT * RTOS-capable A feature of the Crossware 8051 Development Suite Starting at $125! G C Compiler G Assembler G Code Wizards G Debugging Evaluate * Educate * Embed G Simulation G Support Advanced software Program in tools since 1984 Assembler, BASIC, C, and Forth www.crossware.com Tools for Embedded Development Tools CROSSWARE www.TechnologicalArts.com [email protected]

63,  :LUH

            November 2009 – Issue 232 November

78 CIRCUIT CELLAR® • www.circuitcellar.com 79-advertiser's index.qxp 10/9/2009 12:34 PM Page 79

NDEX OF The Index of Advertisers with links to their web sites is IADVERTISERS located at www.circuitcellar.com under the current issue. Page Page Page Page 78 AAG Electronica, LLC 69 Embedded Developer 22 Keil Software 77 Phytec America LLC

49 AP Circuits 20 ExpressPCB 53 Lakeview Research 78 Picofab Inc.

78 All Electronics Corp. 73 ezPCB 77 Lawicel AB 31 Pololu Corp.

77 Apex Embedded Systems 76 FlexiPanel Ltd. 5 LeCroy 77 ProlificUSA

7 Atmel 11 Front Panel Express LLC 11 Lemos International Co. Inc. C3 Rabbit, A Digi International Brand

76 Avocet Systems, Inc. 49 Futurlec 77 MCC (Micro Computer Control) 77 Reach Technology, Inc.

33 CWAV 71 Grid Connect, Inc. 15 MachinePIER 65 Saelig Co.

40 CadSoft Computer, Inc. 42 HobbyLab, LLC 78 Mental Automation, Inc. 76 Scidyne

19 Comfile Technology, Inc. 78 I2CChip 29 Microchip Technology, Inc. 78 Technical Solutions, Inc.

78 Crossware Products, Inc. 30, 57 ICbank Inc. 75 microEngineering Labs, Inc. 24, 25 Technologic Systems

75 Custom Computer Services, Inc. 53 Intuitive Circuits LLC 23 Mouser Electronics 78 Technological Arts

42 DesignNotes 75 Ironwood Electronics C2 NetBurner 77 Tern, Inc.

34 EMAC, Inc. 32, 34 JKmicrosystems, Inc. 21 Noritake Co., Inc. 1 Texas Instruments

77 Earth Computer Technologies 78 JKmicrosystems, Inc. 53 Nurve Networks LLC 76 Trace Systems, Inc.

32 Elprotronic 41 Jameco 15 PCBCore 75 Triangle Research Int’l, Inc.

10 Elsevier 42 Jeffrey Kerr, LLC C4 Parallax, Inc. 2, 3 WIZnet

ATTENTION ADVERTISERS REVIEWof December Issue 233 January Issue, 234 P Theme: Programmable Logic Deadlines

Retrocomputing on an FPGA: Reconstructing an ’80s-Era Home Computer with Space Close: Nov. 9 Material Close: Nov. 16 Programmable Logic Building Microprogrammed Machines with FPGAs Theme A Practical Parallel CRC Generation Method Embedded Applications WIZnet iMCU Design Contest Primer Bonus Distribution DesignCon THE DARKER SIDE Digital Modulations Demystified Call Shannon Barraclough ABOVE THE GROUND PLANE Memories Not Forever now to reserve your space! FROM THE BENCH Extending and Isolating the I2C Bus 860.875.2199 SILICON UPDATE IP Unplugged: The Internet, Silicon, and Software e-mail: [email protected] November 2009 – Issue 232 November

www.circuitcellar.com • CIRCUIT CELLAR® 79 steve_edit_232.qxp 10/6/2009 4:34 PM Page 96

RIORITY PINTERRUPT by Steve Ciarcia, Founder and Editorial Director Keeping the Lights On

Americans like to think that Thomas Edison came up with the light bulb in 1879 all by himself. But a patent set- tlement clearly gives equal credit to Joseph Swan, an English inventor. More importantly, while those early designs have evolved from glowing carbonized bamboo in a vacuum to radiant tungsten in argon gas, the concept and imple- mentation of incandescent light bulbs have remained pretty much untouched for 130 years. Certainly no other elec- trified invention can claim so much history, so why dump it all now? Barely 6% of the energy powering an incandescent bulb is light. And, while 94% radiated as heat might seem absurd, it isn’t always viewed as a complete waste when there is 3′ of snow outside and you’re heating a house in Connecticut with $4-per-gallon heating oil. Of course, personal rationalization aside, the vast majority of the world views incandescent bulbs as grossly inefficient. As of September 1, you can no longer purchase them in Europe, and the same situation will exist here in 2012. The primary lighting source for the immediate future is supposed to be com- pact fluorescent lights (with LEDs a bit more down the timeline). Invented about the same time as the incandescent bulb, it took until the 1970s for us to have a workable CFL design, and it wasn’t until the 1990s that they became affordable—today they are $1.50. They use about one-fourth the power of an equivalent-lumen incandescent bulb, last 10 times longer, and run a whole lot cooler. What’s not to love? ;-) I am probably a very unique case, but let me just tell you some of the realities of no more incandescent bulbs from my perspective. And, before any newbie readers e-mail me to chastise me for my energy inefficiency, let me remind you that I have 10,760 W of PV panels powering my house and right now my latest electric bill ($0) says that I still have a 700-kWHr surplus (they owe me). Based on what the electric company will give me for the surplus power when we settle up at the end, it’s actually cheaper for me to continue using the remaining incandescent bulbs I have versus the cost of buying more CFLs. OK, I’ll stop ranting. I understand the bigger picture regarding energy waste, but simply substituting CFLs or LEDs for every incandescent light bulb is a myth. The naive truth is “maybe.” If you have a light next to your easy chair where you sit to read Circuit Cellar, it is a perfect candidate for a CFL replace- ment. If your Home Control System (HCS) automatically turns that light on or the wall switch controlling the light is a dimmer switch, good luck! If you have a 150-W motion-controlled flood light on your front walkway, it might seem to be the perfect candidate for a 38-W CFL flood light replacement—provided the controller uses a relay and not a triac, and that you don’t mind being 10 seconds past the point of needing light before you actually see any. I might have a unique case of triple witching (electronically speaking), but I think there are a lot of Circuit Cellar read- ers who utilize powerline or wireless communication and control technologies. You may not be running a complete HCS like I do, but the inoperability of any automated device is just as frustrating. CFLs are wonderful, except when they don’t work. For the most part, they don’t like low temperatures, short-duration power cycling, or semiconductor-based power controls (like dimmers or lamp modules). X10-type automated lighting con- trols should be tested with the specific CFL to be used to make sure that it works and that leakage currents don’t cause the CFL to flash. If you have automated lighting or high-traffic areas where the CFL constantly cycles (like a staircase), be prepared to see an 85% reduction in lifespan on most brands. If you need to keep the dimming capability and still want a CFL, be prepared to pay three to five times more for a “dimmable” CFL and wait a few seconds longer for it to light. In my opinion, CFLs are an interim fix on the road to better lighting efficiency, but they certainly aren’t the solu- tion. In the long run, I believe LED lighting is the answer, but be careful before you jump off that cliff right now too. So far, half of the lights at my house are fluorescents in one form or another. I live with the lower lifespan in some places simply because 5 W trumps 60 and I feel like I should try. In another dozen places, I’m using LED bulbs. Their fast turn-on and long cycle life is great for staircases, bathrooms, and hallways, but they are still too expensive for gen- eral implementation (some high-brightness bulbs also radiate too much RFI). I’m currently testing a 15-W 40″ fluores- cent tube replacement that looks promising, but at $70 versus $3 I need a lot more reason to swap out the 50 or so flu- orescent tubes I have. The reality is that I have a very eclectic mix of lighting solutions that are constantly evolving. Much to the chagrin of the politicians, I have to honestly say that a few of my lighting applications are best handled with regular incandes- cent (or halogen) bulbs. For anyone critical enough to take me to task over it, I just say that when you’re generating your own power too, we’ll talk. ;-)

[email protected] November 2009 – Issue 232 November

80 CIRCUIT CELLAR® • www.circuitcellar.com C3.qxp 8/5/2009 10:18 AM Page 1 Sweet! Introducing the MiniCore™ Series of Networking Modules

Smaller than a sugar packet, the Rabbit® MiniCore series of easy-to-use, ultra-compact, and low-cost networking modules come in several pin-compatible flavors. Optimized for real-time control, communications and networking applications such as energy management and intelligent building automation, MiniCore will surely add sweetness to your design.

t Wireless and wired interfaces t Ultra-compact form factor t Low-profile for design flexibility t Priced for volume applications

Wi-Fi and Ethernet Versions MiniCore Module Development Kits From $ Limited 99 time offer. Buy now at: trabbitwirelesskits.com

1.888.411.7228 rabbitwirelesskits.com 2900 Spafford Street, Davis, CA 95618 C4.qxp 10/1/2009 12:41 PM Page 1 THE MAGAZINE FOR COMPUTER APPLICATIONS

by Neil Forcier ONUSARTICLE B Measuring Propagation Delay with a Universal Counter

Have you lost interest in universal counters? It’s time to reexamine their use value in comparison to more expensive oscilloscopes. This article details how a counter makes a signal path delay measurement, the level of precision possible with a counter, and more. You’ll also learn to identify and eliminate error in your measurement setup.

ver the past couple decades, many engineers whether statistical calculation can be employed, and more. O have lost interest in using universal counters for In this article, I’ll describe how a counter makes a signal signal-timing measurements (e.g., period, pulse width, and path delay measurement, the level of precision possible rise/fall time) because they prefer the more visual features with a counter, and how to maximize it. I also explain how of an oscilloscope. They would rather see a visual display to identify and eliminate error in your measurement setup. of the signals they are trying to characterize than a digital display of a long sequence of numbers that can change to a TIME INTERVAL MEASUREMENTS totally different value with a slight adjustment of a single You can measure propagation delay using a counter’s setting. Not to mention that the measurement capabilities time interval measurement feature. A time interval meas- of a scope go much further than just timing. Scopes often urement is an elapsed time measurement between some provide features that allow engineers to decode digital pro- start event and some stop event. It is comparable to using a tocols and capture nonrepetitive signals, for example. stopwatch to time a runner, where the start event is the The main advantage that counters still hold over today’s signal telling the runner to go and the stop event is the typical scopes is the ability to make high-accuracy and runner crossing the finish line. For a counter making a high-resolution time measurements. Typically, a quality time interval measurement, the start event is an electrical counter offers 10 to 12 digits of resolution, while a scope edge and the stop event is an electrical edge occurring later typically has five to eight digits of resolution. An added bonus is that counters start at a much lower price than Gate opens Gate closes scopes. Thus, counters are viable solutions in applications such as timebase calibration, oscillator development/test- Start ing, and clock signal accuracy testing. A counter’s high accuracy and high resolution also make it a powerful solu- Stop tion for high-precision digital signal propagation delay measurements. Only counters provide accurate measure- Open ment resolution down to nanosecond and even sub- Gate nanosecond levels. This level of resolution is required for measuring the propagation delay of a cable, solder run, Clock high-speed digital logic circuit, or any combination of the Accumulated three. clock pulses How short of a delay time can counters accurately Accumulated count resolve? The answer depends on multiple factors, such as the frequency and accuracy of the counter’s timebase, Figure 1—The time interval measurement process November 2009 – Issue 232 CIRCUITNovember CELLAR DIGITAL BONUS PLUS www.circuitcellar.com • CIRCUIT CELLAR® BONUS 1 in time. The time interval is measured by counting the Averaging will not reduce systematic errors (discussed number of clock pulses that occur between the start and later). The more measurements you average together, the stop event. Figure 1 depicts the time interval measurement more the random error will approach zero. Of course, there process. The start event opens a “gate” that triggers the is always a limit to averaging. The limit is usually the counter to start counting the timebase clock ticks. The noise floor, which typically limits the benefits of averaging counter continues tallying the timebase clock ticks until to more than 2 ps. the stop event triggers the counter to close the gate and The majority of counters on the market today can store a stop counting clock ticks. certain number of readings in memory, and they include There are two fundamental problems with this method built-in statistical calculation capability (e.g., averaging) of measuring the time interval between two events. The that can be applied to the stored readings. For instance, the first is that the minimum time interval that can be meas- 53131A and 53132A can store as few as two and up to ured is limited by the counter’s clock frequency. With a 1,000,000 readings in memory that can be analyzed with typical clock frequency of 10 MHz, the minimum time built-in statistical tools. The only trade-off of employing interval a counter can resolve is 100 ns (the period of one averaging is a longer total measurement time. clock cycle). This means if you were trying to measure the signal path delay of an RG 58 A/U 50-Ω coax cable, which SYSTEMATIC ERROR has a delay of approximately 0.052 ns/cm, the counter There are two main types of systematic error that you could only resolve a minimum cable length of 1,923 cm. have some control over when you make time interval The second problem with this time interval measure- measurements: trigger error and cabling/connector error. ment technique is that the counter’s clock is asynchronous Let’s first focus on trigger error. to the start event. You have no way to tell if the clock You have some control over the quality of the start and count began right at the start of a clock pulse or right at stop edges, the input settings, and the trigger-level settings. the end of a clock pulse, so this can lead to a clock pulse Any input start or stop trigger edges that do not have count error of 1 to –1 in extreme cases. smooth voltage transitions through their rise or fall will To deal with these two limitations, modern counters typ- cause timing errors, unless the irregularities are repeatable ically employ some form of interpolation. Interpolation can between the start and stop edges. For accurate trigger tim- come in both analog and digital forms. It can be imple- ing on digital signals, setting each input on the counter for mented by employing a ramp voltage with a known linear DC coupling is important. AC coupling will have a drastic slew rate. When a start event occurs, it starts the voltage affect on the input digital signal’s slew rate. Also, the effect ramp. Once the first clock edge occurs, an analog-to-digital on the start event slew rate will differ from the effect on converter measures the current ramp voltage. The meas- the stop event slew rate because the capacitance in the ured ramp voltage and the known ramp rate are used to cal- start input circuit will not be exactly matched with the culate the elapsed time between the start event and the stop input circuit capacitance. Trigger errors also surface if first clock edge. A second interpolation circuit is used for you set the trigger-level controls improperly on the start the stop event. Combining the start and stop interpolation and stop events. You need to ensure each event triggers off calculations enables a counter to capture start and stop the same percentage point of the slew rate. events smaller than a single clock cycle with resolution Now let’s look at cabling and connection error. Of into the sub-nanosecond realm. The ability to interpolate is course, any type of cabling, adapters, and connectors need- typically what separates low-cost low-precision counters ed to connect the counter to the start of the signal path and from high-precision universal counters. For example, Agi- the end of the signal path you are trying to measure will lent’s 53131A and 53132A universal counters employ digi- add error to your delay measurement (in the form of tal interpolation that enables them to resolve “single-shot” increased time). The cables, adapters, and connectors also time interval measurements as low as 750 ps and 350 ps, add loading affects to the start and stop signal, changing respectively. the slew rate and amplitude of the start signal versus the stop signal, which in turn adds to the time error of the AVERAGING MEASUREMENTS measurement. When measuring the delay through high- So far we have discussed only how low a counter can speed logic, any effect the logic circuits have on the signal’s resolve a single propagation delay measurement (time-inter- slew rate and amplitude will again cause timing error val measurement). Single-shot measurements are done with between the start and stop signal. just a single start and stop pulse versus continuous repeating start and stop events. The problem with single-shot meas- REDUCING SYSTEMATIC ERRORS urements is that random error and noise in the start/stop You can reduce systematic errors in cables by zeroing out signal—in the counter’s clock signal, in the input signal con- their effects. Simply connect your start and stop cabling ditioning, and in the interpolation circuitry—will reduce the together along with your input signal and perform a time measurement’s useful resolution. Performing statistical aver- interval measurement to characterize the delay of your aging on a continuous start/stop signal can help reduce ran- cabling. Then just subtract that measurement time from dom error. The key here is that the error has to be random, the final measurement time of the cabling plus the signal meaning it takes on a Gaussian or normal distribution. path you are characterizing. November 2009 – Issue 232 CIRCUITNovember CELLAR DIGITAL BONUS PLUS

2 BONUS CIRCUIT CELLAR® • www.circuitcellar.com Here is a basic framework to determine a counter’s reso- Triggers at 3 V or 50% Triggers at 3 V or 70% of rise time of rise time lution and accuracy. If you’re dealing with a single-shot delay measurement, your useful resolution will be limited by the manufacturer-specified time interval measurement 3 V random error, the random error of your start event, and the random error of your stop event. The total amount of use- ful resolution is obtained by using the root sum of squares Start event Stop event (RSS) method on the three terms.

Figure 2—Measuring propagation delay through high-speed digital Single shot resolution = logic 2 22 counter random error + start randdom error + stop random error

Many counters have built-in offset capabilities that allow For counters that employ a high-quality quartz oscillator you to zero out the effects of cabling and connectors. When and use some form of interpolation, the random useful res- zeroing out the delay of your cabling and connectors, use as olution of the counter will typically be in the sub-nanosec- few additional connectors as possible (if any) because every ond region. With a continuous start and stop signal, the connector added for the zero measurement will add timing averaging capabilities of the counter can be used to further error to the final measurement. Performing a delay meas- improve the resolution of the counter. urement on your cabling to zero out its effects will also Random timing error factor out any repeatable systematic trigger error. Using a Resolution from averaging = single counter channel to perform your propagation delay N measurement means you must use some type of T connec- N is the number of measurements averaged together. In tor to route both your start and stop signals into the single theory, by continually increasing the number of readings channel. The delay added by the T connector cannot be averaged together, the random error will continue to zeroed out of your final measurement. The better choice is approach zero. In reality, you will eventually hit the noise to use a two-channel counter that allows you to choose one floor inside the counter. The noise floor depends on the channel as the start input and the other as the stop input. counter itself and the environment it is in. Typically, in a This will alleviate the need for a T connector, which will quality counter, you can expect the noise floor to be less cut down on the error of your final delay measurement. than 10 ps or somewhere between 11 and 12 digits of reso- When measuring propagation delay through high-speed lution. You can easily find the number of averages it will digital logic, you may want to reduce any error caused by take to reach the noise floor by brute force—just keep try- slew rate and amplitude differences between the output ing higher averages until you no longer notice any improve- signal (stop event) and input signal (start event). In Figure 2 ment in the resolution. you can see that the trigger level is set for 3 V for the start Accuracy is dependent on your ability to reduce system- and stop edges. The digital logic changed the amplitude and atic errors. First, you will want to eliminate or reduce all slew rate of the pulse, so the start and stop triggers occur at the errors over which you have some control (discussed different percentage points on the edge. above)—namely, zeroing-out cable effects, setting the prop- To reduce this type of error, use the counter’s time inter- er trigger level, using two channels, and setting the input val measurement capability or the built-in rise/fall time for DC coupling. Then you’re left with the systematic measurement capability to find the slew rate and ampli- errors of the counter, which are out of your control, except tude of both the start event and stop event. Use that infor- for regular calibration. In quality universal counters, sys- mation to establish a trigger level for each based on a per- tematic error will typically add up to at least 1 ns or high- centage of the slew rate. This step will eliminate any error er. But because systematic internal counter error is repeat- caused by differences in the start signal and stop signal able, you can eliminate the majority of it and most cabling slew rates and amplitudes. You can also do this using a effects by simply performing an offset measurement. The scope in conjunction with the counter for an easy visual exception is long-term oscillator drift. Because the oscilla- way to match trigger levels based on a percentage of the tor serves as our time reference for every measurement, we slew rate. cannot perform an offset measurement to eliminate errors related to it; but fortunately, it is one of the smallest con- ACCURACY & RESOLUTION tributors to internal systematic error. For instance, with We discussed various sources of errors and how you can the 53131A and 53132A universal counters, timebase error take advantage of the settings and functionality of a univer- can be less than 1 ps. sal counter to overcome or reduce them in your digital propagation delay measurements. So, putting it all togeth- THE COUNTER ADVANTAGE er, where does that leave you as far as resolution and accu- Counters offer higher accuracy, better resolution, and lower racy are concerned? This is not an easy question to answer cost than scopes. In addition, they are viable solutions in because counter specifications are often hard to read and applications that require high-precision, signal-timing meas- vary from manufacturer to manufacturer. urements. This holds true when you are trying to capture the November 2009 – Issue 232 CIRCUITNovember CELLAR DIGITAL BONUS PLUS www.circuitcellar.com • CIRCUIT CELLAR® BONUS 3 propagation delay through a cable, solder run, high-speed digital logic circuit, or any combination of the three, down to the nanosecond range of useful resolution—and, in some cases, the sub-nanosecond range of resolution. I

Neil Forcier ([email protected]) served in the U.S. Navy for six years as a test and measurement equipment calibration technician aboard the USS Harry S. Truman CVN-75. He earned a bachelor’s degree in engineering from The Pennsylvania State University (University Park). Neil is an application engineer for Agilent Technologies, System Products Division. His areas of interest include embedded system design/testing, automated measurement technology, network architecture, and alternative energy.

S OURCE 53131A and 53132A Universal counters Agilent Technologies | www.agilent.com November 2009 – Issue 232 CIRCUITNovember CELLAR DIGITAL BONUS PLUS

4 BONUS CIRCUIT CELLAR® • www.circuitcellar.com