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