Circuit Cellar - 2010 06



Comments



Description

Cover - 239-out_Layout 1 5/13/2010 1:06 PM Page 1Automation with Embedded CANOpen, p. 24 • Single-Key Touch Chips, p. 69 THE MAGAZINE FOR COMPUTER A P P L I C AT I O N S #239 June 2010 WWVB Receiver DSP OAE Probe Amp & Otoacoustic Experiments The USB Enumeration Process Explained Understanding DC/DC Converters Custom Interpreter Development $5.95 U.S. ($6.95 Canada) www.circuitcellar.com C2.qxp 12/4/2009 2:11 PM Page 1 SSH Encrypted SERIAL TO ETHERNET SOLUTIONS Instantly network-enable any serial device Works out of the box no programming is required Device P/N: SB70LC-100CR Kit P/N: NNDK-SB70LC-KIT $47 Qty. 1000 Customize to suit any application with low-cost development kit SB70LC 256-bit encryption protects data from unauthorized monitoring 2-port serial-to-Ethernet server Features: 10/100 Ethernet TCP/UDP/SSH/SSL modes DHCP/Static IP Support Data rates up to 921.6kbps Web-based configuration Device P/N: SB700-EX-100CR Kit P/N: NNDK-SB700EX-KIT SB700EX 2-port serial-to-Ethernet server with RS-232 & RS-485/422 support $129 Qty. 1000 Need a custom solution? NetBurner Serial to Ethernet Development Kits are available to customize any aspect of operation including web pages, data filtering, or custom network applications. All kits include platform hardware, ANSI C/C++ compiler, TCP/IP stack, web server, email protocols, RTOS, flash file system, Eclipse IDE, debugger, cables and power supply. The NetBurner Security Suite option includes SSH v1 & v2 support. Device P/N: CB34-EX-100IR Kit P/N: NNDK-CB34EX-KIT $149 Qty. 1000 CB34EX industrial temperature grade Information and Sales | [email protected] Web | www.netburner.com Telephone | 1-800-695-6828 2-port serial-to-Ethernet server with RS-232 & RS-485/422 support and terminal block connector www.WorldMags.net & www.Journal-Plaza.net 9.qxp 8/7/2008 11:04 AM Page 1 www.WorldMags.net & www.Journal-Plaza.net 2_Layout 1 5/12/2010 7:18 AM Page 1 www.WorldMags.net & www.Journal-Plaza.net Journal-Plaza.net & www.WorldMags.net .2_Layout 1 5/12/2010 7:18 AM Page 2 www. academics. Vernon.S. Two-year (24 issues) subscription rate USA and possessions $49. he or she is ridiculed as a myopic drone with few skills or interests outside his or her technical specialty. Let me explain why. Its mission is to help readers become well-rounded. All rights reserved. Our strength is that we publish a consistently high-end periodical for serious readers seeking to become as technically well-rounded as possible. Circuit Cellar is a registered trademark of Circuit Cellar.rakoczyphoto. Ready to broaden your horizon? Start reading.95. On the other hand.875. Periodical rates paid at Vernon. the English major). 4 CIRCUIT CELLAR® www. 24). 44). E-mail: reprints@circuitcellar. music. bank.com PRINTED IN THE UNITED STATES CONTACTS SUBSCRIPTIONS Information: www. Circuit Cellar.3741 • 978. Circuit Cellar is challenging the conventional notions of what it means to be educated in 2010. design/programming techniques. all other countries $49. CIRCUIT CELLAR®. Circulation Dept.6301. A graduate of the former is. Circuit Cellar® makes no claims or warrants that readers have a right to build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction. 69). Hanover.us Fax: 978. Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions. What do they all have in common? An interest in the most hightech of technology. THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar Incorporated. Incorporated. problems. but we are not a hobby magazine with multiple “intellectual access points”—such as a plugand-play blinking LED project article for the novice followed by an MCU-based radiation detector article for the pro. All subscription orders payable in U. all other countries $85. CT 06066.g. he or she is considered a “Jack of all trades. because of possible variation in the quality and condition of materials and workmanship of reader-assembled projects.luster@circuitcellar. CT and additional offices. engineering. 4 Park Street. NH 03755-5650 or call 800.Journal-Plaza. a featureless clock and signal processing (p. 4 Park St. Box 5650.O..95.2199. Gloucester.269. descriptions.com AUTHORIZED REPRINTS INFORMATION 860. E-mail: newproducts@circuitcellar. funds only via Visa. Vernon. www. at worst.95.net • www. Canada/Mexico $34. international postal money order. Who are these readers? Only engineers and programmers. history.S. Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Box 5650.95. Abate ASSOCIATE PUBLISHER Shannon Barraclough WEST COAST EDITOR Tom Cantrell CUSTOMER SERVICE Debbie Lavoie CONTRIBUTING EDITORS Jeff Bachiochi Robert Lacoste George Martin Ed Nisley CONTROLLER Jeff Yanco ART DIRECTOR KC Prescott GRAPHIC DESIGNERS Grace Chen Carey Penney NEW PRODUCTS EDITOR John Gorsky PROJECT EDITORS Gary Bodley Ken Davidson David Tweed STAFF ENGINEER John Gorsky ADVERTISING 800. thought of as a focused intellectual with money-making potential.281.com Cover photography by Chris Rakoczy—Rakoczy Photography www. and technologies—particularly at a time when single-skill “specialists” are rapidly losing relevance. etc.circuitcellar. This issue comprises information on a variety of important topics: a customized interpretor and domain-specific languages (p. software. cutting-edge engineering ideas to bear on any number of relevant tasks. capacitive touch sensors (p. and more.com Editorial Office: Editor.com AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article.com GENERAL INFORMATION 860. 54). programming.O. 62).7708 • www. P. literature.281.com/advertise ADVERTISING REPRESENTATIVE Peter Wostrel Strategic Media Marketing. characterized as an urbane scholar.269. The reader assumes any risk of infringement liability for constructing or operating such devices. Inc. And as a result.875.871. electronics. One-year (12 issues) subscription rate USA and possessions $29.circuitcellar. Each month.circuitcellar. we reach readers with diverse backgrounds in locations all over the world with engaging editorial content: project articles. or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.6301. Most people think there are two main courses of study: liberal studies (e.. at best. business. Well.” Nor do our readers with backgrounds outside of electronics engineering consider themselves simple hobbyists who couldn’t possibly find a topic like DSP accessible.com/subscribe. or check drawn on U. We provide professional-level content on everything embedded-related—and these days. and beyond. we can boast a multi-talented readership with backgrounds ranging from chip design to filmmaking to media art to industrial management.g.. Entire contents copyright © 2010 by Circuit Cellar. Inc. Box 5650. NH 03755-5650. CT 06066. Hanover. Hanover.7708 peter@smmarketing. 36). The information provided by Circuit Cellar® is for educational purposes.com New Products: New Products.. etc). We appeal to a wide audience. Furthermore. Postmaster: Send address changes to Circuit Cellar. the Engineering major) is. Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from plans. since embedded technology is everywhere..454. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc.us • www. tutorials. is prohibited.g. and more.. MA 01930 USA 800. MasterCard. multidisciplinary technicians who can confidently bring innovative. right? Wrong.com . At worst. E-mail: editor@circuitcellar. USB and enumeration (p. Circuit Cellar.95. Fax: 860.2199.454. J.281. at best. E-mail: [email protected]. or information published by Circuit Cellar®.net & www.0411. master of none” (e. cj@circuitcellar. that means hardware. programmers. P.7706 ADVERTISING COORDINATOR Valerie Luster E-mail: val.com Subscribe: 800. E-mail: info@circuitcellar. the “professional studies” graduate (e.com FOUNDER/EDITORIAL DIRECTOR Steve Ciarcia PUBLISHER Hugo Vanhaecke EDITOR-IN-CHIEF C. We recognize that readers don’t want to be typecast as either “hardware engineers” or “software designers.WorldMags.Task_Masthead_239_masthead. inductors and DC/DC converters (p.circuitcellar. 4 Park St. CT 06066. NH 03755-5650 Address Changes/Problems: E-mail: subscribe@circuitcellar.. 16). and intellectuals interested in computer applications. MCU-based automation and CANOpen software (p. Vernon.3741 • 978. Circuit Cellar Subscriptions.com/subscribe.qxd 5/13/2010 12:41 PM Page 4 T ASK MANAGER THE MAGAZINE FOR COMPUTER APPLICATIONS Embedded Is Everywhere June 2010 – Issue 239 E ach month Circuit Cellar delivers need-to-know technical information to embedded design engineers.) and professional studies (e. 1187 Washington St..smmarketing. a probe amp and otoacoustic experiments (p.O. P. Canada/Mexico $59. Jameco. What did he buy? Go to www.Jameco. the homemade super capacitor would be made from several layers of lemon juice-soaked paper towels interleaved between several layers of a mystery material to form a multi-layer stack. but first he wanted to show how the students could make their own super capacitor and demonstrate its charge/discharge cycles with the simple circuit above.net . Ollie rushed to a nearby pet shop.The stacked layers would then be sandwiched between the two copper-clad PC boards and held together with a rubber band. sign-up for our free full-color catalog.com/teaser7 to see if you are correct and while you are there. Most of the components were already on his workbench. 1-800-831-4242 | www.net & www.com www.Journal-Plaza.5_Layout 1 5/12/2010 8:27 AM Page 1 What is the missing component? Electronics instructor Ollie Circuits planned to show his class of freshman electrical engineering students how to use a super capacitor as a memory back-up capacitor.WorldMags. Otoacoustic Experiments p.WorldMags. 36. Abate 4 NEW PRODUCT NEWS edited by John Gorsky 8 TEST YOUR EQ SOLUTIONS 15 CROSSWORD 74 INDEX OF ADVERTISERS July Preview 79 PRIORITY INTERRUPT Is It Cheating or Is It Collaboration? Steve Ciarcia 80 FROM THE BENCH Application Communication with USB (Part 1) The Enumeration Process Explained Jeff Bachiochi SILICON UPDATE Pitch the Switch Tom Cantrell 6 CIRCUIT CELLAR® www. Push Button Switch Modules 44 ABOVE THE GROUND PLANE Totally Featureless Clock (Part 3) Signal Processing Ed Nisley 54 THE DARKER SIDE DC/DC Converter Basics Robert Lacoste June 2010 – Issue 239 62 69 TASK MANAGER Embedded Is Everywhere C. 16. 69.net & www.com . Interpreter Development p.Journal-Plaza. J.qxd 5/13/2010 7:40 AM Page 6 239 INSIDE ISSUE June 2010 16 24 36 • Communications Custom Interpreter Development An Innovative LED Movie Project Chris Cantrell INTELLIGENT ENERGY SOLUTIONS Home Automation for an Energy-Efficient House (Part 2) Embedded CANOpen Node Hardware & Software Stefan Siegel OAE Probe Amp and Intercom (Part 2) Otoacoustic Experiments Chris Paiano p.TOC_239_toc.circuitcellar. Touch Tech p.net • www. 24. 2-3.qxp 11/2/2009 3:52 PM Page 2 www.net .Journal-Plaza.net & www.WorldMags. CDMA AND UMTS MODEMS SMALL-SIZED POWER AMPLIFIER REDUCES COMPONENT COST The highly successful Terminus platform of GSM/GPRS.com California Eastern Laboratories www. Virtual Communications Port (VCP) interface. and other consumer electronics. June 2010 – Issue 239 Janus Remote Communications www. Free utility software includes the iBurner I2C Bus EEPROM programming software. and Mac. ESD. and dual-stage fuses for laptop or desktop computer protection. Developed in cooperation with wireless module manufacturer Telit Wireless Solutions. these cellular devices are available as open frame modules. cable replacement. Simply plug the i2cStick into a laptop’s USB port. i2cStick’s API compatibility extends to other MCC I2C Bus adapters. the new 2251 is one of the smallest power amplifiers in the industry.to 5-V compatible. Pricing is $85 per unit in 1.npn239_Layout 1 5/12/2010 9:03 AM Page 8 COMPACT USB-TO-I2C HOST ADAPTER The i2cStick brings high-performance I2C to on-the-go mobile developers. and intelligent lighting control systems. and headsets.to 1. Micro Computer Control Corp. and multi-master and arbitration detection capability. C. and includes over-voltage.4/ZigBee devices. digital cameras. The i2cStick supports 7-bit slave addressing.15. which have wide applicability in automatic meter reading.com . bus-powered. these interchangeable modules are specifically designed for quick and easy integration into all new and existing M2M designs.000-piece quantities. CDMA. LabVIEW Virtual Instrument Library. and MFC. mobile phones. and field support personnel.000 and evaluation boards are available.15. Pricing is $0. Terminus CDMA864CF. www. Prices range from $150 to $250 depending on interface cable configuration and order quantity. the Terminus GSM865CF.janus-rc. enabling product designs where PCB space is scarce such as smart phones.com S W E N CT DU R O P NEW Edited by 8 CIRCUIT CELLAR® www. The new PA eliminates the need for RF component matching. and Terminus UMTS864CF share the same mechanical footprint and offer users the ability to easily configure their applications for communication via any cellular protocol. and UMTS modem devices is expanding to include a new range of board-level. connect to a target device with the provided clip-lead or header cable. and start communicating. The PA boosts range for CEL’s extensive line of 802. The device is 3. provides switch-enabled bus pull-ups.8-V control voltage. and simplifies procurement. VCP drivers are available for Windows. hand-held gaming devices. has a 5-V power source for external devices. At 2 mm × 2 mm.Journal-Plaza. California Eastern Laboratories (CEL) is now shipping its new uPG2251T6M GaAs power amplifier (PA). Combining full M2M functionality with the flexibility of a standard “plug-in” DIP design. iPort/AFM. Enclosed designs employing the modules will be available as requested by customers.net & www.cel. plug-in modules for use in wireless communication applications. All plug-in modules operate at 5 V and the GSM and UMTS modules include SIM Card sockets.circuitcellar.82 in quantities of 100. reverse-voltage. saves bill of materials cost. and iPort/AI.net • John Gorsky www.3.4/ZigBee modules. Application developer support includes a . test engineers. and sample software projects in VB. The amplifier operates off a supply voltage of 3 V with a 0. bus master or slave operation at standard (100 kHz) or fast (400 kHz) clock rates. The i2cStick is a pocket-size. including the iPort/USB. wireless security. The new 2251 PA is ideal for applications such as Bluetooth modules designed into notebooks. and Message Center messaging software. which reduces component count.NET Class Library.mcc-us. To allow for easy integration. ASCII-Text application program interface (API). C++. USB-to-I2C Bus adapter.WorldMags. It’s also ideal for 802.com GSM/GPRS. Linux. ® Cortex™.DPSFT t3FBMUJNFNVMUJUBTLJOH. Cost-effective. Stellaris LM3S9B90 Ethernet Evaluation Kit Stellaris LM3S8962 Evaluation Kit Stellaris LM3S3748 Evaluation Kit featuring USB.$6T t"EWBODFEJOUFSSVQUESJWFOTPGUXBSFXJUI4UFMMBSJTXBSF® software Stellaris LM3S6965 Ethernet Evaluation Kit Stellaris LM3S811 Evaluation Kit Stellaris LM3S2965 CAN Evaluation Kit demonstrating an embedded web server out-of-the-box featuring basic embedded control demonstrating a CAN network out-of-the-box $69 $49 $79 Product Information Center .9_Layout 1 5/12/2010 8:28 AM Page 1 ® Stellaris Connected. Versatile. Ethernet and CAN featuring integrated Ethernet and CAN featuring USB Host/Device $99 $89 $109 Stellaris® Means: t%FUFSNJOJTUJD"3. Journal-Plaza.net & www.net .ti.  TVQQPSUUJDPNTDQJDBNFSJDBTIUN buy now: www.com/stellaris-cc www.com/stellariskits-cc www.ti.WorldMags. Journal-Plaza.net .WorldMags.net & www.10_Layout 1 5/12/2010 8:32 AM Page 1 www. com • 11 CIRCUIT CELLAR® www. including cell phones and other devices that require embedded RFID capabilities.8 mm.net & www. functionality and fast integration make the cost-effective LXRW ideally suited for stationary and handheld UHF generation 2 RFID reader-writer units.npn239_Layout 1 5/12/2010 9:03 AM Page 11 WORLD’S SMALLEST RFID READER-WRITER MODULE The LXRW series is the world’s smallest UHF RFID reader-writer module.Journal-Plaza.circuitcellar. Other reader-writer modules typically have a connector which requires a manual connection to a motherboard within the reader production line. power amplifier.net .com June 2010 – Issue 239 NPN www. the surface-mount module is 85% smaller in footprint and 92% smaller by volume when compared to existing reader-writer modules with the same output power. The LXRW reader-writer series sample is available for $120 with significantly lower prices available with volume orders. In addition. Despite its dramatically reduced size.WorldMags.murata. the LXRW is feature rich. Murata’s new module eliminates this costly and time-consuming process. antenna-matching circuit. the LXRW series can be directly mounted onto a printed circuit board using a standard surface-mount assembly line. Included in the module are the processing unit. and oscillator. random access memory. generation 2 firmware. The combination of its small size. Measuring only 23 mm × 13 mm × 2. it has three serial port options and a 100-mW maximum output power for ranges up to two feet with a small size antenna. offering complete RF and baseband functionality. as a surface mount device. Also. Murata Electronics North America www. net .17.Journal-Plaza.net & www.WorldMags.qxp 2/9/2010 9:56 AM Page 1 www. Numerous “software hooks” provide control and flexibility. www.com $99 #1 PC based OBD-II scan tool. a range of ultra-low power modes plus low Tx/Rx power consumption makes the LT2510 ideal for power-restricted or battery-operated applications.lairdtech. integrated solution.net . Enhanced API commands provide dynamic packet routing control and network intelligence. 100% compatible with the ELM327 command set. Functional and physical addressing. RS232. Embedded with a robust server-client protocol. Free OBDwizTM software included. PRM121. Each transceiver is designed to provide OEMs with a feature-rich. configurable.com OBD-II interpreter module in a DIP-24 package. allowing OEMs to build the most optimized network possible.ECUsim.OBDLink. Bluetooth. Inc. PRM113. Contact Laird Technologies for pricing.4-GHz WIRELESS RADIO MODULE PRODUCT FAMILY Laird Technologies announces the introduction of its enhanced LT2510 proprietary 2.com NPN microOBD 200 www. Laird Technologies. and provides an extremely reliable communication link. PRM112. high-performance.com Professional multiprotocol OBD-II ECU simulator. ECUsim 5100 www. PRM120. as opposed to squeezing the application into a fixed communication technology or standard.4-GHz wireless module product family.microOBD. and WiFi options. $49 OBDLink www. allows for co-located systems. The configuration and test software allows OEMs to design and test networks to suit their applications. bootloader. compatible. secure. UART interface. the LT2510 permits an unlimited number of clients to synchronize to a single server for low latency communications. Full support of all OBD-II protocols Free regular firmware updates Discount code for free shipping: CC1006FS Questions? Email sales@scantool. PRM122. In addition.circuitcellar. With its field-proven frequency-hopping spread spectrum (FHSS) air interface protocol.WorldMags. The server and all clients in a network can communicate with any radio in range via either addressed or broadcast packets. three virtual ECUs. the LT2510 delivers speedy data rates. and PRM123. excels in multipath scenarios.npn239_Layout 1 5/12/2010 9:03 AM Page 13 2.Journal-Plaza. With a throughput of up to 250 Kbps in half-duplex mode. USB. PRM111. The product series includes model numbers PRM110.net & www. At the same time. software configurable. the LT2510 rejects RF noise.net www. variable output power options of up to 21 dBm (depending on region) enable communication over distances that aren’t achievable with competing technologies.com • June 2010 – Issue 239 $549 13 CIRCUIT CELLAR® www. allowing designers to mold the communication link around applications. Pricing depends on the connectors and configuration required.95 By: Robert Lacoste ISBN: 9781856177627 $44.com www. 50-Ω coax cable assemblies include the Micro Coax Cable (ERCD Series) and the Direct-to-Lead Coax Cable (ERCDA Series) which is rated from 890 MHz (1 m) to 7. RUGGED.95 By: William Kafig ISBN: 9781856177047 $44. 100-Ω Differential Pair Twinax Cable (ERDP Series) is rated from 1.org.indd 1 2/22/10 9:56:17 PM 14 CIRCUIT CELLAR® www. Everything you need to know to get started.com .net • www.90 GHz (6″) and is hot pluggable.0315″) pitch Edge Rate terminals and sockets (ERM8/ERF8 Series). and ARM). Inc.net & www. Micro Coax. Register for our e-news at newnespress.95 By: Gina Smith ISBN: 9781856177061 $44. The result is a robust family of cable-to-board interconnect solutions ideal for high-speed and long cable run applications as well as for emulation testing (the ERF8 Series connector has been specified as the standard board level interface by NEXUS.newnespres s. The Micro Coax and Twinax assemblies also have an optional squeeze latch system that prevents unintentional de-mating. The Edge Rate 30 AWG.npn239_Layout 1 5/12/2010 9:07 AM Page 14 EDGE RATE CABLES FOR HIGH-SPEED.8-mm (0.Journal-Plaza.samtec. and Direct-to-Lead Coax Cable Assemblies incorporate its rugged 0. All three systems feature rugged friction latches that increase de-mating to 7 lb. Edge Rate 34 AWG.com GZXZ^kZdjgWZhiY^hXdjcih™=ZVgVWdjiWdd`hWZ[dgZi]ZnejWa^h] 6XXZhhid[gZZhVbeaZX]VeiZgh!k^YZdijidg^VahVcYbdgZ 20100490_AD_CircuitCellar_034_1200.33 GHz (6″) and is also hot pluggable. which are designed for superior signal integrity and impedance control and reduced broadside coupling.95 June 2010 – Issue 239 Stop by booth 1823 at ESC West to check out these titles and more! Save 20% when you buy at the show. & TEST APPLICATIONS Samtec’s High-Speed Edge Rate Twinax. www. Samtec. The Direct-to-Lead cable is also designed to optimize signal integrity with a patent-pending direct termination that eliminates the need for a PCB.circuitcellar. POWER. By: Michael Parker ISBN: 9781856179218 $54.com NPN N e w n e s P r e s s Education Never Ends.41 GHz (1 m) to 6.WorldMags. While it would be prohibitive in terms of CPU cycles to compute an FFT over a sliding window (a complete FFT for each input sample). you don’t really care about phase information at all. You don’t see all the detail. as presented to an ADC. Answer 3—While the DFT can be computed on a time series of any length.WorldMags. 8 Digital Inputs + 1 MSa/sec charting They don’t have DC offset. Time resolution is the ability to determine when a tone starts or stops. time-resolution trade-off. noise. A small block size has good time resolution. www. Contributed by David Tweed You may contact the quizmasters at eq@circuitcellar. 52x worse than ours. keep up the good work !!!!!" Karl. but not for arbitrary ones. The spectral response has good SNR.circuitcellar. low spectral leakage. the DFT lends itself quite nicely to a sliding-window implementation.3/1000 = 300 uV (even better at 18uV with the 14 bit ADC). As a result. and spectral leakage. it can handle arbitrary values in either series. However.vs. The discrete Fourier transform (DFT) is the same relationship between a set of values representing a time series and the equivalent set of values that represent a frequency series. Signal: Video color burst. Task: check DC levels. 12 or 14 bit resolution so you see the detail in the signal. They have to digitize over -2V to +2V to capture this signal. it is necessary to decide what block length is best for a particular application.com/eq/ have any particular phase relationship. and the spectral response has poor SNR. In terms of the implementation of a DFT. You see all the detail. rather than breaking the input samples into blocks at arbitrary boundaries.eq-239_Layout 1 5/12/2010 8:21 AM Page 15 CIRCUIT CELLAR Test Your ANSWERS for Issue 238 EQ Edited by David Tweed Answer 1—The Fourier transform is a mathematical relationship between a continuous time-domain function and the equivalent frequency-domain function. good bandwidth occupancy. This reduces the number of basic operations—such as addition and multiplication—that need to be performed. whether you need them or not. the FFT is usually implemented on blocks of samples that are a power of two in length. and almost as bad to do a complete Goertzel algorithm for each sample. it often requires fewer CPU cycles to compute them directly with the DFT algorithm than to execute the full FFT algorithm. and only 8 bits. Theirs : Communications systems transfer voice.Journal-Plaza. In tone detection applications. 12 or 14 bit ADC + Ext Trigger. If you’re only interested in a few of the bins. there are specific solutions for specific functions.cleverscope. and you can in fact use a fixed set of coefficients for each calculation that include the “window” function (lowpass filter) implicitly. USA Ours: Ours 100 MHz MSO 8M Samples 14 bit We have proper DC offset and 10. As such. In a tone detection application. The Cleverscope 14 bit scopes provide all the tools needed to verify the performance of your design.net & www. The fast Fourier transform (FFT) is a particular implementation of the DFT that takes advantage of certain redundancies in the numerical operations that are performed. rather than calculating it as a separate step. amplitudes and phase relationships.net . the FFT computes all of the frequency bins. Communications 15 CIRCUIT CELLAR® www.5V. while a large block size has the opposite characteristics. This gives you a little more leeway with respect to the frequency.circuitcellar. Answer 4—The Goertzel algorithm is a one-bin nonrecursive DFT calculation converted into an equivalent recursive form (requiring much less data storage and very few CPU cycles per sample) that comes up with the same answer. As such. it is often useful to implement the detection algorithm over a “sliding window” of input samples.com www. this means that the sine and cosine functions that you generate to multiply with the incoming signal don’t need to What’s your EQ?—The answers are posted at www. the DFT is O(N2). while the FFT is O(N log N). In this example we digitize over the range 1. data and video.2 to 1.com Are all oscilloscopes created equal? "Cleverscope is still the best out there. and low distortion. Frequency resolution is the ability to distinguish two different frequencies that are close together. The resolution is 4000/256 = 16 mV. including their frequencies.com • In the USA call: June 2010 – Issue 239 + Two mixed signal triggers + Protocol decoding + Spectrum analysis + Symbolic maths + Custom units + Copy & paste + Signal generator + USB or Ethernet + 4 or 8M samples storage + 100 MHz sampling + Dual 10. In “big O” notation. These signals are often digitized. you’re really just looking to see whether a particular frequency component is present at a level above a certain amplitude threshold. time resolution. The trade-off is frequency resolution vs. Answer 2—A Fourier transform gives you information about the component sine waves that are part of a complex signal. but poor frequency resolution. you need good signal to noise (SNR). With the 10 bit ADC the resolution is 0. Since it is computed numerically. To make best use of scarce bandwidth. The left (bottom) half includes the Propeller circuit and sound chips wired on a solderless breadboard. Finally. b—The project opens to reveal the components inside.WorldMags.net • www. Every project has its own specific hardware requirements. Here a rather plump partridge sits on a limb in a pear tree.circuitcellar. elegant dialect was needed.com . The right (top) half includes the four LED boards glued together with the speakers. the chip offers eight pieces of putty you can June 2010 – Issue 239 a) mold into the specific hardware functions you need.Journal-Plaza. A single 5-V regulated wall wart powers the project. The Parallax Propeller chip is a step forward from this brute-force general solution. each with its own unique language: one for movie frames and one for music. 16 CIRCUIT CELLAR® www. and we coded with general-purpose programming languages we slung like clumsy hammers when a more sophisticated. These “putty” cogs also serve as the basic building blocks for custom CPUs tailor-fit to your specific project needs. I will show you how I used the cogs to create several virtual hardware modules mapped into the Propeller chip’s shared memory space. In this article I’ll explain my “putty” approach to designing with the Propeller chip. I can see the day coming when my nerdy grandchildren will ask me what embedded design life was like when I was young. yet today we end up forcing a general off-the-shelf embedded controller to fit different needs. each with its own unique language: one for movie frames and one for music.net & www. And along with these homegrown CPU opcodes. I’ll also show you how I used the cogs to create two specific CPUs. I will tell them about the days when opcodes were rigid things given to us by CPU makers. and the SD card. Instead of providing a fixed set of hardware functions. an amplifier. The design reads movie frames from an SD card and displays them on a 48 × 32 LED display while generating music with six independent voices. you can create “domain-specific languages”—programming languages custom-built for a specific application.F EATURE 2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:46 AM Page 16 ARTICLE by Chris Cantrell (USA) Custom Interpreter Development An Innovative LED Movie Project Ready to make movies? Here you learn how to create two specific CPUs. I’ll describe my SPIN and Java b) Photo 1a—The running movie ornament shows the combined creativity of my entire family. If you have ever walked past an arcade. The display boards require a single 5-V supply. and I tested each module with a small SPIN program that writes and reads the memory mapped virtual registers. recognize 3. you must write the peripheral functions in software and dedicate one of the eight processors to bit-banging the I/O pins. Virtual hardware modules twiddle the I/O signals just like the real things. The hardware cog then pulls the data from shared memory and clocks it out to the displays in the background. and I used a 5-V regulated wall wart to power the entire project. of course. and Propeller circuit.net & www. I discovered the hard way that the display boards do not recognize the 3. the hardware cog sets the Command register back to zero. To the outside world. I implemented each peripheral in cog RISC assembly.WorldMags. I used 7404 TTL inverter gates to bump each board’s CHIPSELECT/DATA/WRITE signals up to 5 V.3 V as high. These chips were popular in computers and arcade games in the 1980s. TTL chips. but the software approach allows you to create a wide www. The project reads movie frames from an SD card and displays them on a 48 × 32 LED display while generating music with six independent voices.) The SD card and sound chips hook to the Propeller’s I/O pins with two resistors. Moonpatrol. There are no interrupt lines and no integrated peripherals. Two inverter chips boost the Propeller’s 3.circuitcellar. HARDWARE The Propeller chip is a collection of eight lightning-fast RISC processors. 17 CIRCUIT CELLAR® www. Each processor has its own tiny 2 KB of RAM for data and code. I used a 3. custom CPUs.3-V power regulator to step down the 5 V for the Propeller chip. Tron. the putty looks like standard memory-mapped hardware tied into the shared 32-KB RAM space. EEPROM. I used two Texas Instruments AY38910 sound chips for the audio in the project.” I started this project by designing the virtual hardware modules.3-V I/O pins to 5 V for the display. I used one Propeller cog as putty to map the display hardware into the propeller shared memory as two registers: Address and Command.net .2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:46 AM Page 17 toolchain to get you started with your own custom CPUs and the language compilers to support them. Instead. Photo 1b shows the project built on a solderless breadboard The display for this project is a combination of four DE-DP016 boards from Sure Electronics. you have heard their voices from games like Frogger. All eight processors share a large pool of 32 KB used for data (code cannot execute directly from this shared space).com • variety of peripherals for different projects. Each board has a 24 × 16 LED matrix and an interface/driver chip that accepts serial SPI-like commands from a host controller. On the inside. and domain-specific languages with my Propeller LED movie project (see Photo 1a). the putty looks like standard hardware devices driving the I/O pins. I’ll demonstrate my virtual hardware. (More info is available on Parallax’s website.Journal-Plaza. An application writes the address of the pixel data to the hardware Address register and then writes a nonzero value to the Command register. I like to think of the Propeller cog CPUs as eight pieces of putty between the I/O pins and the 32 KB of shared RAM space. When the display has been drawn. The whole family chipped in and made the movie sequences for each of “The 12 Days of Christmas.3 V high I/O signals from the Propeller. Software functions are slower than an integrated peripheral. Timepilot.” The project makes a nice seasonal ornament that I add to each year. Figure 1 shows the project’s circuitry. The application sees the virtual hardware as a set of hardware registers that work very much like “the real things. June 2010 – Issue 239 Figure 1—Take a look at the power. I glued four boards together in a 2 × 2 block to make a single display of 48 × 32 LEDs. full software examples are presented that can be the basis for further projects. an object-oriented scripting language.elektor.18_Layout 1 5/12/2010 8:36 AM Page 1 BOARDS. The book covers the Visual Studio 2008 development environment. Writing low level code for graph- fader.60 446 pages • ISBN 978-0-905705-70-5 • $51.COM/SHOP Elektor Shop The world of electronics at your fingertips! Microsoft approved! ! W E N Learn more about C# programming and . a RGB abstraction also applies when writing graphic user-interfaces. This hands-on book covers a series of exciting Obviously having fewer lines of code will be quicker to write but also fewer lines of code means and fun projects with PIC microcontrollers. The programming language PIC Microcontrollers used is Python. later date.E www. BOOKS. Books 240 pages • ISBN 978-0-905705-81-1• $47. DVDs AND MORE AT WWW. schematics.net & www.NET environment and C# programming or who have an interest in interfacing hardware to a PC.60 ore This book and m are available at om/books www. In Python all this is sound super-compression. say. Practical demonstration circuits and down- of each project on a breadboard make this a loadable. 224 pages • ISBN 978-0-905705-87-3 • $47. and pictures computers without requiring hard drive installation. fun activity.ELEKTOR. You can build wrapped up in relatively simple functions. The book guides you through starting with Linux by more than 50 projects for your own use.70 Prices and item descriptions subject to change. and easier to modify at a For example a silent alarm.c Get started quickly and proceed rapidly Python Programming and GUIs This book is aimed at people who want to interface PCs with hardware projects using graphic 50 projects for beginners and experts user interfaces.WorldMags. E. a higher level language than. a serial network.NET C# 2008 and . Code will be more readable. & O. C. a poetry box and a ics and mouse clicks and the like is something that you do not have to do. fewer opportunities to make mistakes. a night buzzer. You can concentrate on the overall operation of the system you are making. a people sensor. The way of a free downloadable. the .NET framework and C# programming language from data types and program flow to more advanced concepts including object oriented programming. This a radar. live bootable distribution that can be ported around different clear explanations. Desktop and web based applications are covered.Journal-Plaza. a VU meter.net .NET programming for Electronic Engineers This book is aimed at Engineers and Scientists who want to learn about the . ISBN 978-90-5381-251-8 •$28.100 articles the most popular items in Elektor’s product DVD Elektor 1990 through 1999 range. hard copy of PCB layouts at printer resolution. zoom in /out on selected PCB but nothing should deter you from becom- areas and export circuit diagrams and illus- ing Master of Embedded Systems Universe trations to other programs. An extensive search ma- prototyping system. with the help of the Elektor Sceptre. This DVD-ROM contains all editorial articles published in Volume 2009 of the Eng- Reign with the Sceptre This DVD-ROM contains the full range of lish.CD/DVD-ROMs 19_Layout 1 5/12/2010 8:36 AM Page 1 A whole year onto a single disk DVD Elektor 2009 New! The year volume DVD/CD-ROMs are among 110 issues.30 0#".30 adapt PCB layouts using your favourite graph- the board’s peripherals. ics program. we also alphabetically by topic. in publication (month/year). but are also listed chine is available to locate keywords in any addition to a very useful little board. Spanish. Ambitious? Maybe. Dutch. To justify this title. The plied Adobe Reader program. more than 2. With this DVD you can also produce need user-friendly development tools and dex enables you to search the entire DVD.100 separate articles have been sented in the same layout as originally found ripherals — it seeks to be a 32-bit ARM7 fast classified chronologically by their dates of in the magazine. American. A comprehensive in- article. libraries that allow fast implementation of ISBN 978-0-905705-76-7 • $111. articles are pre- a big microcontroller and a few useful pe- more than 2. Using the sup- aims to be more than just a little board with Elektor Electronics magazine (PDF). French and This open-source & open-hardware project 1990-1999 volumes (all 110 issues) of German editions of Elektor. POPULATEDANDTESTED. application notes. For standard models.# 090786-71 • $103. TESTSOFTWARELOADED Art. the increased complexity of a switch- and controlling LEDs in different configu- mode design scares away many potential rations.. It’s your one-stop shop for Elektor Books. This DVD contains more than 100 Elektor articles on the subject of LEDs. UniLab A power supply with adjustable output volt- www. etc. even though it actually isn’t all that (power supply units.# 090559-91• $212. this DVD is suitable for building a single or dual power also addresses the main shortcoming of power LEDs: heating.WorldMags. less power transformer Art. dim- complicated if you use a suitable combina- mers.Journal-Plaza. ISBN 978-90-5381-245-7 • $46. Howev- fers several hundred drivers for powering er.00 Elektor US PO Box 180 Vernon.net Kits & Modules Toolbox gathers together data sheets from .). this Elektor is more than just your favorite electronics magazine.elektor. In addition to optical systems. etc. and for a selection of LED modules.30 www. hardware. Kits & Modules and much more! all the manufacturers. PCB and all components.90 Bestseller! See the light on Solid State Lighting DVD LED Toolbox This DVD-ROM contains carefully-sorted comprehensive technical documentation about and around LEDs. DVDs. This circuit light detectors. CDs. white papers and so on.com supply. CT 06066 USA Phone: 860-875-2199 Fax: 860-871-0411 E-mail: sales@elektor. tion of well-known technologies. along with ready-to-use modules builders.net & www.com/shop age and current limiting is part of the basic design guides. DMX controllers. It of- equipment of every electronics lab. I/O lines with a couple of I took apart a cheap miniTwo virtual CPUs at the bottom read their programs from the shared resistors. I used a cardcontroller first latches in the socket break-out board target register’s address on from SparkFun Electronics. Address.WorldMags. A Java program reads through the configuration and comments or uncomments sections of the remaining CORE code as required.com . voices. The host Movie program this project. A single register The SD driver putty is the circuit board and speakshared between CPUs syncs the movie frames to the music beats. based on Tomas Rokicki’s ers to the back of the LED work available for download through putty cog to map the sound chips to display board for a single audio/visual the Parallax Propeller Object the propeller shared memory bus. The command value is 2 for of the mini-speaker system. Number. Each chip Music CPU Movie CPU hardware and driver code I has a bank of 16 8-bit regisMusic used in two other projects. Each volume envelopes for all voice can be a tone or noise.circuitcellar. I modified it to follow the application sees four registers: Chip lines from the sound chips together FAT tables to the first file on the disk. and Comand hooked them directly to the input and you must reformat the card every mand. The compiler then reads the configuration to know which CORE commands to generate for the target engine.Journal-Plaza. The module. Value.net • www. This is a minor inconregister on the target chip. faces to the host controller The SD card interface in with a single 8-bit bus and this project is the same two control lines.) In lope generator.2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:46 AM Page 20 hardware with missing feaSpy Hunter. but the “ice-cream venience that allows the SD driver code code that talks to the sound chips is truck” sound goes nicely with the to fit nicely in a single cog. leaving plenty of low-resolution LED display. and many oth32-KB Shared tures like a frequencyers. Each chip generates RAM sweep function or separate three separate voices. quick and short. The details are The AY38910 chip inter2-KB Frame cache hidden under the putty. The driver sound quality. A little time you write a new data file for your “read” or 1 for “write” to the target RC networking would improve the project to read. The application sees the SD hardware time and space to extend the sound I used another virtual hardware June 2010 – Issue 239 Listing 1—These comments in the SPIN file configure the engine and its compiler automatically. The application sees The host controller can Sound hardware these additional services as directly control the frequenmore memory-mapped cy/volume of a voice over locations. I twisted all six audio output Exchange. ' CALL-STACK SIZE ' #define CALL_STACK_SIZE = 5 // Number of longs reserved for the call stack ' ' MULTIPLY AND DIVIDE ' #define MULTIPLY = NO // Include the generic multiply routine (auto if MULT=YES) ' #define DIVIDE = NO // Include the generic divide routine (auto if DIV or REM = YES) ' ' CORE COMMANDS ' #command coreGOTO = YES ' #command coreGOTOCOND = YES ' #command coreCALL = YES ' #command coreRETURN = YES ' #command coreSTOP = NO ' #command corePAUSE = YES ' #command coreSYNC = YES ' #command coreNATIVEMATH = YES ' #command coreMULT = NO ' #command coreDIV = NO ' #command coreREM = NO 20 CIRCUIT CELLAR® www. ters you twiddle to control program (Refer to my articles in Cirthe three voices and envecuit Cellar 205 and 209. hardware devices to virtual hardware registers within shared RAM. It doesn’t know time or configure an onLED hardware (or care) which functions board envelope generator to are in the hardware and modulate a voice’s volume 2-KB Frame which are synthesized in automatically. cache SD hardware software. Four Propeller COGs at the top of the figure map directly to the Propeller’s using the same bus.net & www. speaker system and glued RAM and manipulate the virtual hardware registers. the bus and then writes (or Figure 2—The Propeller’s 32-KB RAM acts like a traditional The four SPI signals tie reads) the register’s value address/data bus. Then it sends a “read” to the virtual hardware “command” register. you add your dialect-specific commands to the core SPIN code. however. Without application code to pull the strings. Applications need pointers and diverse addressing modes. Finally. but the memory is organized into 4-byte words. No actual memory addresses are shown. For example. libraries and RTOS kernel to provide the designer with the ability to customise their own firmware.Libraries for several USB classes FAT file system support. . The Propeller RISC opcodes. Application code tends to use data in more complicated ways.net & www. Application code tends to be much longer than driver code.Time to market can be reduced using the wide range of available development modules. Then your own assembly language compiles (2) into byte code for your custom CPU.2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:47 AM Page 21 Vinculum VNC2 ASM Source 2 Core compiler 1 Dialect compiler Core Spin 3 Dialect Spin Byte code Figure 3—Generating executable domain-specific language code is a three-part process.Multiple package size options including VNC1L pseudo compatible option. 21 CIRCUIT CELLAR® www.circuitcellar. the data has been read from card to memory. . the hardware is a mindless lump of lifeless limbs.WorldMags. I can create a processor with the complex addressing modes I want. Next. the command set includes a square-root function. but they aren’t very good at running applications. have no indirection at all. drivers. The Propeller cog address space is 2 KB. after all. provide cost effective solutions for the different applications.Royalty-free flexible ‘C’ language Integrated Development Environment including complier. A programmable systemon-chip dual USB 2. The Java preprocessor tool (1) generates the CPU code in SPIN for the Propeller. SPI Master and PWM.net .Handles USB host interfaces and data transfer functions using the in-built 16-bit enhanced MCU with 256 kbyte Flash and 16kbyte RAM. and Command (read or write). Figure 2 shows the various putty cogs mapped into the 32-KB shared RAM space.ftdichip. The application writes the file sector number and the destination memory address. SPI Slave.com June 2010 – Issue 239 as three registers in shared propeller memory: Sector Number. and the Propeller IDE is a rich graphical editor/compiler for the SPIN language. The RISC cogs are great for small.0 host/ slave controller. USB MADE EASY www. . PERFORMANCE. So why reinvent the wheel with a new virtual machine? The SPIN interpreter is a general-purpose engine—a wheel designed to work reasonably well for a large set of axles— yet it does not fit any one axle perfectly. CUSTOM CPUs Hardware is only part of the project. And my application code runs (virtually) out of the much larger byteaddressable. Destination Address. bit-banging hardware drivers. Pointers are simulated by writing addresses into later instructions.Journal-Plaza. What I would really like to do is pop the top off the Propeller chip and replace one or two of those fast RISC www. The two custom CPUs (discussed below) write to all the hardware registers. . The SPIN interpreter is programmed into the Propeller’s ROM. I don’t need square roots in my LED graphics language. When the command location goes to zero. That’s not much space when you are trying to code up the many pathways of an application to play chess. By modeling the CPU features I want in the cog putty. fast. A cog has only 512 addressable locations for code and data.Interfaces to UART. Note that a virtual machine for the Propeller is not a new idea. and there is no stack to support a highlevel application language. . First. The figure simply shows the individual data areas and how they are shared.com • Spin preprocessor cogs with a slower CPU that has the space and power I need to write applications. 32-KB RAM. Parallax designed its SPIN language interpreter to solve these very application limitations. the SPIN engine interprets your compiled program (3). FLEXIBILITY. just a piece of hardware in the memory space of the system. The putty approach allows me to do just that. FIFO. A CPU is. You configure the core engine features in the code comments. They communicate with each other through a single virtual register as shown. but I do need a Bresenham SPEED. you add your dialect-specific compiler code to the Java core compiler. . 2B ' VOICE 1 | 4R | 2B3 D+ | F# D sor. This CORE interthe disk in the background. Listing 1 if($day == 1) { shows part of the CORE configuracall OnTheFirstDay // on the 1st day there is an 8C+ pickup note tion with desired features turned call One } else { on and off. I use a Java program to com' VOICE 2 | 4R | 2R 2B3 | D+ Bment or uncomment sections of ' VOICE 3 | 4R | 2G2 4G 4A | 2D+ 2G the engine based on the configura' VOICE 4 | 4R | 1R | 1R ' VOICE * | 8X 8X | 8X 8X 8X 8X 8X 8X 8X 8X | 8X 8X 8X 8X 8X 8X 8X 8X tion file.net & www. I could code the lar 193). memory. so I wrote my own preproces' VOICE 0 | 8D4 D | 4D 8G G 4G 8F# G | A B C+ A.circuitcellar. In my 2006 article “Java Utility for conditional-jump.ing about the code to load constants. $x // Draw the next frame } return article. grated the tool into the assembler. do/while/if/else to any secondonto the end of the CORE. addressing modes as needed. multiply/divide. The SD driver new language and generates the byteSome commands are common to reads from the SD card in 2-KB cluscode interpreted by the CORE SPIN most computer languages. SPIN language. The for construct and the $ memory references are preprocessed by the BLEND tool available for all assembly languages. 0 // Draw first frame on new page LOADCLUSTER $cachePage. Movie engine uses 4 KB of memory comments to know what commands My CORE framework is a customizfor two disk clusters. Notice how the domain-specific language allows both music developer to select commands and and code to be written together in their natural forms. The added movie-specific commands are shown in all caps. One cluster conand addressing modes are available. source of the Java assembler is in the or dialect-specific commands. The SPIN compiler does // On the Nth day there is no 8C+ pickup note not include preprocessing direc' VOICE 5 | 8D4 D | 4D 8G G 4G 8F# G | A B C+ A. The assembler ects. A single cluster on the disk holds code. but it is really assembly language—one instruction per line. You can use And I’d like to write (and read) code in generation assembly program. and language THE MOVIE LANGUAGE The CORE interpreter is supported features to fit my particular set of projThe LED display is 48 × 32 pixels by a Java assembler. The assembler reads the comjumps and math operations. I’d like to pick and choose com. I’d like to pop the top off of This allows you to use for loops. This bler taking advantage of common preter fetches commands and decodes keeps both the LED display and the operand-parsing routines. and if statements in DRAWLINE algorithm without worrysquare-root opcode with a draw-line your new languages. The LED ments from the CORE configuration instance. or indirect operands. opcode. Conditional ters. You’ll find the CORE } engine in the project file for this 22 CIRCUIT CELLAR® www. Figure 3 shows the basic steps line algorithm which the SPIN interAssembly Programmers” (Circuit Celin the tool chain from creating and cuspreter does not have. pixel taking 192 bytes.x<$numFrames. $nextCluster // Start loading the next sector for($x=1.net • www. memory math from the developer.4. mands. June 2010 – Issue 239 // $nextCluster = next cluster to load // $numFrames = number of frames in current cluster ShowCluster: call FlipPages // Swap cache and active pages WAITONTICK // Wait for the music trigger RENDERFRAME $renderPage. are found in most programs.WorldMags. Notice how RENDERFRAME is called first with a constant and later with a memory reference. The full them into general “CORE” commands disk driver busy. and Commands take a cluster number the code to fetch operands with several addressing modes. This allows In short. able SPIN engine that serves as the tains the frames currently being You can easily add your own dialect base functionality of a specific landrawn and one cluster is loaded from specific commands to the Java assemguage interpreter. I presented a Java tool that tomizing your own engine to compiling line algorithm as a subroutine in the allows you to add third-generation lanyour own custom language. but I’d like lines to be guage flow-control features like Dialect specific commands are added as fast as other language commands.$x=$x+1) { // Loop over the remaining frames WAITONTICK // Wait for the music trigger RENDERFRAME $renderPage. Parameters are resolved automatically by the CORE engine. The The LED Movie language hides the CORE includes general commands like project file for this article.Journal-Plaza.2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:47 AM Page 22 Listing 2—It may look like a strange new language syntax. for 10 complete display frames. Listing 3—Music is best described in notes and measures while program flow is best Comments in the code allow the described with IF/ELSE blocks. in your specific commands. I intethe CORE’s operand fetching routines the vernacular of the program’s domain. That’s what the domain-specific mapped into memory with one bit per reads a text file of commands in the language (DSL) movement is all about. you to focus on the details of the the SPIN interpreter and replace the while loops.B 8R | // 8C+ tives.com . addressing modes. 23 CIRCUIT CELLAR® www. | www. In this case.com/magazine/221. PROJECT FILES To download the code. The strategy is the ultimate in refactoring. writing code for the Propeller chip. The RENDERFRAME memCluster. In the computer applications industry. I made a list of the days from the song and the number of frames for each day. I played trumpet in college band.sureelectronics. and More by John Peterson Circuit Cellar 221.com • movie at www. The code first swaps the active and cache pages. and the sound language includes commands to play notes by number on a particular voice (0 to 5). the Circuit Cellar editorial staff highly recommends the following content: — A Dynamic Tile Display Board Layout. You can also duplicate frames and flip through the movie pages to see how it flows.html June 2010 – Issue 239 (either 0 or 1) and a frame number (0 to 9). informed engineers and programmers don’t just survive. The CORE SPIN and Java compiler in this project is a great starting point for creating your own customized interpreters on the propeller. Tiles. Display Go to: www. and paste pixel areas between frames. Topics: Animation.2105018_Cantrell_Chris Post FE for PP_Layout 1 5/12/2010 9:47 AM Page 23 THE SOUND LANGUAGE The sound engine maintains a table of note frequencies. Tray Go to: www. the 8× means the trigger happens on an eighth note interval.com/magazine/206. go to ftp://ftp. Programming. but it may not suit all of your project needs. He is a senior software engineer at Avocent in Huntsville. On the next music tick. The “8D4” means “eighth note D in octave 4. I found that reinventing the wheel can be practical and fun. The code for the GUI is in the project file. the for loop continues drawing the frames from the active page to the music beat while the cache page continues to load in the background. The WAITONTICK command waits for the music engine to change a shared memory location. For more need-to-know information about topics covered in Chris Cantrell’s Issue 239 article.net .circuitcellar.youtube. 2007 Dale built a character-based serial LCD controller. Topics: Graphics. The assembler for the sound language includes a third-generation “structure” parser to read a sheet-music-like text notation for music and translate it to note events in the code. Real-Time Animation. and evangelizing Java. REFACTORING My entire family enjoyed making the movie for this project. The “12 Days of Christmas” song is particularly patterned (my daughter calls it the “headache song”). The voice * controls the shared memory trigger that synchronizes the movie frames. I typed in the music from a book of piano carols. but to make this process as fast as possible. The GUI allows you to copy. the engine starts drawing the first frame and begins loading the next cluster into the cache page. and note-off events is tedious. I enjoyed exploring domain-specific languages with this Propeller project.net) holds an MS in Electrical Engineering.circuitcellar.net NEED-TO-KNOW INFO Knowledge is power. Controller. and I wish traditional music would use labels and GOTOs and subroutine calls. The tool formats the pixel data in binary format and stores it on the SD card for play in the project. It is best described by a permutation algorithm.circuitcellar. The system features a tray and tiles based on 8 × 8 LED displays. 2008 John designed an expandable platform for light and animation. and more.net & www. animated puzzles.html — PIC-an-LCD by Dale Wheat Circuit Cellar 206. frame draws the selected picture on the LED display. SOURCES Propeller chip Parallax. You can use it to create modular animated signs. Then the kids divided up the days and used the GUI to make the movie segments.circuitcellar.” The “4. Programmers are already used to factoring out common code into subroutines. The SPIN interpreter is a great general-purpose wheel. Listing 2 shows a snippet of code from the movie engine that draws frames one by one to the beat of the music. His many hobbies include teaching scuba diving. cut. You can watch the entire www. LED. pause. But programming music as a sequence of note-on.com/ pub/Circuit_Cellar/2010/239.Journal-Plaza. Finally. Photo 1a shows the running project with the last frame of the movie—the partridge in a pear tree. The LOADCLUSTER memCluster. Inc. Music is more naturally described in traditional eighth notes and rests. And it does teach you a lot about how wheels work! I Chris Cantrell (ccantrell@knology. I created a specific command. This command could be coded as an IF/GOTO check using CORE commands. Alabama. I made a simple Java pixel-plotter to create movie frames.B” means a “dotted quarter note B” played in the current octave. Listing 3 shows how music and program flow can live side by side in a custom language.com/watch?v=WiH14WjoCHw.WorldMags.com DE-DP016 LED Sure Electronics Co. The controller chip is programmed in C language. cardCluster command starts the card driver loading data from the SD card address cardCluster into one of the two memory areas. | www. DSL takes refactoring a step further allowing you to pull common subroutines into first class language features. The individual voices 0 through 5 are numbered on separate lines of the structure. Listing 3 shows a snippet of the “12 Days of Christmas” music in the text notation.parallax. they thrive and excel. Each line represents a different current that is consumed by each node. or fewer nodes on Figure 1—Network power consumption graph. which is the most that the CAN transceivers can handle.2105014_Siegel_Layout 1 5/12/2010 10:12 AM Page 24 INTELLIGENT ENERGY SOLUTIONS Home Automation for an Energy-Efficient House (Part 2) Embedded CANOpen Node Hardware & Software The first part of this series introduced a home automation system an for energy-efficient house. These will cause a lot of voltage drop if you have numerous nodes powered through the same pair of wires over a long distance.net & www. I introduced my energy-efficient home that’s located in Pueblo.Journal-Plaza. It’s also assumed is that all the nodes are spaced equally along the length of the network.circuitcellar. Colorado. This article covers the embedded hardware and software for the nodes. In essence. You can use similar parts and design techniques to automate the building of your choice. which is shown on the vertical axis. I also covered the control needs for it to be energyefficient and the approach I chose to implement control. I n the first part of this article series. the network remains in operation as long as the intersection of network length and number of nodes remains below that line. at most 39 nodes can be June 2010 – Issue 239 NODE POWER SUPPLY 24 The CAT-5 cable I use for the CAN bus network is perfect for the signal wires with its twisted-pair setup.com IE . by Stefan Siegel (USA) a longer network. The limiting criterion here was to keep the common mode voltage on the bus below 7 V. The assumption is that all nodes draw the same current. CIRCUIT CELLAR® www. This can be done by having more nodes on a shorter network. for example. The graph in Figure 1 illustrates that effect. but it is less than desirable for supplying power to the nodes due to the relatively thin-gauge (24 AWG) wires.WorldMags. as you would expect. the home automation system consists of a server and about 80 embedded microcontroller-based automation nodes connected by a controller area network (CAN) bus running a CANOpen software stack. You can operate the bus as long as you stay below the line of the assumed node current. It can be seen.net • www. I’ll describe the nodes’ embedded hardware and firmware. In this installment. that for a 20-mA current draw per node. For a given node current. b—Here the module has a switch cover plate (attached to the switches using double-sided tape). interface to PC Table 1—This is an overview of the different CANOpen node hardware and firmware. there better b) IE www. This prompted me to use a relatively high bus voltage of 24 V and to implement efficient step-down DC-DC converters in each node to minimize power consumption. Also. DeviceNet uses the same CAN physical layer that is described here. but also enable me to use a small power supply and enjoy a low electricity bill. powered along a bus length of 200 m (about 600′). At about 240-mW idle power consumption per node.” While using a different software protocol. Given how much it saves in heating and cooling cost. using either relays or open-collector outputs Power supply for CAN bus. c) CIRCUIT CELLAR® www. I’d say that’s well worth the investment in electric power. c— This is the same module with a stainless steel wall cover plate. one to three buttons Push button + daughter board 4 analog/4 digital Inputs Multi I/O Single gang wall box Interface for door or window contacts. you have a few options: either use an additional pair of the four CAT-5 pairs of wires to power some of the nodes or inject power somewhere along the length of the bus to reduce voltage drop. I used the latter technique on the first floor CAN bus when I ran into problems. If you are planning to hand-solder tens to hundreds of home automation nodes during weekends and evenings.WorldMags. Since the system is on 24/7/365 and has many nodes by design. NODE HARDWARE Although I love tinkering with electronic circuits.net 25 . Add less than twice that for the Linux server (with an efficient Intel Atom Motherboard). power consumption can add up. I had to limit the circuit complexity associated with this project.net & www. 0. All modules will show a less than linear increase in power consumption if they draw more power to support LEDs or other consumers. If this is exceeded. temperature sensors Push button + daughter board 4 analog/4 digital inputs Thermostat Single gang wall box Thermo/hygrostat.circuitcellar. with light sensor and floor/ceiling temperature sensing Push button + daughter board shutter Shutter Single gang wall box Operates a sliding shutter with limit switch/encoder and window contact Push button + daughter board keypad Keypad Single gang wall box Interfaces a numeric keypad and electric door strike for entry control DIN Rail 8 analog inputs/2 outputs 8 Analog inputs DIN Rail mounted Sensor Interface. a—This is the user side showing all six switches along with all LEDs installed.Journal-Plaza. an additional 50 mA are consumed (for 500 ms). An excellent information source on power management and wiring of distributed CAN systems is the ODVA “DeviceNet Planning and Installation Manual. I am using only latching-type bipolar relays that draw current when a change in state happens. all of my 80 nodes use less than 20 W in total. The basic switch module with the Run LED on consumes 10 mA at 24-V bus voltage. since the DC-DC converter becomes more efficient at higher power draw. One conclusion can be drawn from Figure 1 right away: each node can draw only a few milliamps of current before the power supply becomes an issue. which was easy to do since I had some nodes that needed a dedicated thicker power supply line anyway to power valve actuators. a) When one of the relays is actuated temporarily. and the total system consumes about as much as a conventional 60-W light bulb. The two closely spaced holes at the top and bottom need to be joined into an oblong hole to allow for the horizontal alignment of the board on the wall.com • June 2010 – Issue 239 Photo 1—Take a look at the push button switch module. however.2105014_Siegel_Layout 1 5/12/2010 10:13 AM Page 25 Hardware Push button + relay daughter board Software Switch Form factor Single gang wall box Function Light switch actuating one to two lights. All of these measures do not just keep the bus voltage drop small.to 10-V control for actuators DIN Rail 8 relays 8 Relays DIN Rail mounted Master module Master DIN Rail mounted Actuator on-fff control. and humidity sensor are only populated when the board is used as a thermostat. To achieve this. easy implementation. Between different combinations of this Pushbutton main board and the daughter boards. and DC-DC step-down converter. and interface to the server/bus power supply. For the wall-mounted modules. CIRCUIT CELLAR® www. I achieved five different functions. light switch rough-in box. b—The user side has the CANOpen Run and Status LEDs. I designed two basic form factors of the nodes: one that fits into a standard U.S. The two pin headers J1 and J2 allow attachment of a daughter board for added functionality. Also. As Table 1 shows.Journal-Plaza. control (open collector or relay outputs). I tried to keep the number of different circuit boards as small as possible. I’ll cover the hardware and firmware of the Pushbutton main board with the Relay daughter board.net & www. Descriptions of the other modules are available on my website.WorldMags. CAN bus interface. NODE SOFTWARE DESIGN I selected the CAN bus as the bus medium for its low cost.com IE . If no user interface is required. there are three different DIN rail modules that provide sensing (analog inputs).net • www. which are detailed in Table 1. The thermistor. there is only one design called Pushbutton that can be customized by selective population of the board or by adding different daughter boards. These can be populated as needed. photocell. since the cost at the prototype level scales with the number of different boards more than with how many of a given design you are having made. and by using different firmware. The latter is used for installation in a steel enclosure typically used for circuit breakers. and another one that can be mounted to a DIN rail. and ability to connect many a) June 2010 – Issue 239 b) 26 Figure 2a—The wall-facing side of the PCB features the microcontroller. In the remainder of this article.circuitcellar. the switches and LEDs may be omitted.2105014_Siegel_Layout 1 5/12/2010 10:13 AM Page 26 be a relatively finite amount of parts in each. and it has the advantage that there are nice enclosures available that snap onto this DIN rail and house the PCB (see my website for details). as well as up to six pushbutton switches and three LEDs. However. and implement basic analog and digital I/O functionality. If you use this module to interface analog or digital sources This is the main building block of the home automation system.Journal-Plaza.com • CIRCUIT CELLAR® www. there is no bus master. a LGPL-licensed CANOpen stack is available from SourceForge. you can write the entire embedded software with no cash investment whatsoever. IE www. Instead.net & www. Refer to Table 1 for an overview. Following this tutorial and building a few nodes on a breadboard was what initially gave me the confidence that this hardware and software setup was a feasible infrastructure for a home automation system. Thus. The actual switch plate in Photo 1 is a 0.net June 2010 – Issue 239 PUSHBUTTON SWITCH MODULE 27 . you can see the status LEDs through the plate—and yes. More importantly. you’d have to shell out a small fortune for the source code of an implementation of this protocol to run on a small embedded CPU—or spend significant effort to write your own. I picked CANOpen as the network protocol. For the CAN bus. which can be custom-engraved if desired.WorldMags. But I didn’t feel up to this task. and changing the software. this board is used to implement the functionality of a network-connected light switch.circuitcellar. Currently. which you can purchase for well under $100. but it is set up for the Microchip Technology PIC18Fxx8 family of controllers. and see them talk CANOpen over the CAN Bus. pick any color you like. These also happen to be among the smallest and cheapest CPUs that have the resources in terms of flash memory and RAM to run a CANOpen stack. Historically. which is somewhat like reinventing the wheel (since there are nice protocols available) and possibly winding up with a flat tire in the process. but rather each node can transmit on its own schedule. Beyond the stack. program them. The most straightforward choice seems to be to develop your own message transmission standard. adding daughter boards. To program the controllers. My goal here was to design one circuit board that could be customized for different functions by selectively populating the board. Microchip supplies its C compiler free of charge (with some optimization feature limitations). You can potentially recompile the C source code for any embedded CPU.125″-thick (3-mm) piece of acrylic.2105014_Siegel_Layout 1 5/12/2010 10:13 AM Page 27 network nodes with just one twisted pair of wires terminated at each end. implement a thermostat. the distribution comes with an excellent tutorial that allows you to plug together a couple of nodes on a breadboard. interface a keypad to the CANOpen network. which has the advantage of being nonproprietary and reasonably well documented. In terms of form factor. you can choose to use a number of different software protocols to run on the bus. the board is a drop-in replacement for a decora-style light switch that can be used with any decora trim plate from your favorite hardware store. thanks to the hard work of Janez Paternoster. all you need to buy is an in-circuit programmer like the ICD 2. If you choose a translucent color. 53_Layout 1 5/12/2010 8:42 AM Page 1 !NEWERA. INUXAND!NDROID s -EDICAL s . design engineers. suppliers. ESC Chicago 2010 Tracks Include: s $ESIGNINGFOR%MBEDDED. ESC is the ideal conference for the embedded design community to learn. and recognize excellence. visionary keynotes. and hundreds of essential training classes.ETWORKINGAND#ONNECTIVITY s /PEN3OURCE3OFTWARE s 0ROJECT-ANAGEMENT s 0ROJECT-ANAGEMENT s 2EAL 4IME3YSTEM$EVELOPMENT s 2OBOTICS. collaborate.ANEW . and media from across the globe. With cutting edge product demonstrations.EWTRACKS.EWFOCUS ESC ESC Chicago brings together systems architects.EWCOURSES. analysts. -OTOR#ONTROL. AND-ORE)NDUSTRIAL#HANGE-AKERS s 3AFETYAND3ECURITY s 3OFTWARE$EBUGGING4ECHNIQUES 3TARTYOUROWNPERSONALDEVELOPMENTAT%3#9OU CANTAFFORDTOMISSIT Chicago Donald E.net & www. Rosemont. Stevens Convention Center. IL Conference: June 7-9. www. 2010 Expo: June 8-9.WorldMags.net .com/chicago ESC is Co-locating with the Sensor Expo.embedded. 2010 Register Today.Journal-Plaza. ESC attendees will have access to the Sensors expo floor. www. Journal-Plaza.net .qxp 1/7/2009 3:07 PM Page 1 www.net & www.41.WorldMags. In terms of functionality.com IE . each switch is doubled to provide mechanical support for the switch plate. two bottom) will provide the functionality of a double switch. but it has the same standard pin out as the 0. Four (two top. I have successfully recompiled the source code without any changes and it runs on these newer chips without problems. I could have used either a PIC18F248 or a PIC18F258. The National Semiconductor Corp.2105014_Siegel_Layout 1 5/12/2010 12:28 PM Page 30 The DC-DC step-down power supply is more or less straight from the application note AN-1445 for the LM5009 demonstration board.and software-compatible replacements are available as PIC18F2480 and PIC18F2580. & INTERFACE 30 USER-SIDE COMPONENTS LEDs. The bus voltage of nominally 24 V is stepped down in the DC-DC converter (left bottom portion of the circuit) to 5 V/150 mA (max). you can use a blank wall plate to cover it after installation. The CAN bus lines are connected to the CAN driver chip (a Microchip Technology MCP2551 or equivalent).net & www. It can be selectively populated as cable enables you to program the PIC with any needed. Photo 1a is the user side showing all six switches along with all the installed LEDs. but pin. By drilling two holes through the blank wall cover plate for the status LEDs. Figure 2 shows the circuit’s essential components. The former is more affordable.Journal-Plaza.net • www. The two closely spaced holes at the top and bottom need to be joined into an oblong hole to allow vertical alignment of the board on the wall. standard PIC programmer that supports ICSP. the latter has twice the amount of memory (RAM and flash memory). The CAN bus connector is an MTA-type polarized connector and carries the bus voltage of 24-V DC as well as the two CAN bus signal lines. you can still see if the module is online. but will only allow you to implement the functionality of the basic switch described here. and all six a triple switch. and the cover plate provides easy access for maintenance. As for the module’s CPU.1″ pin headers on the switch board. so there is a lot of room for increasing the bus voltage if voltage drop becomes an issue. and their resistors are on the PCB side facing away from the wall when installed. Photo 1b shows the same module with the switch cover plate (attached to the switches using double-sided tape). LM5009 switching regulator tolerates up to 95-V input voltage. June 2010 – Issue 239 CPU. The thermostat-specific components are not populated if you are building a switch.WorldMags. Microchip has phased out the PIC18F248 and PIC18F258. a short patch relay outputs and four open-collector outputs. Thus. Simply use female 0. Photo 2—The wall side of the PCB. POWER. The female pin headers J1 and J2 connect to the daughter board.) The ICSP connector is a miniature surface mount type. you can secure the daughter boards with a pair of #4-40 screws and a spacer to the switch PCB. as these provide visual information on the status of the node to the user. The left portion of the board holds the DC-DC circuitry. The J1 and J2 connectors allow the attachment of daughter boards to add more functionality. The CAN bus connector is at the bottom right. You’ll want to populate the run and error LEDs and their resistors. R_MCP can be increased to 100 kilohms if the bus is operated at 125 KBps and will reduce EMI by providing a slower slew rate of the CAN bus signals. switches. that do not require any user input. (Refer to the MCP2551 driver chip’s datasheet for details. you can get away with a minimum of three switches (like left top and bottom. The remaining switches and LEDs are optional.circuitcellar. and the male counter parts on the daughter boards. for either 2-A or 8-A currentswitching capabilities. CIRCUIT CELLAR® www. While they are pin-compatible. and it’s required if you want to implement more complex software. Photo 1 shows push button switch modules. Photo 1c shows the same module with a stainless steel wall cover plate. which is sufficient to power the switch and any daughter boards. For added mechanical strength. If you use this board for only a single switch. center right). Two different relays fit into the PCB footprint. The ICSP connector is at the top right.1″ version used by the Microchip ICD Figure 3—Relay daughter board schematic. The daughter board provides up to two 2 programmer and clones. Journal-Plaza. ODE_EEPROM. They will maintain either on or off state without a coil current once they have been toggled which takes only about 500 ms. ATTR_RW|ATTR_ROM.PowerOnCounter). For the relays. The ULN2803 is an eight-channel open-collector driver. #endif OD_ENTRY(0x2106. 0x05. Refer to Photos 3a-3c if you intend to use that particular CIRCUIT CELLAR® www. OD_ENTRY(0x2104.net June 2010 – Issue 239 // Mapped RPDO Values OD_ENTRY(0x2110. The female pin headers J1 and J2 connect to the daughterboard. /*0x2110 Sub6*/ UNSIGNED8 OC_3_State = 0. /*0x2101*/ ROM UNSIGNED8 ODE_CANnodeID = ODD_CANnodeID. ODE_CANbitRate). ATTR_RW|ATTR_ROM. /*0x2110 Sub2*/ UNSIGNED8 SW1_State = 0. ATTR_RW|ATTR_ROM. OD_ENTRY(0x2001.2105014_Siegel_Layout 1 5/12/2010 12:27 PM Page 31 Listing 1—Object dictionary entry changes are made in od. //this entry can be replaced with DIP switches on printed board #if CO_NO_SYNC > 0 /*0x2103*/ extern volatile unsigned int CO_SYNCcounter. /*0x2100*/ extern unsigned char CO_ErrorStatusBits[ERROR_NO_OF_BYTES]. 0x00. SW2_State).WorldMags. ATTR_RW|ATTR_ROM. Each channel can drive up to 500 mA in current. and you can operate them in parallel if needed. 0x00. 0x03. ATTR_RW. /*0x2110 Sub5*/ UNSIGNED8 OC_1_State = 0. 0x00. ATTR_RO. OD_ENTRY(0x2101.net & www. 0x00. which also has integrated diodes to prevent voltage spikes induced by the relay’s coils. OC_1_State). At the top are variable declarations. 3 rom UNSIGNED8 SwitchCount = 3. At the bottom are entries in the object dictionary. 0x00. //variable is incremented after SYNC message /*0x2104*/ extern volatile unsigned int CO_SYNCtime. OC_2_State). 0x00.. 0x00. 0x00. ATTR_RW. OC_0_State). /***** Manufacturer specific **************************************************/ OD_ENTRY(0x2000. ATTR_RW|ATTR_ROM. OD_ENTRY(0x2110. OD_ENTRY(0x2110. range is 0 . ATTR_RO|ATTR_ROM. ATTR_RW. ATTR_RW. OD_ENTRY(0x2110. OD_ENTRY(0x2102. OD_ENTRY(0x2110. 0x01. after SYNC message it is set to 0 #endif /*0x2110*/ ROM UNSIGNED8 nRPDOs = 7. these are bi-stable relays in order to minimize power consumption on the bus. #if CO_NO_SYNC > 0 OD_ENTRY(0x2103. /*0x2110 Sub3*/ UNSIGNED8 SW2_State = 0. 0x00. needs to be 1 . ATTR_RW. SW0_State). /******* Index 0x2002 ********************************/ //How many Relais are installed and in use. Photo 2 shows the wall side of the PCB. OD_ENTRY(0x2002. In either case. OD_ENTRY(0x2110. /*0x2110 Sub6*/ UNSIGNED8 OC_2_State = 0. At the top right is the ICSP connector. }. //variable is incremented every 1ms. ODE_CANnodeID). RelaisCount). The CAN bus connector is at the bottom right. /*0x2110 Sub1*/ UNSIGNED8 SW0_State = 0.c. OD_ENTRY(0x2110. 31 .e. OD_ENTRY(0x2100. OD_ENTRY(0x2110. The layout has one pull-up resistor missing. /*0x2110 Sub4*/ UNSIGNED8 OC_0_State = 0. 0x04. 0x00. nRPDOs). SW1_State). 0x02. /******* Index 0x2001 ********************************/ //How many Switches are installed and in use. ATTR_RW. //this entry can be replaced with DIP switches on printed board /*0x2102*/ ROM UNSIGNED8 ODE_CANbitRate = ODD_CANbitRate. Relais_Time). 0x07.circuitcellar. ATTR_RO. RELAY DAUGHTER BOARD This is an add-on module to the basic Switch module that provides two relays and four open-collector outputs. OC_3_State).. 2 rom UNSIGNED8 RelaisCount = 2. ATTR_RW. there are two options: you can use either the cheaper relays with less of a current rating or the more expensive ones with greater current capabilities depending on what IE www. 0x06. CO_SYNCtime). Figure 3 and Photos 3a–3c show the switch daughter board... /***** Manufacturer specific variables ****************************************/ /******* Index 0x2000 ********************************/ //how long is the LED and Relais activated after change of state in ms // i. CO_SYNCcounter).com • you intend to switch. CO_ErrorStatusBits). 500 = 500ms rom UNSIGNED16 Relais_Time = 500. The left portion of the board holds the DC-DC circuitry. ATTR_RW. ATTR_RO. SwitchCount). Journal-Plaza.circuitcellar.net & www.WorldMags. b—This is a close-up shot from above. 32 CIRCUIT CELLAR® www. c—Note the two #4-40 screws and the 0.5” nylon spacer used for attaching the daughter board to the pushbutton board.net • www.2105014_Siegel_Layout 1 5/12/2010 12:27 PM Page 32 a) b) c) June 2010 – Issue 239 Photo 3a—The relay daughter board is attached to the main pushbutton switch module.com IE . The switch status.Journal-Plaza. OPERATIONAL EXPERIENCE With almost two years of operational experience. or three switches installed. The first step in writing the firmware is adding the required Object Dictionary entries to the OD. as well as the activation time of the relays coils. it is time to write the actual code contained in user. If any PDO is received.c file. For the switch module. the OD.com • entire file is available with the rest of the code on the Circuit Cellar FTP site. Beyond the variables SwitchCount and RelaisCount. The switches are sorted top to bottom. after defining the Object Dictionary and the PDO mapping. If all you need is the relays. The Object Dictionary values can be adjusted later through the CAN bus by using service data objects (SDOs) after the firmware has been programmed into flash memory. Next. I use only three of these hooks: at boot time. The CANOpen implementation of Janez Paternoster provides hooks for code to be executed at boot time. as well as the overall CANOpen parameters. Each POD is 1 byte in size.h file shows seven (i.c file. at network reset. what is it like to live with this system on a day-to-day basis? From the perspective of homeowners living in the house. On the RAM side.. the respective switch LED is turned on or off. including the mapping of the Object Dictionary items to Process Data Objects (or PDOs). if you turn on all compiler optimizations. If you are using the free MCC18 compiler with some of these optimizations disabled. there is only one firmware version that covers the hardware with one.5″ nylon spacer used for attaching the daughter board to the pushbutton board. The IE www.2105014_Siegel_Layout 1 5/12/2010 12:25 PM Page 33 FIRMWARE The firmware for this project is based on the CANOpen stack implementation by Janez Paternoster.e. It provides a straightforward API that can be customized to provide the functionality required. there is no pinch because only 686 bytes of RAM are used. The first portion includes the variable declarations found in about the middle of the original file. however. Depending on the number of switches and relays present. and 255 the on state for any of the variables. can be either transmit (when a user hits a button) or receive (when you set the status of the switch over the network). Finally. where the Open Collector states are clearly receive PDOs (set over the network for example from the server). and the relay actuated. the appropriate relay is turned on or off and the respective PDO is sent over the network to inform any other node interested in the new status of the switch. Note the two #4-40 screws and the 0. the status of the three switches and four open-collector outputs is added to the object dictionary. The second portion includes the actual Object Dictionary entries at the end of the file. Zero is the off state.998 of 8. Listing 1 shows the added entries there. You access the declared variables by their names from the main code.192 bytes). Thus. the relays on the daughter board are turned off and every 1 ms I check if the user has pressed a button.WorldMags.h is edited where the overall configuration of the CANOpen parameters takes place.c. two. and relay 2 is associated with switch 2. CIRCUIT CELLAR® www. you will have to use a PIC18F258 to fit the code in the available flash memory.circuitcellar. The code uses almost all of the PIC18F248’s flash memory (7. you can omit the additional open-collector connector as well as the resistor.net & www. as well as the daughter board with zero (or no daughter board) to two relays. and so on. Note that relay 1 is always associated with switch 1.net June 2010 – Issue 239 open-collector channel. CANOpen distinguishes between receive and transmit PDOs. 3 + 4) receive PDOs but only three transmit PDOs. the file OD. For the switch. Listing 2 shows pseudocode for the user. the smallest amount of data that can be transmitted with a CAN message. 33 . at shutdown. the status of the three switches as well as the four open-collector outputs is mapped to PDOs. activate coil to turn off Send PDO 0 message to inform every node who cares Set the LEDs ENDIF // if any switch touched IF PDO 0 has been received toggle status and relay on or off as appropriate set the LEDs ENDIF// PDO 0 received Start the timer for debounce. count down timer Decrement timer by 1 IF Timer ==0 turn off all relays quit debounce mode ENDIF // timer expired ENDELSE// timer counting down } 34 the entire family agrees that this is the most comfortable climate-control system we have ever lived with.circuitcellar.Journal-Plaza.USER INITIALIZATION OF NODE Function is called after start of program. I also managed to drill a few holes into my own knee by not limiting queue sizes and other variables to prevent them from filling up PC memory over time. *******************************************************************************/ User_Process1msIsr: IF we are not in debounce mode //map RPDOs onto LEDS and check switches // Three different situations depending on the number of switches SWITCH(SwitchCount) case 1: //This is the config with 1 Switch and 0 or 1 Relais IF low edge on any of the three TouchSwitches toggle status and relay on or off as appropriate If Switch Status is OFF Toggle Status to ON IF Relay 1 exists.net • www. I had a hard time getting the server software to run stably initially. Here is longer and time consuming code. With proper error-handling. It is deterministic and has priority over mainline functions. CIRCUIT CELLAR® www. Relais and LED End CASE 1 CASE 2: // Config with two switches and 0 to 2 Relais … similar to case one with different mapping. It is non blocking function.1 ms USER TIMER FUNCTION Function is executed every 1 ms.com IE .c pseudocode /******************************************************************************* User_Init .USER PROCESS MAINLINE This function is cyclically called from main(). From the perspective of a homeowner who has to pay the bills. see actual code ENDIF// not in de-bounce mode June 2010 – Issue 239 // this is what we do while debounce is active ELSE //we are in debounce mode. It is asynchronous.2105014_Siegel_Layout 1 5/12/2010 12:25 PM Page 34 Listing 2—Pushbutton switch user. the house has a fraction of the heating and cooling cost of any similar size house in the neighborhood. *******************************************************************************/ User_Init: Toggle all relays to OFF /******************************************************************************* User_ProcessMain . *******************************************************************************/ User_ProcessMain: If New Open Collector PDO has been received: Set respective Open Collector output /******************************************************************************* User_Process1msIsr . particularly in terms of no-draft heating and cooling as well as noise. these issues were resolved. From the perspective of the engineer who designed the system. These problems were tracked to interface issues between the CAN bus hardware driver and the CANOpen message router.WorldMags. activate coil to turn on ELSE Toggle Status to OFF IF Relay 1 exists. where the driver would crash the computer if I sent a message after an error had occurred on the bus.net & www. see actual code CASE 3: // Config with three switches and 0 to 2 Relais … similar to case one with different mapping. install the CAN bus interface. http://apps1. set up a server.com NEED-TO-KNOW INFO Knowledge is power.gridconnect. CANopenNode Janez Paternoster | http://sourceforge.htm — Multifunctional Home Control System by Jack Benjamin and Michael Benjamin Circuit Cellar 187. Microchip Technology. www.circuitcellar. Department of Energy.pdf. as well as a software download for this system. ODVA. and program them following the steps outlined in Janez’s tutorial. A.com/labview LM5009 Switching regulator National Semiconductor Corp. | www. Etschberger.com • CIRCUIT CELLAR® www. PROJECT FILES To download the code.national. There are other uses beyond home automation for the nodes.com/magazine/187toc. Chips and Applications. The system is truly scalable from two nodes without a server.ni. Bootloading Go to: www. 2002. Controller Area Network: Basics.WorldMags.S. Ayre. the system I described here is an industrial-strength automation network on a budget. Embedded Networking with CAN and CANOpen. Air Force Academy in Colorado Springs. they thrive and excel.siegels. | www. 2006. XML. though. Direct Wire. Inc.pdf.com/magazine/161toc. and keep adding nodes as needed. ww1.microchip.2105014_Siegel_Layout 1 5/12/2010 12:22 PM Page 35 An important learning experience for me had to do with the difference between writing code that runs for minutes to hours (which I have been doing in my professional life for years) and code that performs unsupervised flawlessly for months and years. Topics: Home Control. you won’t even need a PC CAN bus interface to see how they work together. IE www. go to ftp://ftp. You can use the same components to automate yours. Olaf describes CANopen and options for implementing the network. U. Stefan Siegel (stefan@siegels. Inc. all the way up to much bigger systems. 2003 MicroMessaging is the perfect bridge between any serial bus and CANopen.net June 2010 – Issue 239 BUILD YOUR OWN 35 .Journal-Plaza.odva. Your first step to get started (this is how I did it.” PUB00027R1. Topics: CANopen. “PIC18FXX8 Data Sheet 28/40-Pin High-Performance.us) holds a PhD in Aerospace Engineering with a minor in Electrical Engineering. anyway) would be to download the CANOpenNode software from SourceForge. Relay.circuitcellar. Protocols. build at least two nodes like the ones I described. informed engineers and programmers don’t just survive.gov/buildings/energyplus/. which is a network of microcontrollers that interact with each other. Pfeiffer.com/pub/ Circuit_Cellar/2010/239.com I’ve shown you the setup I use to automate my house.microchip.circuitcellar. 2003.S. are posted at www.us/SH_Automation. was how stable the software on the embedded nodes runs once debugged—and even more so. I Author’s Note: More details. he performs fluid dynamics and alternative energy research at the U. Just adjust the number of individual CAN bus networks and nodes as needed.” DS41159E. Stefan developed his home automation system in his spare time. At its root. it all has worked out well.energy.net/projects/canopennode/ MPLAB IDE and PIC18F248SO Microcontroller Microchip Technology. Enhanced Flash Microcontrollers with CAN Module. While we took what I would call in retrospect quite a gamble in betting on this untested system to perform. Energy Plus Thermal Modeling Software. Keydel. MicroMessaging. which now truly has been up and running for the entire time we have lived in the house without any shutdown. 2001. “DeviceNet Planning and Installation Manual. how robust the CAN bus is against all sort of hard-and software abuse.com LabVIEW National Instruments | www. For example.htm RESOURCES K. Optocoupler. Scheduler Go to: www. utilities. I use one of the DIN rail modules at work on a rotating propeller rig. O. acquiring data from strain gauges and transmitting it through a slip ring to a PC CAN interface.org/portals/0/library/Publications _Numbered/PUB00027R1_Cable_Guide_Print_Copy.eere. and C. It is also nice to have a system where you can add features and change control behavior easily. Colorado. You can build nodes for little money and program them for free to meet your needs. SOURCES Peak PCI bus CAN adapter Grid Connect. The main surprise for me. For more need-to-know information about topics covered in Stefan Siegel’s Issue 239 article. the Circuit Cellar editorial staff highly recommends the following content: — Implementing CANOpen by Olaf Pfeiffer Circuit Cellar 161. | www. If you set all the configuration parameters when you program the flash of each node. RTC Books.net & www. None of the initial issues in getting the system to work were related to the bus itself. 2006 Ready to build a home control system? This custom design controls alarms. IXXAT Press. and more. through the setup described here. shades. During the day.circuitcellar.com/downloads/en/ DeviceDoc/41159e. In the computer applications industry.html. Then. When I finished this product for my client. I ended up designing a low-cost solution. and my high-gain probe amp to stimulate and capture OAEs for myself.WorldMags.F EATURE 2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 36 ARTICLE by Chris Paiano (USA) OAE Probe Amp and Intercom (Part 2) Otoacoustic Experiments You are familiar with the process of designing and building an OAE probe amp and intercom system. Now. I’d received a real otoacoustic ear probe to experiment with (see Photo 2). but it enabled me to test the concepts involved.net • www. I’ll cover my resulting otoacoustic experiments in detail. I used my computer. Photo 1—My first attempt at a homemade otoacoustic experimentation headset 36 CIRCUIT CELLAR® www. By the time I figured this out.circuitcellar. I introduced the concept of otoacoustic emissions (OAEs) and how they can be used to test the human ear without requiring conscious interaction with the subject.com . June 2010 – Issue 239 EXPERIMENTS For the otoacoustic probe amplifier portion of this project. Doing so will give you a good grounding in the study of otoacoustics and prepare you for future audio projects. I wasn’t satisfied because I hadn’t seen any actual OAEs by then.Journal-Plaza. and two condenser microphones. This custom headset was constructed from ear protectors I bought at a local hardware store. speakers from a set of standard headphones. Now you can perform otoacoustic experiments. My prototype probe was not sensitive enough to actually detect OAEs. I n the first part of this series. a Cypress Semiconductor PSoC. I presented the combined high-gain otoacoustic probe amplifier and touch-totalk intercom system that I designed to perform a variety of professional otoacoustic studies in a client’s laboratory.net & www. I tried creating my own probe for initial testing purposes (see Photo 1). com • record/playback simultaneously. This should theoretically be all that’s required to run some otoacoustic experiments. this utility application. I discovfound as a tkSnack example ered that a short length of 0. I then had to stimulate and record OAEs to prove the concept.net & www. So. some recent experience with Python (heavily modifying an open-source guitar and drum June 2010 – Issue 239 The new probe was far quieter and more sensitive. given the proper software. Once the earpiece. the microphone does not pick up wrote logic that was supposed to the stimulation clicks at all. in order to identify iment.5″ application. of plagued with reflections—no which several can be running matter what (or how much) simultaneously (see Photo 4). it has a Windows PC. 1″ (diameter) tube—filled with The py2exe module cotton and sealed with some allowed me to create a disduct-seal-type putty (shown tributable folder containing above in Photo 2)—gave me the everything required to run response I needed. However. it could be carried around on a PYTHON TEST APP USB flash drive and run My laptop has standard directly from there on any sound capabilities.) In open manipulate the interface controls. This application appears in the otoacoustic emissions with referPhoto 3. and playback capabilities. I air. the isoautomatically run a “transient clicklation between the transducers is evoked otoacoustic emission” expervery good. I aging” button performs this needed to simulate an inacexperiment automatically. (The “Start Otoacoustic Averence to the stimulation clicks. (The other is used for I got the hang of how to handle and intercom communication. I used ActivePython 2.Journal-Plaza. Eventually. was used as a sound-absorbing The basis for this utility was medium. I typically use Visual Basic 6 to build PC applications quickly. as I have a large personal code base to draw from. and it can www.net .WorldMags.circuitcellar. and CALIBRATION & SIMULATION installed the tkSnack module for The stimulation clicks are proreal-time sound recording. I also included a handy The first several artificial modular function generator ear canals I constructed were utility in this program.2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 37 a) b) Photo 2a—This is a commercial otoacoustic earpiece and homemade artificial ear canal.4’s tkinter module to create the GUI. The source microphone input and a headPhoto 3—This is a Python-based otoacoustic click-stimulation testing application. the method I chose to perform my otoacoustic experiments was to write a program to control the sound card and record test data automatically for post-analysis. code itself could easily be phone output. generaduced by one of the two speakers in tion. 37 CIRCUIT CELLAR® www.) tive ear canal. b—A close-up of an otoacoustic earpiece rhythm game called “Frets on Fire”) prompted me to try this portable language to create a basic multi-platform otoacoustic testing application. I simply trans(diameter) plastic tubing mountformed it into an object that ed in a slightly longer piece of can be instantiated endlessly. Initially. even with high-priority threads.net & www.2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 38 Photo 4—A modular signal generator utility that can be running several instances simultaneously. Instead. etc) with Python and tkSnack.com). which provided sufficient data to complete the task for which I was hired.net • www. NOT GOOD ENOUGH Unfortunately.Journal-Plaza. “DL4YHF’s Amateur Radio Software: Spectrum Lab. the application proved to be too unpredictable with its actual timing regarding sound playback and recording.cpeproto. and sometimes it recorded more or less than others—so the averaging did not result in the desired filtering out of everything but the otoacoustic stimulation clicks and responses (OAEs).WorldMags.com (248) 588-4400 Photo 5—A SpecLab screenshot in “Color Direction Finder” spectrum analyzation mode. 38 CIRCUIT CELLAR® www. I wanted to investigate further and actually see some OAEs for myself! I wasted a lot of time attempting to locate an existing otoacoustic public domain PC application to create the stimulus and analyze the raw preamplified signals for me. but I’ll discuss only the application I ended up using for my amateur OAE experiments. The stimulation click samples were rarely in the exact same spots in the individual session. June 2010 – Issue 239 Intuitive Circuits www. I found several useful tools (links to which I posted on www.circuitcellar. ! New $99 OSD-232+ RS-232/TTL controlled on-screen composite video character and graphic overlay in a small 28 pin dip package. Linux. I decided to hunt for a freeware PC oscilloscope designed for analyzing sound card inputs. and I was only researching this for my own knowledge—so I decided against purchasing a professional otoacoustic-testing package.com . Although it let me get the job done for my client. compiled on any other operating system (Mac OS.” Photo 5 is a screenshot of one of its spectrum analyzer functions at work.icircuits. This application allowed me to test the basic concepts involved in running an otoacoustic experiment here on my workbench. Everything this search turned up was too expensive. 2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 39 Stimulator Pulse detector LM324 PSoC Agnd Agnd + + + One-shot (debounce) CMP Timer delay 1 Agnd + + Agnd Timer delay 2 Agnd Agnd + Timer delay 3 Subject’s finger Stimulation pulses To ear speaker Low-noise Preamp Computer Earpiece From ear microphone Agnd Subject’s ear To mic + To mic input LM4562 Mic power LT1790 1.25 V Low drop-out Precision reference (Photo 5 is not really relevant to OAEs, but it is a great demonstration of this freeware program’s capabilities.) With this powerful PC oscilloscope, I was able to set up a trigger and have it act more or less like my bench scope (only with far more persistence) in the TimeDomain mode. Using a standard sound card to take oscilloscope samples limits the effective frequency range that can be analyzed (unless you have a professional sound card, chances are you can’t sample any faster than 44.1 or 48 kHz), but it Photo 6—Take a look at an in-headphone optical ear lobe pulse was perfect for the detector (disassembled, without flex arm) www.circuitcellar.com • relatively low-frequency otoacoustic emissions. Instead of generating the stimulus clicks from the computer’s sound card and risk interrupting the input stream of data, I decided to use another PSoC so I could control the timing accurately. I configured this new PSoC to output the stimulus clicks upon receipt of a trigger pulse. Refer to the block diagram in Figure 1 and pulse trigger PSoC schematic in Figure 2. This PSoC took advantage of the just-released PSoC Designer 5.0, which includes a nice new IDE and even a new user module called a “OneShot” that was not available in previous revisions. This new module allows hardware-level signal debouncing, which came in handy for June 2010 – Issue 239 Figure 1—The optical pulse sensor triggers the stimulation clicks, which are played into the subject’s ear. The computer records the stimulation clicks and any resulting OAE signals for later analysis. 39 CIRCUIT CELLAR® www.WorldMags.net & www.Journal-Plaza.net June 2010 – Issue 239 2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 40 approximately 10%), and its interrupt triggers the third and final 16-bit Timer module counting down for another 20-ms delay. When this last Timer module finishes counting down, it generates the last 100-µs pulse (on yet another output pin for separate attenuation of approximately 1%). This last Timer module’s interrupt resets and prepares all three Timer delays and interrupts for the next trigger event. In my experiments, I’d shortened the delays between pulses to 10 ms so I could zoom in nice and close on the signal and get detailed screenshots. I could do this because my relatively healthy ears emit OAEs rather quickly, within a few milliseconds of the stimulation click. I did not need the entire 20-ms delay to see Figure 2—The incoming pulse signal is fed through a comparator and a one-shot debouncing module. them. An interrupt from the one-shot module triggers the three sequential 20-ms timers to count down and I included a PSoC project generate the stimulation clicks with a combined signal output. with the recommended 20-ms delays for the official test Timer module counting down for a reliable triggering. parameters (PSoC OAE Trigger – 20-ms delay. When this Timer modThe implementation here is pretty Official Test), and another projule reaches its end count, it also gensimple. The trigger input is first fed ect with the altered 10-ms delays for erates a 100-µs pulse (on a different into an analog comparator and then my known healthy ear test parameoutput pin, for attenuation down to into the new OneShot module to ters (PSoC OAE Trigger – Short debounce. (It debounces for eight of its clock cycles and a) b) then releases. So, in this case, clocked at 48 MHz, it debounces the incoming signal for approximately 0.17 µs.) When the OneShot module releases the debounced signal, it triggers an interrupt that starts the first 16bit Timer module counting down for a 100 ms delay. When this timer module reaches its end count, it generates a 100-µs pulse. Actually, the closest I could easily get here without going overboard with clock dividers was about a 122-µs pulse. Its interrupt triggers the second 16-bit Photo 7a—A finger pulse clamp. b—A close-up of the finger clamp pulse detector, squeezed open. 40 CIRCUIT CELLAR® www.WorldMags.net & www.Journal-Plaza.net • www.circuitcellar.com 2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 41 Figure 3—The raw optical pulse signal requires a fair amount of conditioning and filtering to create a reliable output signal that matches the beat of the subject’s detected pulse. Even after all this, the PSoC stimulation generator still has to debounce the output for almost 20 µs to obtain a clean trigger. Delays). You can experiment with both. DETECTOR/TRIGGER/FILTER Initially, I used a signal generator to trigger the three pluses while I tried to observe the OAEs on my bench scope. This proved to be extremely frustrating, as a large familiar signal was swamping the high-gain amplifier about once per second. It’s funny: when you see it on the scope, you start to hear your own pulse! Instead of attempting to filter out b) Photo 8a—Otoacoustic stimulation clicks in an artificial ear. Note how there is no response (or echos) after the stimulation clicks. This artificial ear canal is perfect for calibrating experiments. b—Otoacoustic stimulation clicks and resulting OAEs from my ears. The closer the responses are to the stimulation clicks, the healthier the ear (in general). www.circuitcellar.com • June 2010 – Issue 239 a) the pulse in either the analog or digital domain, it made more sense to use the slow, steady heartbeat to trigger the otoacoustic stimulation pulses—which would, in turn, trigger the PC oscilloscope and display some useful data. So, after trying in vain to synchronize the stimulus pulses to my heartbeat’s signal—which was being picked up by the same in-ear microphone I was stimulating—I decided make the leap to an optical pulsetriggering solution. As the old saying goes, “if at first you don’t succeed, try, try again.” This is another one of those times. My first idea was to modify the old headset I made. (Refer to Photo 1. I was still using this headset, but only to block ambient noise from the more-sensitive ear probe.) The plan was to sense the pulse in the earlobe of the ear not currently being tested. I mounted the red LEDs to a flexing arm so they would push up and under the bottom of the ear lobe and face into the detector. Then I mounted the photosensor in the headset at the bottom so as to detect the source light shining through the earlobe, thereby giving a signal as the blood flow pulsed through the body. Photo 6 shows this disassembled configuration. Although this method worked fine, it proved to be very cumbersome— due to the “in-ear” nature of the microphone/speaker device being used. A finger-clip design turned out to be far more convenient and usable (see Photo 7a and Photo 7b). I designed the circuit in Figure 3 with an LM224 op-amp (an extended temperature range LM324) mainly because I had plenty of them in stock. The photodiode D1 detects the signal. It is then inverted and preamplified by U1-A while being forwardbiased by the integrator formed with U1-B and C4 through R5. This creates an auto-biasing circuit that keeps the photo voltage centered throughout a wide range of optical energy, but with a slow enough speed so as not to interfere with the pickup of the heartbeat. The signal is 41 CIRCUIT CELLAR® www.WorldMags.net & www.Journal-Plaza.net 2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 42 Computing/HMI Serial I/O The right connection creates incredible power. Connectivity and control. Making your interface as reliable as the tides—and just as strong. Sealevel creates hardware and software solutions for both digital and serial interface requirements. We Listen. Think. And Create. amplified in U1-C and then squared by U1-D. The end result of this line of research is a do-it-yourself otoacoustic experimentation procedure, which can be summarized as a block diagram (see Figure 1). The results of my OAE experiments are captured in Photo 8. The first screenshot (Photo 8a) was taken with the ear probe in the artificial ear canal I built (see Photo 2a, above)—only the stimulus clicks are present, as the artificial ear canal produces no OAEs. The second screenshot (Photo 8b) was taken with the ear probe in a real ear. The stimulus clicks clearly elicit some sort of response signal from within the ear. I have not gone so far as to analyze my findings any further than this; however, with the tools and methods described in this article I believe this could be taken as far as is desired. POSSIBILITIES SeaLINK® USB serial converters reduce host processor overhead compared to traditional processor/UART-based designs. sealevel.com > [email protected] > 864. 843. 4343 In this article, I covered one type of OAE—the click-stimulated OAE. This is the easiest emission to make sense of because it can be controlled for consistent experimental results. The ear also emits OAEs in response to normal auditory stimuli. In fact, I believe these OAEs can be directly correlated to what the test subject is actually “listening”—in other words, these emissions may be able to pinpoint auditory focus. This has the potential to be a new window into the human brain, for all sorts of new studies. Now that you know more about the study of otoacoustics, you can perform hearing experiments with a standard PC. In this two-part article series, I presented how to use a standard PSoC to sense touch and proximity. I also explained how to implement this sensory input to control a touch-to-talk intercom system. Now it’s your turn. I hope I’ve inspired you to start a new project! I Chris Paiano wrote over 30 application notes for the Cypress PSoC chipset, including such novelties as PongSoC and the Video RTA. Applicable links and information are available on his website (www.cpeproto.com). © 1986-2010, Sealevel Systems, Inc. All rights reserved. www.WorldMags.net & www.Journal-Plaza.net CIRCUIT CELLAR® • www.circuitcellar.com html EMBEDDED SERVER Standard SIB (Server-In-a-Box) Starting at $305 Quantity 1. the Circuit Cellar editorial staff highly recommends the following content: — Sound Effects Processing by Robert Papp Circuit Cellar 216. Sweden).Journal-Plaza. Audio.html — PSoC Design Techniques (Part 1) Build an Eight-Channel Mixer by Chris Paiano Circuit Cellar 216.” Ver. 2.py2exe. He also presents an eight-channel mixer with adjustment knobs.org/index. com/p/fofix/.2106014_paiano_Layout 1 5/12/2010 10:45 AM Page 43 NEED-TO-KNOW INFO PROJECT FILES To download the code. www. Spectrum Lab. Since 1985 2.circuitcellar. Filter Go to: www.com/magazine/216. informed engineers and programmers don’t just survive.html. ActivePython 2. You can set the volume level and select effects. DL4YHF’s Amateur Radio Software.2.6 KERNEL ! Power Supply Included ! Locked Compact Flash Access ! Analog SVGA 3D Video ! Optional Wireless LAN ! EMAC Linux 2.py2exe.org/moin/ TkInter. www.com • June 2010 – Issue 239 ! Fanless x86 500MHz/1GHz CPU ! 512MB/1GB DDR2 RAM On Board ! 4GB Compact Flash Disk ! 10/100 Base-T Ethernet ! Reliable (No CPU Fan or Disk Drive) ! Two RS-232 Ports ! Four USB 2.linear.cypress. “Snack Manual. Topics: Op-Amp. | www.com/magazine/216.national.com LT1790-1. Mixer.25 Precision reference Linear Technology Corp. | www. In the computer applications industry.htm OVER 25 YEARS OF SINGLE BOARD SOLUTIONS Phone: (618) 529-4525 · Fax: (618) 457-0110 · www.6 Kernel ! XP Embedded & WinCE 6.com /pub/Circuit_Cellar/2010/239. go to ftp://ftp.9 x 4.7 x 1. Topics: Audio.circuitcellar. they thrive and excel.net & www. For more need-to-know information about topics covered in Chris Paiano’s Issue 239 article.activestate.circuitcellar.2/python-man. Switched Capacitor. and the system’s keyboard is used for navigating through a user menu.python.se/snack/ man/snack2.org/.cgi/FrontPage.speech. Royal Institute of Technology (KTH.com/ActivePython/.” http://wiki. 2004.7” (125 x 120 x 44mm) 43 CIRCUIT CELLAR® www. Python.com Knowledge is power. Frets on Fire X.net . Sound Processing Go to: www. http://downloads.WorldMags. | www.com www. “Tkinter. “py2exe” module.emacinc. www.kth. SOURCES CY8C29466 PSoC and PSoC Designer IDE v5. Python.” http://code.0 Cypress Semiconductor Corp.com LM4562 Audio op-amp National Semiconductor Corp.emacinc.4 Windows Distribution.com/servers/standard_sib. Sound Processing. “MFH Mod: FoFiX.0 www.circuitcellar. RESOURCES ActiveState. 2008 Robert built a sound effects processor.google. 2008 Chris covers several useful PSoC design techniques.0 Ports ! Audio In / Out ! Dimensions: 4. with an Arduino Pro microcontroller holding everything together. T he hardware part of the Totally Featureless Clock I built for a friend is straightforward. validates those codes. Perhaps the most surprising part of the story is that the lack of error-detection bits in the WWVB signal isn’t a serious problem.2 Second 50 40 30 80 40 20 10 P1 8 4 2 1 0.8 Second P0 8 4 2 1 0.4 0.” You understand the hardware and how to build a WWVB simulator. as you saw in my previous column: a WWVB receiver and some big blue numeric displays. one per second.net & www.com . The power remains low for the duration of the pulsewidth modulated data: PULSE MEASUREMENT The first level of defense against invalid data consists of simply measuring the received pulse duration. but the rigid structure and successive frames provide plenty of redundancy.Journal-Plaza. and ensures that the clock always displays the correct time. WWVB Time code format On time point A Time frame 1 minute (Index count 1 second) Minutes UTC At point A 2001 258 Days 18 Hours 42 Minutes Hours UT1 At point A 2001 258 Days 18 Hours 41 Minutes 59.8 0.2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 44 A BOVE THE GROUND PLANE by Ed Nisley (USA) Totally Featureless Clock (Part 3) Signal Processing You are well on your way to building a “totally featureless clock. as shown in Figure 1. The “data” conveyed by each pulse is a frame marker or a single binary bit. The transmitter uses amplitude modulation (AM) with a 60-kHz carrier.2 0. and ensures that the clock displays the correct time. decoding the WWVB time code signal is easy: a data frame consists of 60 pulses.5 Second P4 u ADD SUB ADD P3 8 4 2 1 w 200 100 20 10 P2 0.8 Second 40 20 10 PR June 2010 – Issue 239 20 10 8 4 2 1 0 Year UT1 Correction Leap year indicator Leap second warning Daylight saving time Pending Active Figure 1—Each minute-long WWVB time code frame consists of 60 PWM pulses: one per second. I’ll explain how the firmware converts the received pulse stream into time codes. 44 CIRCUIT CELLAR® www. validates the codes. This article details how firmware converts a received pulse stream into time codes.1 80 40 20 10 P5 0.3 Seconds Days UT1 Sign 0 0.net • www.WorldMags. reducing the carrier power 17 dB at the start of each second. comparing it with the three expected • 800 ms = frame marker • 500 ms = binary one bit • 200 ms = binary zero bit In principle. I adapted this diagram from NIST Special Publication 432. In this column. The format has no error-detection bits.circuitcellar. I mapped zero Glitchiness values to 0. + 8 + 20 ms). // valid frame } else { // none of the above. While the curves with time constants around 50.net . The handler values. the pulses occur at 1 Hz.5% frequency tolerance. binary 0. CPU clock from a down to 3 Jiffies: 60 ms.5% ceramic respulses with microseconator may be off by ond accuracy! 4 ms after an 800-ms Because the Totally Frame pulse.PWM_ERROR)) && (PWM_Width < (PWM_NOMINAL_1 + PWM_ERROR))) { PWM_Class = PWM_ONE. That implies a nomThe pulse from the WWVB receiver valid durations to within the tolerance inal 200-ms binary zero pulse could connects to the INT0 external interdefined by PWM_ERROR. The total uncer(which I called Jiffies) tainty is 63 ms (i. the antenna The Timer1 interrupt handler incre. www. RF propagation across half the and sets a flag indicating that a new dler increments PWM_Width on each continent contributes even more second has occurred.PWM_Width variable on the falling edge to begin timing the pulse width resonance smoothes the power transiments the Jiffy variable each time it and sets up some control variables for tion into exponential rise and fall gets control. binary 1. handler increments the Glitchiness receiver output: there’s obviously no where it triggers a hardware interrupt variable and exits.PWM_ERROR)) && (PWM_Width < (PWM_NOMINAL_0 + PWM_ERROR))) { PWM_Class = PWM_ZERO. each tolerance. // valid one } else if ((PWM_Width > (PWM_NOMINAL_FRAME . The CMMR-6P-60 receiver’s resomenting the current time-of-day variWhen the pulse ends.1 for this plot. and rejecting any pulse that 16-MHz ceramic resonator with a reads the current state of the pin to isn’t close to an acceptable value. it has a regsynchronized with the ular heartbeat. so I allowed during much of the a generous 1% error of day when there’s 8 ms.Listing 1—This code classifies the just-completed pulse from the WWVB receiver as a frame marker. 35 per second. Given the input pulse width WWVB edges. and then divide by 40000 to (high). reason to measure the A 0. non-interrupt 20-ms tick.WorldMags.. the become a 165. I picked a measurement has an 20-ms period that additional uncertainty of produces 50 ticks 20 ms. which (in Figure 2—This plot of the Glitchiness variable shows the total number of noise The Arduino Pro view of the resonator pulses during each minute of 48 mid-winter hours. When the count reaches use when the pulse ends. Glitchiness++. A valid time code frame will have 60 valid pulse durations: a single error restarts the synchronization routine. // valid zero } else if ((PWM_Width > (PWM_NOMINAL_1 . Although create an interrupt every 20 ms. } handler on each edge. lengthy and tedious process of increthe pulse width in Jiffies. the firmware nant ferrite-bar antenna and demoduables if a new minute has also in Listing 1 determines whether the lating circuitry conspire to give it a occurred. if ((PWM_Width > (PWM_NOMINAL_0 . I set determine whether the PWM pulse The WWVB transmitter’s resonant Timer1 to use the divide-by-8 has just begun (low) or just ended antenna system has a very narrow prescaler.com • June 2010 – Issue 239 ) 2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 45 45 CIRCUIT CELLAR® www. so that its value at the risuncertainty to the energy at the firmware then takes care of the ing edge of the WWVB signal will be receiver.net & www.e.to 235-ms pulse at the rupt pin on the Arduino Pro board. ±0. The handler clears the 600-Hz bandwidth: Q = 100. so reset parsing and bail out PWM_Class = PWM_BAD. or a glitch. If it’s not.Journal-Plaza. WWVB_Index = 0. the handler resets Jiffy to zero pulse remains low. starting in the late evening. Because the simply no RF to be Timer1 ticks are not received.PWM_ERROR)) && (PWM_Width < (PWM_NOMINAL_FRAME + PWM_ERROR))) { PWM_Class = PWM_FRAME. board generates its tolerance) I rounded The logarithmic vertical scale compresses the vast range of noise.circuitcellar. the Timer1 han200 µs. I don’t Featureless Clock know the actual tolerruns independently ance for the unit on of the WWVB signal the board. // tick the noise level indicator return. measured width matches one of the ±35-ms jitter spec. ............1..............1............3.1.. the firmware must apply more sanity checking to the incoming pulses by comparing them to the 46 CIRCUIT CELLAR® www.. ~~~~XLC76.. 9H64224219GB5111....231.....net • www. ~~~~WEB514231...............................1..................2.1.....1...................11... ~~~wSBB12...... and solar flux between the transmitter and receiver......... weather........ The firmware does not measure the duration from the end of one PWM pulse to the start of the next.......1...........2.....441..2AGD311.. I converted zero count values to 0.......... ~~~kREG233121.2Y7........231.2......... because that’s when the RF signal has the lowest amplitude...............1....BCE4....... f~~dSIB866534...... creates a character-based histogram of the pulse widths during each minute.......52. ~~~wUD6721.....1....1.... Figure 2 plots the value of the Glitchiness variable at the end of each minute over the course of two midwinter days.circuitcellar.....1 for plotting purposes.......BEI11......... As a result.2 ........11......6......... This is typical behavior: the signal strength rises and falls as RF propagation varies with the wind....2.............4V8.....1..1..1......1. ~~~nQ976332. Another chunk of firmware....4U631.11.....1.......... ~~~~QHB61..... 2541.....1...22..1..1.. ~~~rR7651.271.....4U7..........16GI3....... it’s obvious that ambient noise poses a constant problem: glitchfree minutes are few and far between.621......2..... The logarithmic vertical scale compresses a vast range of noise.......212........... All other pulse Figure 3—This trace shows the minuteby-minute reception quality as a weak WWVB signal fades into the noise while the sun rises on a midwinter day.43.....2 12....... 3923............1....1111..............WorldMags................... .2....2 ...............124........11..............311......1..... ~~~~TK7822.....141..... a-z.... then proceeds 1-9...........2...1............1432.21. ~~~~MA976............2...22 ..........1...432..1....1....3.....1.....3...........8MD..2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 46 Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: Glitchiness: 25 27 9 11 3 6 0 3 5 5 6 10 0 16 14 52 82 104 148 239 269 333 450 524 553 566 506 522 531 523 526 529 546 575 549 Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: Histogram: 24541.....2821.42........22 14111.....................46. As I see it.................. Remember that synchronizing to the signal requires at least two consecutive error-free minutes! widths simply increment Glitchiness................11.9OB... Each histogram character shows the number of pulses during that 20-ms interval: the counting sequence starts with a period for zero counts.... A glitch while the RF signal is high will inject a spurious pulse into the datastream that can be rejected by subsequent checking: a valid time frame must have exactly 60 PWM pulses except during very rare leap minutes........3...........1....1............ 440 to 560.........1.............. w~~kqED9421111..... nor does it insist that pulses start exactly 1 s apart...11..........1541.. z~~~cIA615..................... starting late one evening. 2241.15....... Figure 3 shows half an hour of reception during a midwinter morning as a weak WWVB signal vanishes into the noise............1.631......3 ...........1.Journal-Plaza...... A-Z................................1.1...3.......3311.. EoMA5GC3519E91123222..2T911. Although reception improves overnight...55..................789B51...1......1252...2.....1......262.....2.2......... the firmware in Listing 1 will accept a pulse with any of three different durations: 140 to 260... or 740 to 860 ms..........................16QB........................ FbH6543629AB76.....212... .............1........1361.1.. .11....121.com .....7S9.2..net & www.........442....... CMCA541443G7543. O~uSGCB667656135..................1...24....115. and stalls with a tilde (~) for counts beyond 61.....1......162... i~oQL9C9E97442. ~~~uQ96151... the active time of each pulse is most subject to interference........... ...42...1. June 2010 – Issue 239 Therefore....11127FE31..261.........................12.1...................... which I don’t have room for here..1..................................331...21 ....1...................................... WorldMags. The second entry expects another frame marker. break. } ++WWVB_Index.. WWVB_Parse = pgm_read_byte(&WWVB_Table[WWVB_Index]).com // something bad happened.2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 47 Listing 2—This character array defines the expected value for each second within the time code. } else PWM_Class = PWM_BAD. case '0' : // waiting for a known-zero bit if (PWM_ZERO != PWM_Class) { PWM_Class = PWM_BAD. even without errordetection bits. case 'M' : // waiting for Minute data bits case 'H' : // waiting for Hour data bits case 'D' : // waiting for Day-of-Year data bits case 'Y' : // waiting for Year data bits if ((PWM_ZERO == PWM_Class) || (PWM_ONE == PWM_Class)) { WWVB_Time. The first entry corresponds to the “unsynchronized” state that occurs when the firmware is trying to synchronize with the WWVB time code signal by waiting for a frame marker. as defined by the WWVB_Table character array and accumulates successive data bits encoding the minute. // 5 Minute 8 // remainder of array omitted here } expected values. A seventh Reference frame marker defines the start of the time code frame during the “zero-th” second of each minute. hour. so restart entire sync process // everything worked right. return..net . 29. } break. return. // similar cases omitted here } 47 CIRCUIT CELLAR® www. 39. break. break. // 59 P0 marker in previous minute = fundamental sync starting point 'R'. // 2 Minute 20 'M'.Journal-Plaza.uli << 1) | PWM_Class. // fetch expected event from parse table switch (WWVB_Parse) { // process PWM pulse according to what we expect to find if (PWM_BAD == PWM_Class) { WWVB_Index = 0. case 'R' : // waiting for PR marker at start of minute if (PWM_FRAME == PWM_Class) { WWVB_Time. // this will be set properly in a valid minute } else PWM_Class = PWM_BAD. WWVB_Second = 0. // 4 reserved 'M'. // 1 Minute 40 'M'. during the 9.circuitcellar.net & www. // it's still the zero-th second } else PWM_Class = PWM_BAD. a 4-byte integer union. // 0 PR Frame Reference marker @ second = 0 = minute starting point 'M'. 49. the time code frame in Figure 1 has an extremely rigid structure that simplifies the decoding process and allows for considerable error checking.uli = (WWVB_Time. Six 800-ms frame markers occur “at the nines” of each minute.uli = 0. // 3 Minute 10 '0'. // BINGO! Flush old bits to make room for the new ones.ui = 0. so step to next table entry • June 2010 – Issue 239 case 'S' : // waiting for P0 marker to start sync process if (PWM_FRAME == PWM_Class) { WWVB_Second = 0. www. because two consecutive markers uniquely indicate the start of a new minute. and year into WWVB_Time. and 59 second pulses. day. PROGMEM prog_char WWVB_Table[] = { 'S'. WWVB_Flags. TIME CODE FRAME SYNCH Fortunately. The Listing 3—This code verifies that each pulse matches the expected value for the current second. 19. The Listing 4—The WWVB_Time variable is a union that allows firmware can compare access to the same bits as either an unsigned integer or a the just-measured collection of bit fields. be invalid. requires an 800-ms unsigned char Hour_10:2. The leading edge of each subsequent PWM pulse defines the start of the seconds within the minute. steps through I used a simple state machine to the entries as PWM pulses arrive parse the incoming data. leap second. cates an error. Along with the UTC time. of the 60 PWM pulses in each frame. and the remaining 42 pulses must be binary data. marker. 11 must be binary zeros. seven must be frame markers. then the ‘R’ case resets &RUWH[Œ0&RUWH[5DQG&0&8V DQG$QGURLG WWVB_Index to select the first array ‡6XSSRUWIRUDOO$50DSSOLFDWLRQSURFHVVRUV ‡5726DQGPLGGOHZDUHOLEUDULHV ‡+LJKSHUIRUPDQFHGHEXJDQGWUDFHDGDSWHU entry and the search for a frame pulse ‡86%-7$*DGDSWHUDQGHYDOXDWLRQERDUGV starts all over again. allowed value for that position in the frame struct WWVB_time_bits_ { to validate the pulse. in order of occurrence.net & www. The from the receiver. Thus. unsigned char DOY_10:4.com 1-800-348-8051 binary zeros. and minute of the PR marker at the start of the frame. struct WWVB_time_bits_ bits. However. and UT1 corrections.com . the state varitime code frame. able and array index. The ‘R’ character directs the switch statement to verify that the next pulse is another frame pulse.Journal-Plaza. a frame pulse occurring union WWVB_time_code_ { in a data bit’s slot indiunsigned long int uli. While it’s possible the format may change in the future. hour. time code frame must }. time code format unsigned char Hour_1:4. additional bits indicate leap year. For example. you do not know the current time until well after the minute begins. but label each second within a time it’s incorrect for that position in the frame. indicating that the firmware must wait for a valid frame pulse to arrive. Daylight Saving Time. WWVB_Table array partially shown in The firmware starts with WWVB_Index selecting the first array entry. 48 CIRCUIT CELLAR® www. the entire unsigned char Minute_1:4. unsigned char Minute_10:3. 500-ms binary one unsigned char DOY_1:4. pulse arrives when the unsigned char DOY_100:2. and P0. if the pulse is a binary For ARM Application Processors: For Microcontroller: zero or one (which is the most likely ® ‡(FOLSVHEDVHGGHYHORSPHQWWRROVIRU/LQX[ ‡6RIWZDUHGHYHORSPHQWWRROVIRU$50 outcome!).. bits that are currently transmitted as www. In both }..net • www.circuitcellar. cases. the last change was in the mid-1960s. You could modify this routine to allow both zero and one June 2010 – Issue 239 Leading Embedded Development Tools. Similarly. the firmware increments WWVB_Index to point to the second table entry. The ‘0’ case shows how the firmware verifies the reserved frame . the time code includes 11 Reserved bits that are always transmitted as 200-ms binary zero pulses. three allowed durations and passed the Listing 2 contains characters that pulse-width test described earlier. Because the time code bits arrive after the start of the minute. two consecutive frame pulses indicate the beginning of the time code frame for a new minute. if a unsigned char Year_10:4. In addition to frame markers and data bits. the received pulse has one of the volatile union WWVB_time_code_ WWVB_Time. The ‘S’ character directs the switch statement in Listing 3 to select the corresponding case statement.2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 48 frame markers in each minute are known as PR. When a frame pulse eventually arrives. P1 through P5. The time code bits within each frame give the UTC year. WWVB_Index.WorldMags. day-of-year. The interrupt handler shifts incoming WWVB data bits into the integer and the non-interrupt pulse width with the code sets the time with the bit-field BCD values. which ignores anything other than a frame pulse by setting WWVB_Class to flag an invalid duration. unsigned char Year_1:4.keil. As shown in twice a month.9 Loc= 3 Age=0 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 UTC: 10 004 08:33:00. That. which extracts the BCD digits event. that and then extract them through the bit offset continues until the clock once fields. programs fall right off the rails at that bits.5 days of midwinter reception time code in clearly shows high daytime noise levels. these compact devices will deliver. #1350 Micro Maestro 6-Channel $19. www.net . as my friend observes.95 #1352 Mini Maestro 12-Channel $29. The first valid frame arrived after 222 minutes of poor reception. so that any future changes to the point.95 #1354 Mini Maestro 18-Channel $39. I overlaid those fields with always has one invalid digit and that an unsigned long int variable in a digit is generally high by a power of union that makes it easy to shift the two. the clock may show 6:21 or incoming data bits into the integer 3:21 rather than 2:21. where it once again waits until it encounters a frame marker pulse. A similar routine shifts the again synchronizes with WWVB and frame’s flag bits into another union receives an error-free time code variable. hour. A single invalid pulse during that entire sequence causes the parser to reject the entire frame and return to the first state. While this pulses while extracting data and flag seems difficult. and internal scripting Free configuration and control application with motion sequencer Channels can be used for digital I/O or up to 12 analog inputs Individual servo speed and acceleration control for each channel Up to 8 KB of internal scripting memory (~3000 servo positions) 0. After receiving two consecutive can take all day! frame marker pulses to establish The firmware must somehow synch with a new time code frame.25 us servo pulse resolution with pulse rate up to 333 Hz more information at www. host controller-free applications.WorldMags.083259 Elapsed 13440 Offset 1 Corr +2 ICR1 39842 Set: 10 004 08:32:59.Journal-Plaza.net & www. detect bad data bits. Whether you want the best servo controller available or a versatile. general-purpose I/O control board. Worse. during which the adjusted internal timer had gained only one second. frame. 18-. even without an the firmware must see 59 more valid error-correction code.0 Loc= 3 Age=223 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 WWVB: 30200410 Flags=0510 Valid 1 UTC: 10 004 08:32:00.com • Maestro USB Servo Controllers Conduct a symphony of servos. the minute ends with a valid Figure 5—Plotting the histograms from 3. because my friend reports her encoding the UTC year. Although the frame has passed time code format will not require a incoming inspection with valid pulse corresponding firmware update. an The WWVB_Table entries for the error may have flipped one of the data minute.pololu. commercial WWVB-based clock disand minute into bit field variables plays an incorrect time perhaps that occupy 31 bits. 500-. wind up at the same routine in ListThis is a rare.circuitcellar. but it to-right mark the 200-.0 Loc= 3 Age=222 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 WWVB: 29200410 Flags=0510 Bad prediction: WWVB: 17200410 Flags=0510 UTC: 10 004 08:31:00. TTL serial. If all goes well. hour. The vertical seems most scale is simply the numeric equivalent of the ASCII characters shown in WWVB clock Figure 3. durations in all the right places.9 Loc= 3 Age=1 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 49 CIRCUIT CELLAR® www. The displayed time Listing 4.0 Loc= 3 Age=225 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 WWVB: 32200410 Flags=0510 Valid 3 Drift: TS 5265872 UTC 10004. day. and 24-channel Mini Maestros take serial servo controllers to the next level by incorporating native USB control for easy connection to a PC and programmability via a simple scripting language for self-contained.95 Pololu's 6-channel Micro Maestro and new 12-. and 800-ms pulse widths.2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 49 Introducing Pololu’s new Figure 4—The firmware validates four consecutive time code frames before synchronizing to the WWVB signal. The three ridges running lefthand. day.com/maestro June 2010 – Issue 239 UTC: 10 004 08:30:00. ing 3.95 #1356 Mini Maestro 24-Channel $49. Three control methods: USB. and year fields all bits and that seems to be undetectable. it simply requires bits from the frame.9 Loc= 3 Age=224 LY=0 LS=0 DST=0 Chg=0 UT1=1 Mon=1 DOM=4 WWVB: 31200410 Flags=0510 Valid 2 UTC: 10 004 08:33:00. but not impossible. receiving four consecutive valid frames occurs much less often than receiving just two. then it’s almost certain the time code was received without error.circuitcellar. which was corrected by increasing Timer1’s period by two counts: a mere 0. and compares both the time and flag variables to the current copy. so the firmware synchronized with the frame at UTC 08:32 in the last second of that minute. June 2010 – Issue 239 ENFORCING REDUNDANCY The NIST’s “Recommended Practices” document clearly spells out the technique: “During a given hour. at the cost of eliminating some perfectly valid time code frames. the clock can afford to wait for another minute: it has plenty of time on its hands. or UT1 information happens to be inserted or deleted). however. Obviously. It increments the minute field in that copy. the handler copies the time and flag bit field variables. and shifting a few bits to the LEDs.WorldMags. but the clock can free-run quite accurately for a day or two between synchs.5 days of minute-by-minute histogram data similar to Figure 3. plotted using the numeric equivalent of the ASCII characters on the vertical scale. The large hills in the background mark high-noise daylight hours. 25. The first valid time code frame was UTC 08:29. The 50 units of the pulse width scale along the left edge have 20-ms increments: the three left-toright ridges at 10.005%. the firmware saves the current values to compare with the next valid frame and resumes waiting. Therefore. Obviously. With the clock’s internal time once again synchronized to the WWVB signal. it proceeds to synchronize its internal time with the UTC values from WWVB. The firmware also adjusted the Timer1 tick rate to compensate for the ceramic resonator’s frequency offset and drift. sets a flag indicating that the copies are valid. After the interrupt at the end of the P0 marker in a completely valid time code frame. with 50 CIRCUIT CELLAR® www.2106004_nisley Post FE for PP_Layout 1 5/13/2010 3:31 PM Page 50 thinking outside the frame. DST. After all. If they match exactly.net & www. In that case.net • www. during the last hundred milliseconds of the last second in the minute. The main-line routine stores the time and bit fields for the previous valid frame. RECEPTION RESULTS I left the clock running for several months while collecting its trace data with a low-power laptop. That process occurs immediately after the end of the WWVB P0 pulse. and 40 mark the three valid PWM pulses. Given the errors displayed on my friend’s various WWVB clocks. the time code normally changes from frame-to-frame in an entirely predictable fashion. which arrived 222 minutes after the previous valid frame.com . or four consecutive frames must match. the plusone-minute prediction based on a four-hour-old frame was invalid! The next three frames also passed incoming inspection.Journal-Plaza. A pair of DIP switches on the back of the clock selects the degree of redundancy: two. and prepares to extract the bits from the next time code. when the variables still match the current minute! Figure 4 shows the synchronization process. three. When the firmware has sufficient confidence that the time and flag variables have the correct bits.”[1] None of the WWVB clock programs I’ve found on the web take advantage of that redundancy. encoding. In this case. the clock’s internal time was fast by 1 second over those 4 hours. there’s no way to know which copy is wrong. Figure 5 shows 3. If the variables differ. the rest of the firmware is a simple matter of counting. which makes bit and frame averaging possible and desirable. thus predicting what the current time variable bits should be. some of the proprietary programs work the same way: poorly. only the minute information in the time code changes from frame-to-frame (except during the rare hours when leap second. This technique also handles leap minutes and other oddities. net .WorldMags.Journal-Plaza.51_Layout 1 5/13/2010 4:37 PM Page 1 www.net & www. 2010. I Ed Nisley is an EE and author in Poughkeepsie. In the computer applications industry. REFERENCE June 2010 – Issue 239 [1] M. even when it must receive four sequential correct time codes.” Circuit Cellar 235.com . Decoding Go to: www. informed engineers and programmers don’t just survive. all the “constant variables” use that trick. Now. The ceramic oscillator is sufficiently stable to maintain timekeeping within 25 ppm. Many eyes make bugs shallow. 2008.net • www. A.gov/general/pdf/1383.2106004_nisley Post FE for PP_Layout 1 5/12/2010 10:48 AM Page 52 low-noise valleys appearing at night. but complex receivers can perform better symbol decoding. For more need-to-know information about topics covered in Ed Nisley’s Issue 239 article. CMMR-6P-60 WWVB Receiver (Digi-Key Part No. nist. they thrive and excel. Transmission. Nisley. et al. et al. WWVB. G.WorldMags.nist. the code accompanying this column should work better. http://tf. so the clock will be accurate enough for my friend’s purposes. Synchronization. E. Topics: Time Signal.boulder. 2005. “WWVB Radio Controlled Clocks: Recommended Practices for Manufacturers and Consumers.net & www.org with “Circuit Cellar” in the subject to avoid spam filters. WWVB time code signal. and PCB layout from the Circuit Cellar FTP site. 561-1014-ND) C-MAX | www.” NIST Special Publication 960-14. S.com NEED-TO-KNOW INFO Knowledge is power. “NIST Time and Frequency Radio Stations: WWV. You can download the complete source program.” Circuit Cellar 220. PCB layout. NIST.pdf. in fact. which doesn’t surprise me at all. 2005.com Digi-Key Corp. so I put it entirely in flash memory to eliminate 61 bytes of RAM usage. during each pulse. WWVB transmitter and data format specs. WWVH.pdf. 2008 Coordinate your Ethernet applications with a time server.circuitcellar. rather than 10 dB.com/pub/Circuit_ Cellar/2010/239.circuitcellar. http://tf.com/magazine/220.” Circuit Cellar 237. which amounts to 2 seconds per day. http://tf.” NIST Special Publication 250-67. Here you learn how the signal works. Alert reader Bernard Debbasch pointed out that WWVB now drops the carrier 17 dB. If the clock’s new home in her kitchen has worse reception than my living room.c-max-time.digikey.html — Digital Decoding Decode Periodic Signal Transmissions by Danilo Consonni Circuit Cellar 225. NIST. “Time Server Design: Synchronize with the WWVB Time Code Signal.html 52 CIRCUIT CELLAR® www. ———. “Totally Featureless Clock (Part 1): WWVB Simulator.nisley@ieee. 2010. Lombardi. PROJECT FILES To download the schematics.cc/en/Main/ArduinoBoardPro EAGLE Schematic and PCB layout CadSoft | www. The system keeps a master time and date clock that is synchronized to the U. to finish machining and gluing the clock’s Totally Featureless Case! CONTACT RELEASE The WWVB_Table is a constant array. RESOURCES M. and WWVB. NY.htm.circuitcellar. Fortunately. 2002. The 7 dB change occurred several years ago. Topics: Time Signal. but most of their documentation hasn’t caught up. 2009 This digital decoder decodes the SRC-RAI signal.circuitcellar. He also found an error in my Daylight Saving Time calculation.arduino. and Arduino program.pdf. Contact him at ed.” NIST Special Publication 432.com/magazine/225.nist.nist.gov/general/pdf/1976. Nelson.gov/ general/pdf/1969. SOURCES Arduino Pro Microcontroller board Arduino | www. go to ftp://ftp. (distributor) | www. “Totally Featureless Clock (Part 2): Hardware. Ethernet Go to: www.cadsoftusa.Journal-Plaza.gov/stations/wwvb. the evidence suggests it’ll work fine with only two or three consecutive time codes. the clock synchronizes properly several times in each 24-hour period. Although the PWM pulses are present during the day.boulder. Nickels.S. Demodulation. The first line in Listing 3 extracts the array entry corresponding to the current state: pgm_read_byte() function is the Arduino way of fetching flash values to RAM. schematics. Lombardi. The net effect is to make the PWM pulses more susceptible to amplitude noise. it’s obvious that the simple AM receiver and DSP techniques I’m using aren’t up to the task of extracting valid time codes from the noise.com. “NIST Time and Frequency Services. the Circuit Cellar editorial staff highly recommends the following content: — Time Server Design Synchronize with the WWVB Time Code Signal by Steven Nickels Circuit Cellar 220. tf. net & www.WorldMags. The newest RF products and technologies make designing even more fun. RF Front End Range Extender: CC2591 591 mouser.com/siliconlabssi100x MC13224V ZigBee™ Platform-in-Package mouser. Other products. www.com/TICC2591 Si100x / Si101x Single Chip MCU with RF Transceiver mouser. and company names mentioned herein. may be trademarks of their respective owners.28_Layout 1 5/12/2010 8:38 AM Page 1 The Newest Products For Your Newest Designs When it comes to new RF technologies.net 3:01:34 PM . we’re on the same wavelength.com/celupg2253t6s WARNING: Designing with Hot.com (800) 346-6873 Mouser and Mouser Electronics are registered trademarks of Mouser Electronics.com/freescale_mc13224v UPG2253T6S RF front-end IC mouser. New Products May Cause a Time-to-Market Advantage. Experience Mouser’s time-to-market advantage with no minimums and sameday shipping of the newest products from more than 400 leading suppliers.Journal-Plaza. logos. Inc. mouser. I don’t know. if you try to reduce the current circulating in an inductor.com . You can recover this energy by switching off the voltage source. but even some experienced designers are afraid of inductors.5LI2 Generates a voltage proportional to the current variation over time U = L × dv/dt Forbids immediate current change Table 1—Capacitors and inductors have symmetrical properties. More precisely.net & www. and when the current is switched off. and high-frequency designs. Inductor-based filtering will need another column. Applying a voltage to a capacitor charges it. you’ll end up with the definition for an inductor.circuitcellar. it will generate a voltage to compensate for this reduction Inductor Store energy as a magnetic field Energy proportional to the square of the current E = 0. an inductor will do whatever it can to keep the current constant. let alone put to good use. I won’t describe an actual power supply project. Beginners in electronics are quickly at ease with resistors and capacitors. If you reread the previous sentence and exchange the word voltage with current and the word electrical with magnetic. My goal. it is unfortunate because inductors are more than helpful: their main domains of excellence are filtering. which Capacitor Store energy as an electric field Energy proportional to the square of the voltage E = 0. The voltage across the capacitor remains constant and then decays when the energy is pulled out of the capacitor. INDUCTORS? June 2010 – Issue 239 You know that a capacitor can store energy. Thus.Journal-Plaza. W elcome back to The Darker Side.net • www. This means it stores magnetic energy through its windings. or at least to understand how such a converter actually works. Explained in another way. is to help you understand how to design it yourself.5CU2 Generates a current proportional to the voltage variation over time I = C × dv/dt Forbids immediate voltage change means it stores electrical energy between its electrodes. Stay tuned.WorldMags.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:16 AM Page 54 T HE DARKER SIDE by Robert Lacoste (France) DC/DC Converter Basics Inductors can be difficult to understand. Maybe it’s because their behavior is a little less easy to understand due to the underlying magnetic physics? In any case. All of these are hot topics. a current passing in an inductor creates a magnetic field. Why? Honestly. 54 CIRCUIT CELLAR® www. however. I’ll remind you about inductors and how you can use them to build high-efficiency DC/DC converters. this magnetic field generates the same current in the inductor and then decays. power conversion. This month. This article bridges the gap between inductor theory and the practice of using inductors to build efficient DC/DC converters. You can recover this energy by switching off the current source: the current circulating in the inductor stays constant and then decays when the energy is pulled out of its windings. Applying a current to an inductor charges it. What’s the behavior of an inductor simply connected to a voltage source through a current-limiting resistor? Refer to Figure 1a.WorldMags. That would mean a non-null current change (di) in a time step (dt) equal to zero. but the rate of increase of the current is unchanged. Another interesting simulation is to connect an inductor—still through a current-limiting resistor—to a pulse generator. And that’s exactly what Figure 2 shows you.5 A) and continue to flow in the same direction. I used my preferred CAD tool suite. so the current slope is lower and lower.net . the voltage across the inductor (in red) becomes negative in order to continue to “pull” current from the source. the voltage across the inductor (in red) decreases.5 A in this example. the current through the inductor (in blue) decreases but can’t change suddenly. It’s 6. 55 CIRCUIT CELLAR® www. which implies that the voltage across the inductor is a) b) Figure 1a—When applying a voltage source to an inductor through a current-limiting resistor. When the source is switched to zero. Here the current will increase linearly over time if the voltage across the inductor remains constant. Labcenter’s Proteus. but the initial slope is exactly the same. the current going through the inductor must stay constant (6. the final current is higher. there is no black the pulse goes low.5 V + 6. This slowing down is due to the increased voltage drop across the resistor (remember U = R × I).5 A = –6. Just before switching off. resulting an infinite voltage.5 A (as the voltage drop across the resistor is 6. the current first increases when the pulse is high. the current going through the inductor increases to a given value fixed by the voltage and duration of the pulse. As expected. as shown on Figure 1b. Reversing the formula gives di = U/L × dt. The inductor needs to generate a voltage of U = R × I = 1 Ω × –6.circuitcellar.com • reduced over time as the current increases. there is no way to increase the current through an inductor L faster than at a rate of U/L amperes each second. b—When the resistor is lowered.5 V. When the source is switched back to 0 V. They have a lot in common. Figure 2.Journal-Plaza. Once again. 10 V and 0 V.5 A. But you can reproduce these examples with any Spice-based tool. thanks to the inductor. you can’t immediately change the current flowing through an inductor. As a consemagic in negative voltages quence. This means that the inductor must continue to “pull” current from the source. It is fixed by the inductance L. I simulated this one for you too. the voltage U between the terminals of an inductor is proportional to the current’s rate of change (meaning to its derivative across time) and the multiplicative factor is the inductance: U = L × di/dt. Based on this formula. or high voltages generated www. but this is possible only with a negative voltage across the inductor as the source is at ground level! And that’s what’s illustrated in the simulation. and the result is depicted in June 2010 – Issue 239 and keep the current constant (at least initially).5 V and the current is 6.net & www.5 V= 10 V. the current must stay at 6. When So. Let’s consider some examples. the current (in blue) climbs slowly and reaches the current limit set by the resistor. Table 1 summarizes the key characteristics of inductors and capacitors. the voltage across the inductor is 3. say. Mathematically speaking.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:19 AM Page 55 SIMULATION Enough theory. the final current will be higher.5 V and 3. Configure the generator to quickly switch between a fixed voltage of. If you reduce the resistor. the current doesn’t “jump” from zero to a high current. What’s happening? When the source voltage jumps from 0 to 10 V. the source voltage). At the same time. It starts by a gentle linear increase and then slows down until it reaches the current limit defined by the resistor.5 A × 1 Ω = 6. which is now at 0 V. Figure 2—When applying a voltage pulse to an inductor. With a voltage source U. This is Lenz’s Law. The slope of the blue curve is identical on both figures at the starting point. usually an integrated dedicated DC/DC controller chip. The blue line on the leftmost graph shows you that the output voltage is a stable –5 V. When the transistor is switched off. In fact. nearly all DC/DC converters manage this task automatically in a closed-loop way: a circuit. Here the input voltage is 12 V and the out- put is –5 V. You have a voltage inverter. The current through the inductor also increases when the transistor is on. A boost converter always generates a Figure 4—This diagram shows you how to interconnect the transistor. INDUCTORS TO CONVERTERS June 2010 – Issue 239 You now know enough to understand the topology of all usual DC/DC converters. When the transistor is switched on.net & www. The last simulation showed you that a negative voltage can be generated by switching off current in an inductor. This means that the inductor generates a positive voltage that adds to the input voltage. A capacitor. Such a converter always generates a voltage with a polarity opposed to the source’s polarity. blue line). measures the output voltage. This gives the inverter DC/DC converter topology shown in Figure 3. just change the on/off ratio of the logic signal driving the transistor—that is.net • www. By the way. stores this negative voltage and power the load simulated by R1. More on that later. even if the current circulating in the inductor oscillates between 1 and 1.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:21 AM Page 56 Figure 3—A DC/DC inverting converter is achieved with a simple modification to Figure 2. the current through the inductor increases and the diode doesn’t conduct any current. by inductors.circuitcellar. but when it switches off. and capacitor to make a step-up boost converter. When it switched off. Here a current is forced to circulate in the inductor when the transistor is switched on.Journal-Plaza. its duty cycle. Other topologies are also quite easy to understand.WorldMags. a negative voltage appears across the inductor and charges the output capacitor C1 through the diode D1. the current through the inductor decreases and the diode loads the capacitor with a negative voltage. If you move the transistor to the other end of the inductor and reverse the diode. diode. It is just that the energy stored in the magnetic field around the inductor (or inside its core for non-air-based coils) must be given back and with no jumps in current. you have a step-up boost converter as shown in Figure 4. 56 CIRCUIT CELLAR® www. Look at the current plot. and adjusts the duty cycle of the gate signal in accordance. the energy will be 100% restored if the so-called quality factor of the inductor is one. Here the input is 12 V and the output is 17 V.com . C1. To modify the output voltage. the current must continue to flow from the input voltage to the capacitor through the inductor and diode. compares it with the required voltage. inductor.8 A (right graph. which is unfortunately never exactly the case. The idea is to quickly switch on and off current in the inductor through a transistor—the P-channel T1 MOSFET in this instance—and grab the negative voltage pulses generated by the inductor through diode D1. 2/9/2010 9:34 AM Page 1 How far will your design take you? 5. Use the Stellaris® LM3S9B96 microcontroller from Texas Instruments with Keil’s RealView® Microcontroller Development Kit (RVMDK) and SafeRTOS™ from Wittenstein to create your design contest entry. s s . and see how far your design will take you! Stellaris EKK-LM3S9B96 Evaluation Kit free with your contest entry while supplies last! s . CAN.qxp Challenge yourself against other top embedded engineers around the world in DesignStellaris 2010. and SafeRTOS in ROM. cables. sponsored by Texas Instruments. a time-limited copy of the Keil RealView Microcontroller Development Kit.OPURCHASENECESSARYTOENTER The EKK-LM3S9B96 Evaluation Kit includes: an evaluation board with an 80 MHz LM3S9B96 MCU featuring Ethernet MAC+PHY. documentation. and StellarisWare® software. USB OTG. INCASHPRIZES %NTRYDEADLINEIS*UNE. ti.Journal-Plaza.net & www. s 7INNERSWILLBEANNOUNCEDATTHE %MBEDDED3YSTEMS#ONFERENCE Boston 2010. Visit: www. s 3UBMITYOURDESIGNTODAY For Complete Details.net .WorldMags.com/designstellaris2010 www. the current increases and loads the output capacitor at the same time.WorldMags. When the transistor is switched off. It has still the same number of components but just shuffled around. or like synchronous variants. while the input current oscillates from 0 to 1. When it switches off. which replace the diode with a second transistor to increase efficiency.41 A. the current increases in the inductor and loads the output capacitor. you can modify the output voltage just by changing the duty cycle on the driving signal or by asking the DC/DC controller chip to do it for you.4. For this simulation. Nor can I spend too much time on the IC controller.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:23 AM Page 58 Figure 5—The last common configuration is the stepdown buck converter. but this time thanks to the voltage generated by the inductor and circulating through the diode. Here the 12-V input is down converted to 5 V. which would draw at least 1 A on the 5 V—meaning. Here. This means it continues to charge the capacitor. Thus. I’ll address one topology and explain how to choose the proper component values for a design.net & www. When it is off.3 A.8 W). an inductor or a capacitor won’t dissipate any power if you consider that their parasitic resistances are very low. so they can be minimized with a proper selection of components. The transistor will not dissipate any significant power if its on-state resistance is low and if its transitions are fast enough. In this example. In order to stay focused on the fundamentals. the current continues to flow in the same direction. Lastly. it will dissipate 64% of the energy in heat.com . with the same polarity. For buck converters. Now you are convinced. of course. and in the diode D1.8 W/5 V = 0. the current through the inductor increases as before.circuitcellar. you get 17 V at the output. Just compare it to a linear regulator. 58 CIRCUIT CELLAR® www. a 5V voltage is generated from the 12-V input. 1. meaning that there is always a current flowing in the inductor. if you need 1 A under 1. Let’s also assume that the converter is working in the so-called continuous conduction mode..8 V (i. As one end of the inductor is still at 12 V. but this time through D1. of course. when the transistor is switched on. the current must continue to charge the capacitor. which is especially useful in AC/DC power supplies. which allows you to increase or decrease the voltage. Similarly. There are. Once again. also all the so-called flyback variants that use a transformer to get a galvanic insulation between source and load. Plenty of other DC/DC converters topologies exist.net • www. such as the buck/boost converter. the inductor must generate a voltage that will add to the 12 V and charge the capacitor C1 through D1. the current must continue to flow in the same direction. You could.e. Let’s first set the output voltage of the converter. you’ll draw a little more than I = P/U = 1. use a linear voltage regulator for this Toff IAC IAC dP SELECTING COMPONENTS June 2010 – Issue 239 task. i Ton I can’t cover all the interesting topologies in one column. When the transistor is on. discuss only this configuration in this article. If you look again at Figure 5 you will understand why its efficiency is close to 100%. with an average of only 0. but a step-down voltage converter has a key advantage: its theoretical power conversion efficiency is close to 100%. the most usual topology is the step down buck converter (see Figure 5). I will target the typical step-down buck converter because you will implement such a converter to generate the 1. This variant generates a voltage always lower than the source voltage and with the same polarity. a good value is usually r = 0. which is the most IDC (1-d)dP P (period) t r=IAC/IDC Figure 6—The current ripple ratio r is defined as the ratio between the DC current circulating through the inductor and the AC component of this current. thanks to the voltage generated by the inductor.8 V needed by a processor core or an FPGA from the 5-V rail. for simplicity. starting with 12 V. when the transistor is switched on. The output current is a constant 1 A. The only power losses are in the parasitic resistances of the components. so let’s use a buck converter. voltage higher than the source.Journal-Plaza. (I will.36 A from the 5-V line. Here. If you want a current ripple ratio (r) equal to 0. Unfortunately. the output voltage of such a converter is absolutely independent of any component’s value. We do up to three iterations of a design within a day. a circuit measures the actual output voltage and corrects the duty cycle. industrial quality PCBs right at your desk? LPKF’s ProtoMat benchtop prototyping systems are helping thousands of engineers around the world take their development time from days and weeks to minutes and hours. and the components are not perfect.net . Let’s do the math: L = U × dt/di = 5 V × 32 µs/0. as the duty cycle of the transistor is 0. it calculates the required duty cycle and applies it to the transistor without any control chip. the voltage across the inductor is simply the output voltage. A standard 220-µH inductor will be perfect. so a closed-control loop will be far better. Calculating the inductor is actually simple.4 × 1 A = 0. The duty cycle will be equal to the voltage ratio: d = 1. And you also know dt. However.Journal-Plaza. Theoretically. An optimal converter. So. even if it seems strange. It is simply the period of the converter (1/200 kHz = 50 µs) multiplied by 1 – d = 1 – 0. That’s all.com • inductor value by looking at either the transistor’s “on” time or “off” time.) The equation giving the output voltage of a buck converter in such a case is very simple: it is equal to the input voltage times the duty cycle of the transistor.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:23 AM Page 59 www. the current variation. www. The average current through the inductor will be equal to the output current: IDC = IOUT = 1 A.36 = 0. this condition may be not accepted by socalled “discontinuous conduction mode” converters.WorldMags.64 = 32 µs. Remember the inductor equation U = L × di/dt? During the off time.8 A. What about the selection of the inductor? If you refer back to Figure 5. as long as all components are supposed perfects. you could use open-loop control as long as the input voltage remains constant— that is. you have U = 5 V. The result will be the same. at least if you neglect the voltage drop across the diode. So dt = 50 µs × 0. the input voltage usually isn’t stable enough. this current also has an AC component (IAC) as it swings from IDC + IAC to IDC – IAC at the converter-switching frequency (see Figure 6). More on that later.net & www. In such a loop.4.4. but this would bring us too far). In today’s race to market.com/pcb 1-800-345-LPKF “You can’t beat an LPKF system for prototyping.8 V/5 V = 0.64. Still on the example of a 5 V to 1.8 A = 200 µH.8 V/1 A converter shown in Figure 5. You have everything needed to calculate L. you’ll see that the average current circulating in the inductor is. You also know di. In a buck converter. it’s like having a time machine. This last equation—L = U × dt/di—is ProtoMat® Benchtop PCB Prototyping Machine What would your day look like tomorrow if you could cut yourself free from the board house and produce true. including the inductor. which is called the current ripple ratio.circuitcellar. is usually achieved with r close to 0.36 (see Figure 6). when the transistor is switched off.8 V/1 A step-down buck converter and assume that the switching frequency is 200 kHz. you need to have IAC = r × IDC = 0. equal to the output current IDC. at least for a buck converter.36. in terms of efficiency and size. Let’s return to the example of a 5 V to 1. which is di = 2 × IAC = 2 × 0.lpkfusa. which is the time the transistor is off.” Leonard Weber Agilent June 2010 – Issue 239 common as long as the output current is not very small.4 A. This means that the current variation through the inductor shouldn’t be to large in order to avoid the current going to zero amperes (to be complete. Consider the ratio r between IAC and IDC. it is easier to use the “off” time.4 A = 0. This current variation must also be large enough to get the proper value for r. You can then calculate the 59 CIRCUIT CELLAR® www. 4 A. inductor. The transistor is switched on periodically. troller to regulate the output Figure 7—This schematic shows you how a current-mode PWM regulator which also means that the voltage.” You ultra-low ESR. increasing the principle is very simple as illus(Source: Maxim. chip supplied in a 1.to ing must be sufficiently high.8 tunately.net & www. the simplest possible example because datasheets or application notes. It has an ultra-minimal know the basics. So. That’s why DC/DC controller is the easiest part of 1. but two other I’ve only presented a simplified calculation method for one topology. meaning 1 + 0. Look at the fordiode. which means it will heat up I will be honest with you: this was will usually find formulas in the and the converter’s efficiency will drop.) switching frequency is a good trated on Figure 7. If small as possible. which terms of EMC. Take out your microscope! their maximums. But this is not the diode for most designs. and its ripple current ratFigure 8—This is the full schematic of a 5. replace the diode with a second MOScomponents count and a fully integrated the worst case is when the input voltFET for higher efficiency. I think the inductor. you now called synchronous converters that the TPS62231. in this column. Unforresistance) and the diode D1. Therefore. and that’s why you will find sothe latest ICs from Texas Instrument.4 A in this example.8-V. and it which is edited by Marty Brown. This diode shows the full schematic of a 5 V to 1. at the switching freinductor will have a smaller tions of the input voltage and value for the same output cur. This will higher output current calls for also make your life easier in a lower inductor value. A common error is the last 10 years. For a buck converter. as hundreds of kilohertz to megahertz in plenty of excellent chips are available current above 1. A higher value ject of DC/DC converters. as the tions—current mode PWM. The best techcan be implemented on less than 4 mm × 3 mm ticular. Refer to Maxim’s application note APP2031. dt will be lower. As an real life. you must check what will the transistor (meaning low RDSON example. you DC/DC converters have moved from must select an inductor with a saturation the job when designing a converter. neglecting the itate to browse through the websites of current ripple and using only the output the key suppliers so you can see how current.quency. You saturate.4 = inductor will be smaller. you also you will probably understand more eascurrent were supposed to be fixed. which both the input voltage and the output When it comes to efficiency. Anyway. increase di. tively isn’t a good place for low-cost around a TPS62236.June 2010 – Issue 239 2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:28 AM Page 60 important. will help.Journal-Plaza. It is IDC + IAC. whatever the variaworks.5 × 1 mm SON age and output current are both at you’ll need to select a fast Schottky package. (Source: Texas Instruments) know that DC/DC converters are low-ESR electrolytic capacitors may be 60 CIRCUIT CELLAR® www.net • www. I also encourage you to read the minimized. but by Sanjaya Maniktala titled “DC-DC ic capacitor (MLCC). interconnect the transistor. but adding in parallel a if you need to design a conlower-value ceramic capacitor verter with a higher output helps a lot to keep the ESR as current? IDC will increase. output capacimula again. of course. It defini.WorldMags. First. Tantalum capacitors or capacitors and high-quality inductors will make it work. In particular. buck conparameters are even more critical: the verters.book Power sources and Supplies: 1. It can’t be simpler. The PCB routing is also critical to you want to keep a constant achieve good performance. It is only switched off when the output voltage reaches the prelosses in the components. briefly touched on the interesting suboutput voltage ripple.com .circuitcellar. Ceramic Converter Design and Magnetics. what happens used. I have only ated with DC/DC converters—namely. In parelectrolytic capacitors. which happen in worst-case scenarios. you will sure to use short tracks to need to increase IAC—that is. defining the worst case may is usually the major source of efficiency V/500 mA converter made with one of not be trivial because it depends on the loss. This means that a tor. which provides the selection of the components is key. I’m sure you will be able to output capacitor’s equivalent serial work out the other topologies by yourresistance (ESR) must be drastically self. converter topology. 500-mA step-down buck converter built World Class Designs (Newnes. which solution to reduce the PCB shows one of the usual solureal estate needed for a converter. check out the excellent chapter nology is usually a multi-layer ceramof PCB surface with all these components. the inductor will REAL-WORLD CONCERNS integrated these solutions can be. This component is key to reducing You also need to take care of the CONVERTER USE one of the most notable problems associmaximum current circulating in the Of course. Furthermore. rent. if you decide to You’ll probably need to increase the converter freimplement a closed-loop conquency. case for all converters. In that case. may not be intuitive. In any case. 2007). that offer zillions of features. In need to select low-loss components for ily after reading this article. Be current ripple ratio r. Last but not least is the output capacitor. take a look on Figure 8. Don’t hesto undersize the inductor. The set value when the current through the inductor starts to be too high. and ground plane. com. 2007.com /app-notes/index. 2009 With the proper analysis. France. a step-up DC-to-DC converter. The inverter was built using a control board and software based on an MC-1 development board. But they are really marvelous tools that should be in every engineer’s tool bag.com/magazine/229. I Robert Lacoste lives near Paris. Inc. Robert started a consulting company.net & www.net . 2001. Brown (editor). you can use any small high-voltage transformer. Induction. especially when they aren’t properly engineered or when integrated in noise-sensitive designs.circuitcellar.ti.circuitcellar. Power Sources and Supplies: WorldClass Designs. You can’t ignore them.maxim-ic.” Application Note 2031. “DC-DC Converter Tutorial.” AN513/0393. For more need-to-know information about topics covered in Robert Lacoste’s Issue 239 article. 1999.html — A Blast for the Past High-Voltage DC Dosimeter Charger by Ed Nisley Circuit Cellar 229. informed engineers and programmers don’t just survive. Snubbing. ALCIOM. Gate Driver. Topics: Dosimeter. analog designs. And I hope they are no longer on “the darker side” for you. and more. He has 20 years of experience working on embedded systems. | www. L. Circuit Cellar 217. 2008 You can build an electric vehicle (EV) inverter. DC Go to: www. Topics: Inverter.WorldMags.Journal-Plaza. RESOURCES M.circuitcellar.com NEED-TO-KNOW INFO www. Maxim Integrated Products. EV Go to: www. In the computer applications industry.mvp/id/2031. and wireless telecommunications. et al.com • 61 CIRCUIT CELLAR® www.2106005_lacoste post FE for PP_Layout 1 5/12/2010 11:28 AM Page 61 sometimes the sources of problems. You can reach him at rlacoste@alciom. CAN. SOURCES Knowledge is power. Charger. Don’t forget to write “Darker Side” in the subject line to bypass his spam filters. Wuidart. to share his passion for innovative mixed-signal designs.com/magazine/217.html June 2010 – Issue 239 TPS62236 Step-down converter Texas Instruments. He has won prizes in more than 15 international design contests. In 2003. ST Microelectronics. the Circuit Cellar editorial staff recommends the following content: — Electric Vehicle Inverter Design by Dan Hall. Ed covers transformer measurement. they thrive and excel. www. Newnes. “Topologies for Switched Mode Power Supplies. every time—or so the dream perpetuates. This article series is an excellent starting point. the Bulk. UARTs were an easy interface.circuitcellar. Many considered these divine in their simplicity. printer. we’re ready to go. For a developer. We plug it in and bing-bong. but can function with sporadic data errors) Data Error correction Guaranteed delivery rate Guaranteed latency Message Yes No No Stream Yes No No Stream Yes No Yes Stream No Yes Yes Table 1—While a USB device could get by using just Control transfers. camera. modem. “Make our lives easier!” The user drives the market. However there may be a little confusion with DB25s and DE9s. first time. Enumeration is the process of exchanging information that allows the host (connection manager) to learn about a connected device (peripheral). Although USB continues to evolve. connecting peripherals has become a nothought process. a lot of serial communication used an 8-bit data length with no parity and a single stop bit. it’s a different story.net & www. it must follow a rigorous enumeration process. No matter what the peripheral—keyboard. when I wanted to give my project user I/O through a PC connection.WorldMags. Interrupt. as a user. In fact.net • www. Once a device is plugged into the USB Transfer type Typical use Control Configuration Bulk Printer (Delivery time not critical. the OS will prompt you to supply one. If a standard driver does not fit the device. mouse. There are many device drivers that come standard with your OS (assuming it supports USB). In order for every peripheral to play through the standard USB connection. For more information on how a device driver is selected. 62 CIRCUIT CELLAR® www. and Isochronous methods have been implemented to guarantee specific requirements. but must get there without errors) Interrupt Mouse (Needs to be delivered in a timely fashion without errors) Isochronous Audio (Needs to be delivered on time. Every USB device will go through a number of states as it progresses through the enumeration process. I liked using the serial and parallel ports.2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 62 F ROM THE BENCH by Jeff Bachiochi (USA) Application Communication with USB (Part 1) The Enumeration Process Explained Consumers understand how to use USB technology. like tying a shoe lace. I think we could have come up with a smaller connection form factor to keep laptop manufacturers happy. the host can determine which kind of device is attached and find the right driver to load for that device. Plug it in (a driver might have to be selected once) and then it just works. I suggest you pick up a copy of Jan Axelson’s USB Complete.Journal-Plaza. It begins with an “unattached” state. but users seemed to be shouting.com . not to mention their s…e…x. it was as easy as 8–N–1. we have the universal serial bus (USB). or bulk storage—it’s all the same. Developers must understand how it works. I June 2010 – Issue 239 n the past. By asking the right questions. And so. For the user. Here you learn how a USB device goes through a number of states as it progresses through the enumeration process. You could pretty much rely on using this default and connection was assured. it’s (pretty much) plug and play. and isochronous. so I won’t discuss connection speed or 5 4 Single Packet Transfer Ended Zero Disable 3 USB module enable packet timing here. To start the enumeration process. Multiple transactions are necessary when all the information won’t fit into a transaction’s fixed capacity. data. no parity). the device is now in the “configured” state and ready for application communication. However. one for each possible endpoint.com • June 2010 – Issue 239 Transfer type Stage 63 CIRCUIT CELLAR® www. 1 stop bit. configure how the endpoint is used.net & www. but concentrate on the transfers themselves. TRANSFERS RS-232 communication consists of a single type of transfer. The host can apply power to the device if necessary and the device enters the “powered” state. taking the place of its default address of 0. where an application passes data back and forth between devices at a prearranged protocol (normally 8 data bits. Now the device is in the “addressed state. each newly attached device must default to a control pipe with an endpoint of 0. bulk. our requirements have been simplified by the introduction 2 Resume Enable 1 0 USB Suspend — UCFG Eye Pattern OE Monitor — Enable Enable On-chip Pull-ups On-chip Transceiver Full Speed Enabled Disable Enable PPB CFG1 PPB CFG2 USTAT — ENDP3 ENDP2 ENDP1 ENDP0 Transaction Direction Transaction PP Bit — UADDR UFRML UFRMH UEP0 D7 D7 — — D6 D6 — — D5 D5 — — D4 D4 — EndPoint Handshake Enable D3 D3 — Control EndPoint Disable D2 D2 D10 Output Endpoint Enable D1 D1 D9 Input Endpoint Enable D0 D0 D8 Endpoint Stall Indicator … … UEP15 — — — EndPoint Handshake Enable Control EndPoint Disable Output Endpoint Enable Input Endpoint Enable Endpoint Stall Indicator Table 3—The first two registers configure the SIE. and handshaking packets (except the Isochronous method).” Additional information retrieval takes place and if the process completes properly. USB communication has two types of transfers: configuring and Register bits 7 UCON — 6 Ping-Pong Reset message. and Status. with USB this configuration is handled by the host without user intervention. After retrieving some initial information from the device.net . None of this can happen without data being passed. Data (optional). In order for this whole idea of using a single interface for every peripheral to work.WorldMags. While a pipe is not a physical connection. The control transfer is the only transfer that can operate bidirectionally through its particular pipe or connection.circuitcellar.Journal-Plaza. Not are only configuration and message conversations taking place between the host and an attached device. the last 16 registers. The UFRMH:L register pair is used in isochronous transfers to monitor the present frame number. Every stage requires token. ENDP0:15. USB has multiple conversations happening simultaneously. I’ve discussed the electrical side of USB in a past column (you can find a list of my past USB columns at the end of this article). This is handled by the USB protocol. a data packet. the host must be able to somehow configure itself based on what gets plugged in. A device must know whether the configuration or application data being passed is for itself or another device. The USTAT register reflects the state of a four-deep FIFO keeping track of transactions. interrupt. www. The handshaking phase is not required in an isochronous transfer since there is no error correction.2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 63 Control Setup Phase Token Data Handshake Data (in or out) Token Data Handshake Status Token Data Handshake Bulk Data (in or out) Token Data Handshake Interrupt Data (in or out) Token Data Handshake Isochronous Data (in or out) Token Data Table 2—The Control transfer is the only transfer method that consists of multiple Stages: Setup. It is sufficient to say that USB communication uses one of four transfer methods: control. it is an association between the host and a device’s endpoint. The host will use this default address to communicate with this new device and begin the enumeration process by requesting information. UADRR is an assignment for future communications by the host once the device has been enumerated through a default assignment of ADDR=0. and a handshake packet (see Table 2). As a developer. So let’s start out with a look at the transfer process. all USB communications must use the control transfer to make use of the predefined functions (in the USB specifications) and perform the enumeration process. Each transaction will have an associated pipe or Endpoint 0:15 and will indicate the direction of the transaction Setup/Output or Input and a ping-pong bit (which I’ll skip over for now). all over the same wires. Finally. where the user was originally responsible for the configuration of the connection by setting up both UARTs to the same protocol. Table 1 shows typical uses for these transfer methods. bus. most consisting of a token packet. So. it enters the “attached” state. To be able to share the bus with all devices. A transaction can have multiple stages. but potentially multiple devices. the host assigns the device its own unique address. all information to be transferred is broken down into one or more transactions. Refer to Figure 1 for the three stages of a control transfer. Then the enumeration process begins From host From host To host SETUP Token Data ACK From host To host From host IN Token Data ACK From host From host To host OUT Token Empty data ACK USB Reset URSTIF June 2010 – Issue 239 Start-of-frame SOFIF with the first transfer labeled “Get Device Descriptor.net • www. I used a protocol analyzer made by Total Phase called the Beagle USB480. SET. many microcontrollers contain a USB peripheral that handles all of the USB bus interfacing.WorldMags. and it begins with the Standard Device Descriptor. Note that each stage (setup. Each transaction ends with the SIE setting the Transaction Complete interrupt.com . been using. Enumeration gathers the parameters that describe the device. READY. Most of the action taking place during enumeration will be from either the USB Reset or the Transaction Complete interrupts. I will be using the interrupt mode (as opposed to polling) for this project. and handshake). and status) of a transfer consists of three transaction phases (token.2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 64 of some special hardware. the host issues a control transfer. This support takes care of the hardware and its associated bus issues and leaves you to deal with the actual packets. I’ve used a total of three endpoints. Here the host is resetting the bus and checking the attached hardware to determine what bus speed to use for communications. I’ve listed them in Table 3 so you can refer to them while we discuss the code developed for this project. To monitor USB traffic between the host and the device. data. so most of the work will take place in response to USB interrupts set by the serial interface engine (SIE). Using an analyzer helps you keep track of the communication packets and helps determine what your code is reacting to.” The enumeration process is like reading the device’s datasheet.net & www. and the information presented here may be specific to this manufacturer.circuitcellar. CIRCUIT CELLAR® www. These include the default. data. The control transfer shown here is only an example showing events that can occur for every transaction. an input endpoint1 (configured for interrupt transfers). Photo 1 is the Beagle’s datacenter view of USB activity when I plug my project into the bus through the analyzer. I’ve broken down the registers associated with the SIE into two groups: the control/status and the interrupt registers. Typical control transfers will spread across multiple frames. This project has just been plugged into the USB bus and is beginning an enumeration sequence. The interrupt registers are divided into status and error interrupts (see Table 3).Journal-Plaza. let’s consider the hardware setup I’ve Photo 1—This view of the Total Phase Data Center application shows the logging of USB events that have been captured by the Beagle USB 480 protocol analyzer. To retrieve this information from the newly attached USB device. Note the top two green entries. the procedural outline should be similar for any micro depending on the implementation of its USB peripheral. SAMPLE Before getting into the actual code. control endpoint0. While this project uses a Microchip Technology PIC18F4450. SIE Today. and both input and output endpoint2s (configured for bulk transfers). The control/status registers are basically used to configure the USB SIE. Figure 2 shows Set TRNIF Set TRNIF Set TRNIF Transaction Transaction complete RESET SOF SETUP DATA SOF STATUS Differential data Control transfer[1] 1-ms frame 64 Figure 1—USB communications will consist of 1-ms frames that can contain many transactions between a host and connected devices. Let’s begin with that first transaction—the setup stage. This product can capture all of the USB events that pass through it. This figure shows a potential sequence of three transactions that will complete a control transfer within a single frame. in this case 256 bytes in length (0x0400–0x04FF).2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 65 the packet protocol for each transaction phase on the USB bus. this could be 64 endpoints when using ping-pong buffers. endpoint. That’s half the allotted dual-port RAM. Remember that unlike the single data channel for RS-232 communications. The USTAT information refers to a special dual-port RAM area that the SIE shares with the micro.WorldMags. the SIE has also placed an entry into a 4-byte FIFO called USTAT. which is simply the complement of the lower nibble.net & www.Journal-Plaza. USB has configuration and messaging information that shares the same bus. and endpoint from the host. Table 4 shows the breakdown of the first byte of every transaction—the PID. After a specially formatted sync byte. www. endpoint 0b0000. or 128 registers. you are getting the first transaction received by the SIE (the next entry in the FIFO becomes available as soon as the Transaction Complete interrupt is cleared). receives the packet.com • point received and direction of the transaction. and CRC information (0x00 and 0x10 = 0b00000000 and 0b00010000 = address 0b0000000. and acknowledgement. Enables downstream bus traffic to low-speed devices. the host only knows about two: the default control pipe to endpoint0. Each transaction from the SIE uses a set of four registers. The 0x2D PID (Packet Indentifier Field in the highlighted transaction in Photo 1) indicates a setup token. The remaining 128 bytes of dual-port RAM would be used as buffers for each of these endpoints. The Transaction Complete interrupt is raised and it’s up to us to do something with it. which at this point is only the default control pipe between the host and endpoint0.023 bytes (full)/1. data. will use a total of five endpoints. that’s the PID. You can see that space is at a premium here. At this point. This information came from the 3-byte setup token (highlighted in Photo 1). In fact.024 bytes (high) When you read USTAT. The following two bytes hold address. So where does this transaction end up? Handshake Special ADDR ENDP CRC EOP 8 bits 7 bits 4 bits 5 bits N/A SYNC PID CRC EOP 5 to 16 bits N/A DATA 8 bits (low/full) 32 bits (high) 8 bits SYNC PID EOP 8 bits (low/full) 32 bits (high) 8 bits N/A Up to 8 bytes (low)/1. Data PID Figure 2—Here are the three transactions that form a control setup transfer: setup. This area is used for passing all of the data that moves through any established pipe. each packet begins with a PID byte. in this case endpoint0 and setup/out (bit 7 of the PID).circuitcellar. and indicates when it is complete. and an output endpoint (EP0Out). USTAT holds the last end- PID Name OUT PID<3:0>* 0001B Description Address + endpoint number in host-to-function transaction IN 1001B Address + endpoint number in function-to-host transaction SOF SETUP 0101B 1101B DATA0 DATA1 DATA2 0011B 1011B 0111B Start-of-frame marker and frame number Address + endpoint number in host-to-function transaction for SETUP to a control pipe Data packet PID even Data packet PID odd Data packet PID high-speed. address. and crc 0b1000) as in Figure 2. as previously mentioned. That is a potential use of 32 × 4. This project. DUAL-PORT RAM PID Type Token SYNC 8 bits (low/full) 32 bits (high) 65 CIRCUIT CELLAR® www. which has an input endpoint (EP0In). one set for each of the possible endpoints— EPIn0:15 and EPOut0:15. high bandwidth isochronous transaction in a microframe MDATA 1111B Data packet PID high-speed for split and high bandwidth isochronous transactions ACK NAK 0010B 1010B Receiver accepts error-free data packet Receiving device cannot accept data or transmitting device cannot send data STALL 1110B Endpoint is halted or a control pipe request is not supported NYET 0110B No response yet from receiver PRE 1100B ERR 1100B (Token) Host-issued preamble. The SIE recognizes the first transaction as a setup token. but we won’t discuss this option here. Referring to Figure 2. The PID (see Table 4) determines the data that follows. Part of the design process is to allocate 4 bytes (BDs or Buffer Descriptors) for each endpoint that will be Table 2 doing a June 2010 – Issue 239 Besides setting the Transaction Complete interrupt. thus holding its own checksum. This area will eventually be used for two purposes: operational information and data.net . (Handshake) Split Transaction Error Handshake (reuses PRE value) SPLIT 1000B (Token) High-speed Split Transaction Token PING 0100B Reserved 0000B (Token) High-speed flow control probe for a bulk/control endpoint Reserved PID Table 4—The PID value is made up of the lower nibble above and an upper nibble. Interrupt conditions are revealed via the *IR registers. BDnSTAT. This method simply marks each packet using the data toggle bit that is flipped after each use.7 when it is finished. Since the endpoint allocation is 4 bytes for each endpoint. When the SIE hands you these buffers (BDnSTAT. and endpoint2. endpoint1. UEP0:15 defined if and how each of the endpoints will be used. as you can see in Figure 3. signalling that there is stuff there for the user.WorldMags. data toggling is implemented. since it isn’t enabled. In this project. If a packet is missed. it’s up to the designer to decide if and how the remaining endpoints will be used. can be a little confusing as it has a multiple purpose.7 = 1. It then sets up the BDs for the default control endpoint0 (BD0. The size can vary by endpoint and is defined in the Descriptor Tables. The associated BD for EP0Out is BD0. BDnADRH:L (where n = 0-32) form an address pointer to USBnB (USBn Buffer) where the endpoint data will be found. Beginning with the last 2 bytes. If you are clever you may have noticed (from Photo 1) that a USB Reset had occurred prior to the Get Device Descriptor request. the SIE owns the endpoints’ RAM and the user should not alter the endpoints’ BDs or USBnB. EP0In). This tests every USB interrupt in registers UIE and UIR (referring back to Table 5) to see which USB interrupts are enabled and which needs servicing.5 along with peripheral and global enable (INTCON. When you finish reading from or writing to the BDs and USBnB. the SIE knows where each set of 4 bytes begins. This project uses five of the first six buffers. (The Descriptor Tables are the device’s datasheet. BD0ADRL. This includes the USB0:5 buffer address pointers for each BD. you will know what to do with the data in the USBnB! When you hand the BDs and USBnB back to the SIE. The SIE will release these to the user by clearing BDnSTAT. So assuming that the USB interrupts have been enabled via PIE2. and UEP0:15 registers. execution has been tossed to the interrupt routine. we’ll get to these later on. and USB3 and USB5 will be 64 bytes in length. The four BD0 registers—BD0STAT. The size (length) of this Figure 3—The four byte groups of Buffer Descriptors have predefined locations in the dual-port RAM. In this project.circuitcellar. For now we are interested in only two: Transaction Complete and USB Reset.7:6). the BDnSTAT holds GET ON WITH IT The data we found in USTAT tells us that we are dealing with EP0Out.com . BD0) of the dual-port RAM with EP0In following at 0x0404 (BD1). the BDnSTAT holds the received token’s PID (Packet IDentifier). Bit1 of the Status Register is a global Enable and Status bit of the Error registers. and our routine clears out the FIFO.Journal-Plaza. data toggling will be out of sync and the packet can be rejected. With this value. bit 7 of BDnSTAT is a semaphore flag used to indicate who owns the BD and USBnB. Since the dual-port RAM can be accessed by the SIE and the user application. UADDR. The USB Reset interrupt requests this. so it will begin by putting a device into a known state by requesting a reset. EP0Out is placed at the first byte (0x0400. 66 CIRCUIT CELLAR® www. As a means of making sure that stuff is passed back and forth between the host and the device correctly. indicates the actual count of pertinent data in the buffer. Their ADRH:L registers are used to define the actual data buffers used by each enabled endpoint. BD4 (EP1In) is not used. Referring back to Table 3. The rest of the BDnSTAT bits take on different meanings depending on who owns the BD’s dual-port RAM. All RAM after the last enabled BD can be used for the actual buffers.net • www. Note that the BD4 registers are accounted for and are free RAM. When BDnSTAT. USB0-2 will be 8 bytes in length. BDnCNT. The first byte. The host will want a device to interpret its request correctly. BD0CNT. EP0Out and BD1.) The second byte. While the UEP0 register is the default control endpoint and will normally have bits D3:1 set.2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 66 BD0STAT 0x0400–0x0403 BD0CNT BD0ADRL BD0ADRH 0x0404–0x040F 0x0410–0x0413 0x0414–0x0417 BD1–BD3 BD4 BD5STAT BD5CNT BD5ADRL BD5ADRH 0x0418–0x041F USB0 Buffer 0x0418–0x046F USB1–3 Buffers 0x0470–0x04AF USB5 Buffer 0x04B0–0x04FF Free RAM Dual–port RAM June 2010 – Issue 239 used in your application. and BD0ADRH—beginning at address 0x400 have all we need to know to access the first transaction.net & www. Interrupt register bits Status UIR and UIE 7 — 6 Start of frame token 5 Stall handshake 4 Idle detect 3 Transaction complete 2 Bus activity detect 1 USB Error condition 0 USB Reset Error UEIR and UEIE Bit stuff — — Bus turnaround timeout Data field size CRC16 CRC5 PID Check failure Table 5—Any interrupt can be enabled via the *IE registers. The location of each endpoint has been predefined. no USB4 Buffer exists. some housekeeping information. buffer is defined during the design process.7 = 0). Each byte of the BD has an important function. you give it back to the SIE by setting BDnSTAT. The most important housekeeping item is the data toggle bit. net .POJ U PS  IJ HI  G VM M   BOE     M PX TQFFE 64# EBU B #FBHM F 64#  1SPU PDPM  "OBM Z[FS  t 3FBM  U J NF EJ TQM BZ XJ U I     EFTDS J QU PS  QBS TJ OH  t . so you use the USTAT register to determine which BD to service. This time it was the Get Device Descriptor request that set the Transfer Complete interrupt.D0: Recipient 00000=Device 00001=Interface 00010=Endpoint 00011=Other 001xx-111xx=Reserved Specific request 0=Get_Status 1=Clear_Feature 2=Reserved 3=Set_Feature 4=Reserved 5=Set_Address 6=Get_Descriptor 7=Set_Descriptor 8=Set_Configuration 9=Get_Configuration 10=Get_Interface 11=Set_Interface 12=Synch_Frame Word-sized field that varies according to the request.2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 67 Offset 0 1 2 Field bmRequestType bRequest wValue Size (bytes) 1 1 2 Following the flow of USB activity based on the Beagle’s logging (back in Photo 1).POJ U PS  G VM M   BOE M PX     TQFFE 64# EBU B 7J T J U  U IF M J OL CFM PX G PS  B T QFD J BM  QS J D F XXX U PU BM QIBTF D PNPG G FS $$ Number of bytes to transfer if there is a Data stage Table 6—The USB Device Request might be the most informative group of information transferred via USB. a control endpoint using setup.WorldMags. all of the USB interrupts are cleared and you exit the interrupt routine. and out transfers.Journal-Plaza. The first byte completely describes how the request should be handled while the second byte defines the request. Typically used to pass an index or offset #FBHM F 64#  1SPU PDPM  "OBM Z[FS  t 3FBM  U J NF EJ TQM BZ XJ U I     64# DM BTT M FWFM  EFDPEJ OH  t .circuitcellar. The BD’s four bytes Value Bitmap Value Value 4 wIndex 2 Index or Offset 6 wLength 2 Count " 64# &OHJ OFFS T #FTU  'SJ FOE 5 PU BM  1IBTF 64# BOBM Z[FS T G FBU VS F S FBM  U J NF EJ TQM BZ BOE mM U FS J OH PG  M J WF 64# EBU B Description Characteristics of request: D7: Data transfer direction 0=Host-to-device 1=Device-to-host D6. The endpoint control UEP0 is configured for the default.com • * $  41*  BOE $"/ U PPM T BM T P BWBJ M BCM F * OEVTU S Z M FBEJ OH  FNCFEEFE TZTU FNT U PPM T June 2010 – Issue 239 the third and fourth bytes of each BD (BDnADRH:L). Finally. You don’t know what the request was yet. 67 CIRCUIT CELLAR® www. UEP1 will be output (interrupt) transfers only and UEP2 will use both in and out (bulk) transfers.. www.. for descriptors 0x0100=Device 0x02xx=Configuration 0x03xx=String 0x0400=Interface 0x0500=Endpoint 0x0600=Device_Qualifier 0x0700=Other_Speed_Configuration 0x0800=Interface_Power Word-sized field that varies according to the request. execution has been directed again to the interrupt routine.D5: Type 00=Standard 01=Class 10=Vender 11=Reserved D4.net & www. in. Luckily. “Embedded USB Breakthrough. You can reach him at jeff.microchip. These eight bytes in the USB0Buffer are moved to another set of working registers (so we won’t need pointers anymore to access them).zip. We’ve already determined that we need to service the GetDescriptor. I encourage you download a copy of the “Universal Serial Bus Revision 2.2. This is based on the first byte of the data phase (BMREQUEST. 2008 Get started with USB. ———. In addition. 2004. Table 6 shows the format of the USB Device Request.” USB devices have been grouped by function into classes. WI. they thrive and excel. “Create a USB Hybrid Hub. we need only three: device.” Circuit Cellar 165.totalphase. Inc. We branch to the ProcessSetupToken routine to continue this interrupt service. You then clear the packet-transfer disable that is set by the SIE when a setup token is received (UCON. Of particular importance is Chapter 9 as this is the essence of communication and enumeration.7 = 1). configuration. Referring back to Photo 1.com or at www.PKTDIS = 0). each request doesn’t use all of the possible types. OTG. RESOURCES J.” Circuit Cellar 200. The lower byte will be zero unless there are multiple configurations or strings.. It should be a USB Device Request of eight bytes. “Accessing the USB Framework. Lakeview Research. 2nd ed. embedded hosting. www. This is the first item in a device’s datasheet. Within the Standard Descriptor branch there are 10 types of requests (offset 1 in Photo 1). USB0Buffer holds the data phase of the setup stage. www.2_WM C1. ———. 2007. and out (see Table 2 and Table 4). Keep this column handy. Next month. USB Implementers Forum. HNP Protocol.bachiochi@imaginethat now.usb. Topics: USB. For more need-to-know information about topics covered in Jeff Bachiochi’s Issue 239 article. the second byte in the data phase of the setup stage is GetDescriptor (0x06) and the host is requesting 0x40 characters. in this case it is a Standard Descriptor. This Transfer Complete interrupt routine will be handling three of the four token PIDs possible in a control transfer. | www.usb.com Beagle USB 480 Protocol analyzer Total Phase. in which case this will indicate an array index.” Circuit Cellar 165.zip.net • www. informed engineers and programmers don’t just survive.circuitcellar. Class Definitions for Communication Devices 1. Jeff presents MCUs with USB peripheral support. We’re through processing the USB0Buffer. setup. I Jeff Bachiochi (pronounced BAH-key-AH-key) has been writing for Circuit Cellar since 1988. “USB in Embedded Design Part 2: HIDmaker Converts an Application.1. the “2” is just D’s complement). 2004.com/magazine/219. ———. Axelson. Inc. Since this project’s USB device is of the communication class.0” specification. you might wish to look through the requests and notifications that are specific to this kind of device. The value 0x2D tells us we need to service a setup token (actually it’s the “D” that indicates the PID. 2004. and BD0CNT indicates how many characters are significant. USB Complete: Everything You Need to Develop Custom USB Peripherals.2.usb. BD0ADRH:L shows where to find the USB0Buffer. | www. J. In the computer applications industry.June 2010 – Issue 239 2106002-Bachiochi-3 Post FE for PP_Layout 1 5/12/2010 11:51 AM Page 68 plus the USTAT register are moved into a set of working registers to make them easier to interrogate. SOURCES PIC18F4450 Microcontroller Microchip Technology. Madison. as there is much to refer back to next time. in.0 Specification. 2006. We now know that the host is requesting a GetDescriptor transfer and that we need to send the Standard Device Descriptor. His background includes product design and manufacturing.6:5).org/developers/devclass_docs/CDC1. and more. For this project. however there are eight possible descriptor types (offset 2 in Photo 1). I’m hopeful this project will help you to wade through the USB specifications and locate those parts that are meaningful to your particular design. ———. 2001.circuitcellar.WorldMags.org/developers /docs/usb_20_122909-2.” Circuit Cellar 195. Bachiochi. download the “Class Definitions for Communication Devices 1.org. TPL Go to: www. This action signals the SIE that we’ve serviced it. we’ll look at this and the other items that make up the datasheet (or USB Descriptors) for this project.com.” Circuit Cellar 172.com NEED-TO-KNOW INFO Knowledge is power. so the BD can be released to the SIE (BD0STAT. 2004.html 68 CIRCUIT CELLAR® www. www. the Circuit Cellar editorial staff highly recommends the following content: — Get Started with PIC USB Connectivity by Jeff Bachiochi Circuit Cellar 219. in this case it is Device Descriptor (0x0100). “USB in Embedded Design Part 1: The Undeniable Benefits. BDSTAT holds the PID that determines which of these to service. The upper byte of the wValue in the data phase indicates the descriptor type. and string descriptors.com . ———.imaginethatnow. Now we need to make a branch to handle the type of descriptor request.Journal-Plaza. “USB DMX.” Circuit Cellar 170. USB Revision 2.net & www. Now Atmel says it’s time to rethink the obvious.e. So let’s get started.e.e. the power supply specification only allows for 20 mV of combined noise and ripple. which is rather strict. and the like? These are invariably constrained in terms of silicon. etc. silicon and software) under the hood. Atmel hopes to enable the proliferation of touch into virtually any and every application. The newest gadgets in a road warrior’s quiver take the touch concept even further with multi-touch and gesturerecognition capabilities. measuring touch pressure) and haptics (synthesized tactile response) make their way from the lab to your pocket. a range that accommodates practically any application. MP3 players. And that means every designer needs to take a closer look. is pretty darn low. relatively speaking.net & www. However. 1-BIT WONDER With just six pins. However. The question for touch is how low it can go.circuitcellar. And. ranging from tens to hundreds of microamps depending on the sample rate and supply voltage. using a cheap wall wart. inexpensive. with 32-bit processors and gigs of memory. discerning a few picofarads of touch capacitance quickly and reliably in a variety of changing conditions. They’re full-blown computers in drag. The answer. How many switches get sold every year? Wow. lowpower chip. Starting with the power supply. And progress won’t stop there as features like force-sensing (i.net ..8 and 5.2106003-Cantrell2 Post FE for PP_Layout 1 5/12/2010 11:59 AM Page 69 S ILICON UPDATE by Tom Cantrell (USA) Pitch the Switch? The basic design of the mechanical switch—two conductors and a contact—is hundreds of years old. have no shortage of horsepower (i. software. the new Atmel chips (AT42QT1010. consider using a dedicated supply June 2010 – Issue 239 C 69 CIRCUIT CELLAR® www.. quickly and precisely measuring an exceedingly small change in capacitance). but for now here’s the basic description that applies to all of them. If in doubt. and power consumption. keep the spec in mind if you’re switching high-current loads.. that’s a big number. More on that subject later. they have large battery capacity and bill-of-materials budgets to work with. The bad news is a sophisticated high-resolution touch interface requires a lot of processing behind the scenes. the ’101x runs on anything between 1.WorldMags. But what about really simple blue-collar apps Figure 1—The Atmel ’101x single-key touch chips are easy answers for a surprisingly tough problem. The pinouts even look the same (see Figure 1). by now everyone gets it that touch interfaces are the way to go for devices like cell phones. appliances. www. ’1011. and PDAs.5 V.Journal-Plaza. such as Apple’s iPad.com • like toys. They’re introducing a line of single-key touch solutions that distills practically everything involved down to a tiny. handheld meters. The good news is that the latest-and-greatest devices. and ’1012) are blessedly easy to describe. according to Atmel. although each works slightly differently. The good news is that power consumption is negligible. The tight spec is understandable given the task at hand (i. Is it time to pitch the switch? ontinuing last month’s theme. localized interference. The SYNC pin defines the sample mental and use factors such as water and a few discretes? Indeed. narrowerally sticky situation of a “stuck when you can roll your own touch band interference. OUT heartbeat feature (i.net • www. By adding a pullin. OUT is don’t need the feature (i. but hopefully. sampling at Figure 2—There are a lot of clever ways to implement a lishment that superimposes a “heartexactly 10 Hz would capacitive touch sensor. battery) or regulator to avoid now’s the time to start talking about amiss. tivity. head-scratching down the road. while slow mode introduces an 80-ms delay. If you use the the key electrode via an external resis. That could be useful to counter interferPhoto 1—Homebrewing your own touch sensor is easy. some software.. SYNC can be clocked to explicitly control the sample timing. etc.circuitcellar.Journal-Plaza. You’ll need more hardware and/or up resistor to OUT. The ’1010 has libraries (including Atmel with their selects built-in “fast” or “slow” saman automatic 60-s timeout after which “QTouch Library”) that implement pling. VDD HOLD HOLD June 2010 – Issue 239 SENSORn 70 CIRCUIT CELLAR® www. slower for increased sensi. most of timing with three options to choose film buildup. Even if you tum a few years ago. and tolerates more.e.e.e. monitoring logic It all comes together software to deal with the vagaries real-world applications. works is that the normally push/pull interference (e.g. the value of the latgoes high.e.. otherwise “quiet” VC ANx INPUT – C What if the chip gets zapped and times (e. key.The ’1011 has no timeout.com . The way it help counter any mains borrows the ADC sample-and-hold capacitor (T. The get around the tight ’1012 goes further with a selectable power supply noise timeout delay (15 min or 1 h) or the spec by sampling at ADC + option to disable timeout altogether. faster with higher sensed capacwould make sense for an application Handling touch with an MCU itance. Fast mode is essentially continua) b) ous (only 1-ms pause between samples).2106003-Cantrell2 Post FE for PP_Layout 1 5/12/2010 11:59 AM Page 70 like automatic power control of a you might be able to hearing aid or Bluetooth headset. The ’1010 and ’1011 act like a that’s not too clever. you’ll be getting a lot of pulses to deal with above and Acquired with the purchase of Quanonce touch is removed). which dard MCUs.” AN1298. and stays high. touch is detected and then returns low resistor to OUT).” which can occur due to environsensor with an MCU. 50/60. rather than big fixed-frequency ones. no touch)? you’re switching a C How would you know there’s a probnearby LED). the beyond actual touches.. However. Peter. unique by virtue of using multiple (i.g. The ’1012 is also unique in that ed to doesn’t glitch when the input floats for 15 µs. add a pull-up tor and capacitor. as long as ter setting the overall sensitivity...momentary push button (i.. Holding SYNC high or low inadvertent touch. It’s the OUT polarity can be configured heartbeat palpitations..net & www. How does that work? ence. 2009). Atmel’s charge’1012 is like a toggle switch. Here’s a clue: touch a scope probe (b) and what do you see? A little experimentation never (60) Hertz. not when OUT gets stuck low (i.WorldMags. one The SNS and SNSK pins connect to chips. Along the lem? The answer is a failsafe embelsame lines. Actual response it will turn off OUT and recalibrate.g. the major touch players offer software from. can look for the heartbeat pulses to at the OUT pin and determine whether something is badly (e. capacitive touch-sensing on their stantime varies. Just remember that the basic each sample period. no pull-up). as in this Microchip example that beat” on the OUT pin. “Capacitive Touch Using Only an ADC (‘CVD’). respectively.. a Another difference between the FICKLE FINGER spread-spectrum technique that generchips is the way each handles the litWhy bother with a separate chip ates less. Instead of using the built-in “fast” and “slow” options.e. lest your design suffer approach and touch the electrode. Just hang a wire on an ADC (a). sensor is only the start. OUT pin is briefly (15 µs) tristated 100/120 Hz) creeping Microchip Technology. the differences between the three It’s a clever idea. transfer scheme is able to discern the asserted upon touch detection and make sure whatever OUT is connectminiscule (a few picofarads) uptick in remains that way until a subsequent capacitance that occurs when you touch. For example. active high or active low) using small time-varying charge pulses an external resistor. Perme and D. Not to mention way more time spent testing and tuning than you might imagine. When I added a single PRINTF statement to disnately.685 the room. Take multiple samples to filter out glitches before confirming a touch event. but don’t be afraid to think outside the box.” you can use a more finessed Table 1—Enabling a wide range of applicathat knows what it is doing.2 16. measurements of voltage and time. Automatically calibrate the sensor at power-up. And even if power isn’t a concern.024 ent that there is virtue in getting a the way. And each KD02.181 sensor out of the water. FortuWrong. 2009) describes a scheme that works with any of their MCUs by devoting a couple of pins and an ADC to the cause.8 7.the sensitivity. overhead which will consume enough power to be noticeable in battery-powered apps.net . more interrupts. just what the world that’s exactly the wrong thing to do FR-4 5. Microchip application note AN1298 (“Capacitive Touch Using Only an ADC (‘CVD’)”. accepted pracLexan 2.WorldMags.717 turned on the microwave oven across ground plane for noise isolation.874 same time.” AN. Provide a measure of hysteresis to prevent output chattering (i. Don’t overlook that in your makeversus-buy calculus.. it takes more than a few lines of toy code to deal with the harsh facts of real-life applications. But. All you need is a few lines of code to check for the designing the electrode itself. Photo 1 shows my poor-man’s touch sensor in action. more cycles. Atmel has a couple of excellent application notes play the ADC reading. you’re going to have to fire up the entire MCU just to sample the touch key. but oh so critical. and recalibrate if necessary.e. so Mylar 3. details. continually monitor for a “stuck key” condition. Plus. ty was enough to shift the level on the Refer to the Resources section at the Epsilon Breakdown V/mm pin and blow my finely crafted touch end of this article.8 17. it happened to start workTypically. drift compensation is a must for any real-world touch application. But Polystyrene 2.9 15. and in turn the usable since detecting a few picofarads of panel thickness (see Table 1). that was at least until I tice is to surround them with a big Polyethelene 2.0 295. there are answers to all these questions. when dealing with lowPyrex glass 4. Hey. voila..9 28. when laying out your electrode. One can only guess how much time Atmel’s engineers spent figuring out the devilish.Journal-Plaza. Considerations include the dielectric software required to roll your own without weighing it down.2106003-Cantrell2 Post FE for PP_Layout 1 5/12/2010 11:59 AM Page 71 seems easy enough. Yes.189 ing as a pretty decent proximity senlevel signals on a PCB.0 1. alternatively. The fact is. Allow me pass some Air 1.543 seems easy at first. which affects ed from the Quantum Research Group’s should be relatively high-performance “Secrets of Successful QTouch Design. but the more you a touch as a change in capacitance. the chip is trying to sense PVC.circuitcellar. touch sense solution is nontrivial.370 helping hand from a dedicated chip “plane. you need an analog function (i. The discharge time will lengthen with the increased parallel capacitance on the electrode due to a touch.2 27. we don’t need no stinkin’ itive. rolling your own touch sensor is one of those things that’s easy to do…poorly. It’s just a piece of wire connected to an ADC.717 You get the picture.e. It just keeps snowballing: more code. more power.6 19. touch capacitance requires precise material has its own breakdown voltage www.3 17. the extra activifull of practical design tips and tricks. rigid 2. But at the of them along. especially if you embelspecial chips! lish your design with add-ons like LED backlighting.com • June 2010 – Issue 239 Figure 3—No matter how good the sensor.559 needs—a microwave oven detector.8 13. 2005). there’s an even simpler way. A neat trick is using the ADC’s on-chip sample-and-hold capacitor so an external capacitor isn’t required (see Figure 2). most designers can probably come up with some more useful ways to burn cycles and juggle interrupts than babysitting a touch key. and aging drift of the electronics? Big versus small fingers? Of course. Automatically monitor and compensate for drift without interrupting normal operation (see Figure 3). in fact. just touching the DON’T ’TRODE ON ME wire will result in a quite noticeable jump in the ADC But there is one can-be-devilish detail left—namely. ground “ring” around the electrode tions. the voltage level reached at a fixed time after discharge. Just charge-up a capacitor connected in to the electrode and then discharge it to drain through a resistor. Touch sensing Remember.1 39. the more it becomes apparany other stray capacitance just gets in Nylon 3. 71 CIRCUIT CELLAR® www.net & www. converter or comparator) and a timer.276 dig into it. Instead of a big ground Teflon 2. constant (Epsilon) and breakdown voltage. and as much art as science. It can be a bit counter-intu“magic number”—and.748 sor! Well. a capacitive touch sensor can use The amount of MCU silicon and that will help shape the touch field any non-conducting material as a front panel. Plexiglass 2. You Different panel materials have their Here’s a list of the popular options (adaptneed an ADC and timer. Either way. Furthermore. Common glass 7. and both own dielectric constant. What about moisture or grime build-up on the electrode? Voltage. the equivalent of “debouncing” a mechanical switch). reading. Having it built-in is a big plus for the Atmel chips. temperature. You can either measure the time it takes to discharge to a predetermined voltage level or. g. too much moisture building up too quickly can trigger a false touch. I started with some tive foam.. Designs using larger multi-channel touch chips have the luxury of fighting back by using spare channels for strategically placed “wipe down” detectors or “driven shields. power supply hovering my finger over the key and and at least the 6 to 7 mm of a small (instead of the battery). bigger is better. and so on. unlike my “onechip. metal springs (see clear tape and worked up through Photo 2). OUT connection (instead of the chip enters the 80-ms sleep cycle). Just toss in a few discrete components and an electrode and poke away. front panel. with versions available for the experimentation with the EVK. the delay from getting zapped. switches (or jumpers) might be in order? That being said. the EVK1010A any switch are reliability and response providing protection against ESD. barely.. Specs and app notes are all (see Atmel’s “Touch Sensors Design Guide”) well and good. adding a touch switch isn’t a big deal with the Atmel ’101x chips. And even It’s important to establish a then. which makes for an easy and seeing if it works.g. using springs as the process of poking at the thing and electrodes. an issue ting traces.” But even with just a single channel. It Photo 4—Atmel has put a lot of work into the devilish front panel. By dimension of 4× the panel thickness LED on the board).e.Journal-Plaza. Touchto the electrode isolated from When it came to moisture sensitive furniture anyone? 72 CIRCUIT CELLAR® www. Genertrode (instead of the “Key” on the case (i. and even when I wore gloves.WorldMags. Even in always be insulated to protect the chip ’1011 and ’1012 as well.. clamping.ognizing a light touch. The good news is “single key’ not as easy as it could be though. The The discrete resistors and gloves (although I had to press a switch worked well with different front panel materials. ON/OFF LED behind the key). some form of user feedback is a must. gives designers the opportunity to get creative.g. prototyping easier than fumbling with between touching the key and the One of the neat features of touch the tiny chip itself. KEY TO THE I-WAY robust front panel connection. It may be window glass without a hitch. The EVK makes it easy to try with options such as doubledifferent panel materials (see sided tape.net • www. key touched right after the ally. pardon the is unambiguously apparent (e. Based on my admittedly ad hoc Speaking of which. and then only in the worst size is pretty much up to you. getting in touch with the techcally an LED or an audible click. Dare I suggest a few real likely in real-world use. but this was a that proves challenging in designs ing the connection when you change very contrived scenario and not at all with multiple tightly spaced keys your mind). Photo 3—As you can see. When dealing with tiny amounts of capacitance.com . contrary to that welldamp or dry.2106003-Cantrell2 Post FE for PP_Layout 1 5/12/2010 11:59 AM Page 72 June 2010 – Issue 239 everything (e. I was ultifinger. The versatility to the chip and the connection known objection. possible to get away with a sinAnd this was without changing gle-sided PCB that “backfires” any components or having to through the PCB itself and the power-cycle for recalibration. drift apps don’t have to deal with interfermaking changes generally requires cutcompensation algorithm) into not recence from nearby electrodes.. and it shows. matter. (see Photo 3). there are some things you can do to help moisture-proof your design. such as conformal coatings and packaging (think umbrella). I’m wire” hack. since mately able to spoof the chip (i. The app note discusses plenty of ways to do it. with a minimum board).. it should be bypassed with a small capacitor. the EVK is useful Photo 2—Unless actuation of a touch switch for kicking the tires and. even the details.e. It’s approaching very slowly. If there’s a switched connection nearby (e. simply pressing the key mechanically sound connection with a bit more pressure set between the electrode and the things right. It’s based on the ’1010 time.net & www. even kept working when I put on details (such as drift compensation). which is a pain (as is restor. flashlight). interfering signals. The EVK1010A makes experimenting and slow sampling mode. such as cleaning the PCB of any flux residue. on this EVK1010A board. The board offers LED illuminating was just barely persensing is that electrode shape and some provision to use your own elecceptible. typipun. capacitors should be kept close bit harder). conducPhoto 4). This design nology.circuitcellar. and so on. ground plane. Atmel sent me one of their cute litTwo fundamental requirements for tle evaluation boards. an electrode should impressed in both regards. but they can’t replace shows another neat trick. Despite the chip’s best efforts. and floating metal). You sure you want a power saw with a touch switch? So. 2009. That being said. board.com/ dyn/resources/prod_documents/an-kd02_103-touch_ secrets. Microchip Technology. You may reach him by e-mail at tom. The generic use of the term “switch” may contribute to unrealistic expectations and hype. Perme and D.com/downloads/en/AppNotes /01298A.net .pdf. RESOURCES Atmel Corp. But watch out. 2009. A touch chip and a touch of common sense are all it takes. Have you ever fumbled in the dark for a bedside lamp switch? Beyond simply “replacing” existing switches. by all means. I did go at it with a damp (and then dripping wet) finger. don’t overlook the fact that ever lower-cost and easier-to-use touch technology will also enable compelling “nontraditional” applications.net & www. FINGER FOOD FOR THOUGHT Tom Cantrell has been working on chip. We’ve all seen the travails of Toyota. T. the water made the EVK a little easier to fool—in this case. with some tape covering the key and tilting the board to drain (i. so to speak. I www. Nevertheless.com.com/dyn/resources/prod_ documents/doc10620. But again. big number. I had to go way outside the bounds of normal operator behavior to find even this tiny difference.com • 73 CIRCUIT CELLAR® www. www. put on your thinking caps and have at it.WorldMags. I can foresee a rush to dubious designs as everyone scrambles to get on the bandwagon (i. Really. “Secrets of Successful QTouch Design. touch for touch’s sake).atmel. To my mind. and systems design and marketing for several years.. away from the parts).” AN-KD02.” 10620EAT42.e. a “switch” should be capable of “switching” an actual connection.pdf. “Capacitive Touch Using Only an ADC (‘CVD’). “Touch Sensors Design Guide. the Atmel chip is kind of a 1-bit. recognizing a close (few millimeters) hovering finger as a touch. Can the Atmel chips replace them all? Not a chance. which were partly attributable to the fact that the company replaced the good old ignition key with an On/Off switch that really wasn’t.circuitcellar.e.” AN1298. Peter. Yes.. Quantum Research Group. www.Journal-Plaza..atmel.cantrell@circuitcellar. ww1.pdf.com June 2010 – Issue 239 One can only imagine how many mechanical switches get sold every year.2106003-Cantrell2 Post FE for PP_Layout 1 5/12/2010 11:59 AM Page 73 testing. there are no doubt “traditional” switch applications where a touch version could offer advantages. dual-port memory with a touch write port and digital read port.microchip. It’s a big. 2005. SOURCES AT42Q101x Single-channel capacitive touch switch Atmel | www.atmel. I didn’t want to go overboard. both literally and figuratively Cation charge Prevents overheating Can be tweaked post-manufacture [two words] Point of I/O Closes and opens contacts Old equipment Flowing water.circuitcellar. 10. 4. 12.com/crossword. 13. Niagara Falls A bundle of software updates [two words] TMS pin [three words] Down 2. 7. 9. April 2010 [two words] Flux removes Dopant Java’s character Plastic strip for data Semiconductor with impurities For wind velocity pH < 7 Common EMF Unit The answers will be available in the next issue and at www.circuitcellar.net • www. 15. 19. 5. 3. 17. Embedded Systems Conference. 11. 74 CIRCUIT CELLAR® www.WorldMags. 16. 8.Journal-Plaza. 18. 6. Purposely obscure your code to protect it Disconnect.net & www.crossword2_Layout 1 5/13/2010 12:38 PM Page 78 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 June 2010 – Issue 239 Across 1. 20. 14.com . com/advertise). PO Box 180.7708 or [email protected]. The Vendor Directory at www.us.ib-239_Layout 1 5/12/2010 12:09 PM Page 75 I DEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES AD FORMAT: Advertisers must furnish digital files that meet our specifications (www.com with your file or send it to IDEA BOX.com Mosaic Industries.com www.5”x4” C-programmable single-board computer Fast 16-bit Freescale HCS12 processor Ideal for data acquisition and control Embedded dynamic web server Email program-controlled messages from your instrument Plug-in modules for any kind of I/O. USB.net . E-mail adcopy@circuitcellar. For current rates. Inc. tel: 510-790-1255 fax: 510-790-0925 www. 978.com/vendor/ is your guide to a variety of engineering products and services. Vernon. including GPS. AC and DC relays. and more information contact Peter Wostrel at 800. and many more.net & www. Mosaic Industries Inc. deadlines. D/A. (510) 790-1255 June 2010 – Issue 239 http://www.circuitcellar. ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. Circuit Cellar.. CT 06066.454.mosaic-industries.3741. UART. A/D.281..WorldMags.circuitcellar.mosaic-industries.com • 75 CIRCUIT CELLAR® www. I/O-Rich SBC Supports Embedded Ethernet/WiFi O O O O O O PDQ Board with The PDQ Board Ethernet module a low cost 2. ib-239_Layout 1 5/12/2010 12:09 PM Page 76 63.  :LUH    .  .     T +I T & EAT UR ES ) NC L UDE N E M q & UL L S PEED 53"   I NT ER F AC E P O L E q 3OF T WAR E L I BR AR I ES S UPPOR T I NG () $ V E AND #$# C L AS S ES $ " 3 q %XAMPL ES I NC L UDE () $. BUL K MODE T R ANS F ER 5  VI R T UAL #/- POR T ¸ q $E V E L OPME NT +I T WI T H F UL L ) $% 0) # -#5 #OMPI L E R  ) #$ 5 0R OGR AMMER  $EBUGGER & June 2010 – Issue 239 % 3T AR T I NG AT  ! "# *" # * $ % &% # + % ' ( !)%" #!) %&" #OMI NG 3OON 0) # 53" $EVEL OPMENT +I T 53" 0) #& $OES NOT R EQUI R E DET AI L ED KNOWL EDGE OF 53" 0R OT OC OL WWW C C S I NF O C OM 53" -I C R OC HI P 4HI R D 0AR T Y 4 OOL 0R OVI DER S AL ES C C S I NF O C OM    X 0) #¸-#5 A ND DS 0) #¸$3 # A R E R E GI S T E R E D T R A DE MA R K S OF -I C R OC HI P 4 E C HNOL OGY . net • www.circuitcellar.WorldMags. ) NC  76 CIRCUIT CELLAR® www.Journal-Plaza.net & www.com . STMicroelectronics.com Phone: 630-213-8700 Fax: 630-213-0776 www. Atmel. AM3517 PowerPC: MPC5554.No flow pregpregs and dielectric thickness .circuitcellar. Z520. Combined with our design services. Rogers SPECIAL OFFERS! 2 LAYERS @ $11/ea 4 LAYERS @ $33/ea Mention Circuit Cellar when you buy and we’ll gladly send you a JTAG adapter—for free! June 2010 – Issue 239 RowleyAssociates. LPC3180 ARM11: i.9913 7XUQ\RXU3&LQWRD63. Visit us online or call today www. Debugger. i. your new ideas arrive to market in the most timely and cost-efficient manner.& 60%XVRU*3.ib-239_Layout 1 5/12/2010 12:09 PM Page 77 SHORTEN TIME-TO-MARKET REDUCE DEVELOPMENT COSTS AVOID DESIGN RISK ARM9: i.phytec. LPC3250.4mil laser drill ..278.3/3 line spacing hybrid & Teflon PCB . Proudly Presents.com • 77 CIRCUIT CELLAR® www. and many other microcontrollers Includes royalty-free tasking library Come and see what we have! Free Ground Shipping Stock Materials: FR-4tg 140-180.net .Same day to long lead availibility . Z530 (Atom®) Cortex A8: OMAP3530.MX35.1-24 layers .com Email us: [email protected].. TI. IDE.2&RQWUROOHU $IIRUGDEOH7HVWDQG 0HDVXUHPHQW7RROV ZZZNHWHUH[FRP Rowley CrossWorks Fine Circuits Inc.MX27. and JTAG programming tools in a single professional package ..Impedance with polar report Board and CPU support for NXP.com www. 370HR/IS410 polynelco. Instant online ordering FREE 1st Article with ANY PRODUCTION ORDER! $50‡$50‡&RUWH[ Quality supplier of Printed Circuit Boards with wide range of rigid & flex manufacturering capabilities: C/C++ Compiler.MPC565.finecircuits.com | 800.MPC555 PHYTEC embedded System On Module technology is your production-ready hardware and software solution.MX31 ARM7: LPC2294 XScale: PXA270 Blackfin: ADSP-BF537 Coldfire: MCF5485 x86: Z510.net & www.MPC5200B.MPC5567. DUMMY—Simulated load 20. PORT—AGP = Accelerated Graphics ___ 15. ADMITTANCE—Antonym: impedance 14. replaces mouse 10. GIGAWATTHOUR—1 billion watthours 7. WINDOWS—WS_FTP is for? 2. SPI. / 17. GAIN—Increased power 12. PI—C/d 13.Journal-Plaza. PCB—Where’s a “track”? 18. SOLIDUS—Slash. PATCH—A system or code “fix” 11. LISTSERV—Mailing list management program 21. but he won the Nobel Prize in 2000 for ___ 9. petro [two words] 5. FOSSILFUEL—Coal. SERIAL—I2C. CURIE—Discovered the piezoelectric effect in 1883 4.net O N L L I • www. BARE—Conductor without insulation 6.net & www. BIAS—An input applied for system/device control 8. ZEPTO—10–21 F O S S I L F U E L 4 S R N 5 D I B I A S O E A T R E 6 W G 7 8 P P H Y S I L E C S L G A 9 10 P I T R A C K B A L L 11 G W C 12 T 13 A D M I H S T T A N C E 14 E P O R T R C I N T 15 P I H T O T T U B E O A 16 S O L I 17 18 D U M M Y D U S A R 19 Z X 20 L I S T S E R V P M T 21 Q U A D R I 78 CIRCUIT CELLAR® www.WorldMags. SATELLITE—The “S” in SATCOM 5. MAXIM—Founded the ARRL in 1914 19.ib-239_Layout 1 5/12/2010 12:09 PM Page 78 CROSSWORD ANSWERS from Issue 238 1 2 C W June 2010 – Issue 239 3 Across 3. measures airspeed [two words] 16.com . 1-Wire 14.circuitcellar. QUADRILLION—A petabyte = 1 ___ bytes Down 1. TRACKBALL—Moves cursor. PITOTTUBE—Measures fluid flow velocity. PHYSICS—Jack Kilby invented the integrated circuit in 1958. Inc. 78 JK microsystems. Page Page Page 77 AAG Electronica. Inc.7708 e-mail: peter@smmarketing. Motion Planning. Inc. LLC 76 Atria Technologies. 75 All Electronics Corp. Inc. 77 Earth Computer Technologies 76. Flash Memory Summit Call Peter Wostrel now to reserve your space! 800.net. 3 77 Hexapod Kinematics: Motor Communication.281. 77 Rowley Associates 77 Apex Embedded Systems 77 Fine Circuits. LLC 73 Linx Technologies. Inc.I NDEX OF ADVERTISERS located at www. 50 DesignNotes Imagineering. 76 Lawicel AB 42 Sealevel Systems 33 CWAV 13 Grid Connect. 59 LPFKF Laser & Electronics 13 ScanTool. 32 JK microsystems. 15 Cleverscope 38 HobbyLab. Inc. Inc. Inc.us June 2010 – Issue 239 Page The Index of Advertisers with links to their web sites is 79 CIRCUIT CELLAR® www. 73 AP Circuits 27 ExpressPCB 48 Keil Software 78 Reach Technology. Inc. 21 FTDI 77 Keterex. 76 MCC (Micro Computer Control) 76 Custom Computer Services. Inc. Inc.com under the current issue. LLC 49 Pololu Corp. 12 Comfile Technology. Inc. Inc. Inc. Inc. 19 1 Elektor P 5 REVIEW 2. 77 Phytec America LLC Jameco 46 PoLabs 18. 75 Ironwood Electronics 32 PCB-Pool 7 28 ESC Chicago 11. Inc. Inc.circuitcellar.net & www. Texas Instruments WIZnet iMCU Design Contest A TTENTION A DVERTISERS of July Issue 240 Theme: Internet & Connectivity www. Bluetooth Headset Build an Unbuntu Webcam Server THE CONSUMMATE ENGINEER It All Begins with a Spec LESSONS FROM THE TRENCHES Put C Language to the Test (Part 3): Rules and Assignments FROM THE BENCH Application Communication with USB (Part 2): The Importance of Descriptors SILICON UPDATE Wall Whisperer: A New Take on Powerline Communication • Tern. 11 Lemos International Co. 78 FlexiPanel Ltd. 57 TI DesignStellaris 2010 Contest 75 Decade Engineering 29 ICbank. 76 I2CChip 76 microEngineering Labs. C3 Digi International 38 Intuitive Circuits LLC C2 NetBurner 75 Triangle Research Int’l. 53 Mouser Electronics 78 Trace Systems. 67 Total Phase.Journal-Plaza. 43 EMAC.circuitcellar.3741 or 978. LLC 14 Elsevier 38 Jeffrey Kerr. 75 Mosaic Industries. 10 Holtek Semiconductor. Inc. Inc.net .com 9 Technologic Systems August Issue 241 Deadlines Space Close: June 11 Material Close: June 18 Theme Embedded Development Bonus Distribution Hot Chips.WorldMags. Inc. Inc.454. C4 Parallax. Inc. and Image Processing X10 Controller Design (Part 1): Hardware and Circuitry Wireless Data Exchange: Building a 2700-lb. I’ve accused various graduating classes of being dumber than shoe leather and others of downright laziness. And. if educators demand to know a student’s unique contribution when collaborating. closed-book exams were the norm. no one fixates on the mechanics of exactly how great people arrive at great solutions. you were screwed. but a change in one of my classes made all the difference in my success. I wonder if the system is sometimes also stacked against them. It is not original. but that was by me too! It may not be “original” when I say it today. Engineering and computer science students aren’t more dishonest than others. Out in the real world. steve. Certainly.com . Back in my day. and contribution. The scanning software was correct. And. not memorize formulas. I’m not convinced that all the claims of cheating and plagiarism in computer science and engineering classes are entirely valid—not because I deny that there is copied code and circuits circulating in classes. While this example may be questionable.circuitcellar. but because the witch hunt to find it contradicts the reality of life outside the classroom. Then.. right. copyright. especially when something determined to be “cheating” in one place is often considered “intelligent collaboration” in another. Especially with computer science classes. One frequently used excuse is that students should be learning the mechanics of problem solving (i.ciarcia@circuitcellar. I question the point of the exercise. I cringe at the thought of America becoming a third-world technical power due to an education process that often seems to emphasize quantity over quality. ask them! Certainly. in the defense of hard-working students. do it all themselves with no other sources) before the world of collaboration is open to them.com 80 CIRCUIT CELLAR® www. technique. it was first used in the early 1980s. However.net • www. What is the purpose of all this formal education if it discourages a sense of teamwork and collaboration that students absolutely need for later success? Cheating should be about the ethics and morality of content use (i. When asked if it was original or not. not demean.. one semester. If you didn’t remember the correct formulas (the “mechanics”). it got my attention. the concentration on “mechanics” is about evaluating a student’s unique problem-solving skills and programming technique. red flags immediately indicated that I had plagiarized it and that the saying had originated in the early 1980s. change the questions! If they are worried about students working together. But. the easiest way to determine the stars and duds in a design committee (college or business) is to interview them individually and ask each to explain their logic. a graduate student complained to me that he felt some of his professors were on a witch hunt about plagiarism and cheating. but it is absolutely not plagiarism because I’m the guy who wrote the “original” line back then. and permissions) and not simply about its syntax and acquisition.” which I used a few months ago.steve_edit_239_ver1_Layout 1 5/12/2010 8:20 AM Page 96 RIORITY PINTERRUPT by Steve Ciarcia. But I assure you: it was meant to motivate.Journal-Plaza. If educators are so worried about students copying past solutions. The problem is that before the Internet. Recently.e. the dummy who wrote the scanning program that might be deciding the fate of others didn’t go far enough. Founder and Editorial Director Is It Cheating or Is It Collaboration? June 2010 – Issue 239 I know I have been hard on students in the past. a professor declared that his exams would be “open book” from then on. it has morphed into a myriad list of prohibitions about sources. It’s been a long time since I was in college. They are just more apt to be caught violating the “rules” because their professors are more likely able to use automated tools that scan and detect coincidences among sources. Yes. but his logic was that engineering careers were “open book. Yeah. Today. issues about cheating were exclusively about ethics and morality. “My favorite programming language is solder. license. it meant that he had to change exam questions and homework assignments each semester. but what makes an outstanding engineer or scientist is ultimately performance.net & www. it has nothing to do with avoiding all the work associated with changing test problems and homework assignments from previous semesters. When these embargos prevent using online examples or knowledge from others. I realize there is a fine line separating the arguments in all this. Over the years. then simply have students declare the names of other collaborators when they submit their work. he asked one of the plagiarism scanning packages to check the sentence.e. To make his point.” Educate engineers to solve problems.WorldMags. especially with regard to the Internet and certainly in colleges. digi. gateways.C3. 1-877-912-3444 Adapters www.net .qxp 4/7/2010 1:05 PM Page 1 XBee ® 7KH0RVW)OH[LEOH=LJ%HH3ODWIRUP : ZigBee PRO interoperability : Out-of-the-box RF communications : Common XBee footprint makes substituting modules easy NEW! Programmable ZigBee modules : Optimized for ZigBee application profiles including Smart Energy : iDigi™ Energy solution bundle : Complete solution: Modules. services The industry’s first ZigBee Smart Energy modules 'LJLŠVMMLYZ[OLPUK\Z[Y`»ZTVZ[JVTWSL[LZL[VMOHYK^HYLHUKZLY]PJLZMVY`V\YAPN)LLLUHISLK ZVS\[PVU?)LLWYVK\J[ZZ\WWVY[H^PKLYHUNLVMHWWSPJH[PVUZPUJS\KPUN:THY[.net & www.com/getXBee www.WorldMags.Journal-Plaza.ULYN`/VTLHUK )\PSKPUN(\[VTH[PVU9LTV[L+L]PJL4HUHNLTLU[HUKTVYL>P[OHOVZ[VMTVK\SLZZ[HUKHSVUL Gateways HKHW[LYZ07LUHISLKNH[L^H`ZHUKP+PNPKH[HZLY]PJLZ+PNPOHZ[OL[VVSZ[VZLL`V\YWYVQLJ[ [OYV\NOMYVTILNPUUPUN[VLUK Modules Get started today with an XBee Development Kit Digi International Tel. adapters. net .WorldMags.net & www.Journal-Plaza.C4_Layout 1 5/12/2010 8:22 AM Page 1 www.
Copyright © 2024 DOKUMEN.SITE Inc.