Cover - 246_Layout 1 12/10/2010 1:08 PM Page 1
worldmags
design Tips: sound detection Algorithm origin: Canada pAge: 36
insighT: Circuit-probing Tools origin: United states pAge: 48
projeCT: select & implement an rTos origin: United states pAge: 52
The worLd’s soUrCe for eMBedded eLeCTroniCs engineering inforMATion
eMBedded AppLiCATions
jAnUArY 2011 issue 246
MCU-Based Brake Control system embedded energy Conservation “smart” network Access explained surge disaster preparedness Tips
pLUs iMCU design projeCTs innovative embedded internet Applications from the U.s., U.K., india, & Beyond: // network Monitor & Control // humidity Control system // embedded dhCp server // network operating system // ethernet-to-gpiB interface // And More
$7.50 U.S. ($8.50 Canada)
www.circuitcellar.com
5_Layout 1 11/1/2010 11:49 AM Page 1
worldmags
Low-cost Industrial
Serial to Ethernet Solutions t*OTUBOUMZOFUXPSLFOBCMFBOZTFSJBMEFWJDF t/PQSPHSBNNJOHJTSFRVJSFEGPSTFSJBMUP&UIFSOFUBQQMJDBUJPO t$VTUPNJ[FUPTVJUBOZBQQMJDBUJPOXJUIBEFWFMPQNFOULJU
SBL2e 100
SBL2e Chip
SBL2e 200
QPSUTFSJBMUP&UIFSOFUTFSWFS XJUIFJHIU"%DPOWFSUFSJOQVUT BOEPQUJPOBM41* *$QFSJQIFSBM EFWJDFTVQQPSU
QPSUTFSJBMUP&UIFSOFUTFSWFS XJUIGPVS"%DPOWFSUFSJOQVUT PQUJPOBM*$QFSJQIFSBMTVQQPSU BOEQJOIFBEFS
SBL2e
Hardware Features 6QUPUISFFTFSJBMQPSUT .CQT&UIFSOFU VQUPEJHJUBM*0 CJU"%DPOWFSUFST PQFSBUJOHUFNQFSBUVSFUP$ CJUQFSGPSNBODF
Serial-to-Ethernet server with RS-232 support
QPSUTFSJBMUP&UIFSOFUTFSWFS XJUIGPVS"%DPOWFSUFSJOQVUT PQUJPOBM*$QFSJQIFSBMTVQQPSU BOE3+DPOOFDUPS
Software Features 5$16%15FMOFU)551NPEFT %)$14UBUJD*1TVQQPSU XFCCBTFEPS "5DPNNBOEDPOöHVSBUJPO Low Prices 4#-F$IJQ 2UZL %FWJDF1/4#-F$)*1*3
4#-F 2UZ %FWJDF1/4#-F*3
4#-F 2UZ %FWJDF1/4#-F*3
4#-F9 2UZ %FWJDF1/4#-F9*3
4#-F9" 2UZ %FWJDF1/4#-F9"*3
SBL2e XA &YUFSOBMTFSWFSXJUIVQUP GPVS"%DPOWFSUFSJOQVUT VQUPFJHIUEJHJUBM*0BOEVQ UPUXP6"354 POF34
worldmags
Need a custom solution? /FU#VSOFS4FSJBMUP&UIFSOFU%FWFMPQNFOU,JUTBSFBWBJMBCMFUPDVTUPNJ[FBOZ BTQFDUPGPQFSBUJPOJODMVEJOHXFCQBHFT EBUBöMUFSJOH PSDVTUPNOFUXPSL BQQMJDBUJPOT"MMLJUTJODMVEFQMBUGPSNIBSEXBSF "/4*$$ DPNQJMFS 5$1*1 TUBDL XFCTFSWFS FNBJMQSPUPDPMT 3504 BOE/#&DMJQTF*%& Information and Sales]TBMFT!OFUCVSOFSDPN Web]XXXOFUCVSOFSDPNTelephone]
9.qxp
8/7/2008
11:04 AM
Page 1
worldmags
worldmags
2_Layout 1 10/27/2010 1:26 PM Page 1
worldmags
Embedded Systems High-End Performance with Embedded Ruggedness
TS-7800
500 MHz ARM9
Unbrickable design
229
$
Low power - 4W@5V
qty 100
128MB DDR RAM 512MB high-speed (17MB/sec) onboard Flash
269
$
qty 1
12K LUT customizable FPGA shown w/ optional SD Cards
3x faster and backward compatible with TS-72xx
Internal PCI Bus, PC/104 connector 2 host USB 2.0 480 Mbps Gigabit ethernet
2 SD sockets
10 serial ports
110 GPIO
5 ADC (10-bit)
2 SATA ports
Sleep mode uses 200 microamps Boots Linux 2.6 in 0.7 seconds Linux 2.6 and Debian by default
TS-TPC-7390 7” Color Touch Panel Computer Low Power, Industrial Quality Design Mountable aluminum frame 200 MHz ARM9 64MB SDRAM (128MB opt) 512MB Flash w/ Debian Linux 800 x 480 video core Dedicated framebuffer- 8MB RAM
$
Audio codec with speaker
449 qty 1
Boots Linux 2.6 in less than 2 seconds Unbrickable, boots from SD or NAND Runs X Windows GUI applications Runs Eclipse IDE out-of-the-box
Over 25 years in business Open Source Vision Never discontinued a product Engineers on Tech Support
More Touch Panel Computers on our website
Custom configurations and designs w/ excellent pricing and turn-around time Most products stocked and available for next day shipping
Design your solution with one of our engineers (480) 837-5200 worldmags
3_Layout 1 10/27/2010 1:28 PM Page 1
worldmags
New Products TS-WIFIBOX-2
$
A Complete Solution for 802.11g WiFi Applications
185 qty 1
Low power (3.2 watts), fanless Power via 5-12 VDC, USB, PoE (opt.) 64MB DDR-RAM 256MB ultra-reliable XNAND drive Micro-SD Card slot RS-232, RS-485, CAN, RTC Header with SPI and 11 DIO 480Mbit/s USB, Ethernet, PoE option Boots Linux 2.6.24 in < 3 seconds
Ideal for gateway or firewall, protocol converter, web server, WiFi audio, and unattended remote applications
Un-brickable, boots from SD or flash Customizable FPGA - 5K LUT Optional DIN mountable enclosure
series starts at
$
92
TS-SOCKET Macrocontrollers Jump Start Your Embedded System Design
55 mm / 2.165 in.
qty 100
TS-SOCKET Macrocontrollers are CPU core modules that securely connect to a baseboard using the TS-SOCKET connector standard. COTS baseboards are available or design a baseboard for a custom solution with drastically reduced design time and complexity. Start your embedded system around a TS-SOCKET Macrocontroller to reduce your overall project risk and accelerate time to market. Current projects include:
75 mm / 2.953 in.
TS-4200: Atmel ARM9 with super low power TS-4300: Cavium ARM11 with dual 600 MHz and FPU Dual 100-pin connectors
TS-4500: Cavium ARM9 at very low cost
Secure connection w/ mounting holes
TS-4700: Marvell PXA168 with video and 1.2 GHz CPU
Common pin-out interface
TS-4800: Freescale iMX515 with video and 800 MHz CPU
Low profile w/ 6mm spacing
Several COTS baseboards for evaluation & development
Technologic Systems We use our stuff. Visit our TS-7800 powered website at
www.embeddedARM.com worldmags
Task_Masthead_246_masthead.qxd 12/9/2010 4:06 PM Page 4
worldmags
T
ASK MANAGER Circuit Cellar International
January 2011 – Issue 246
S
4 worldmags
ince joining forces with Elektor in 2009, we’ve worked hard to reach new readers in new locations who use embedded technologies. To do so, we’ve logged some serious miles. For instance, staffers travelled to ESC San Jose in early 2010 to recruit new readers and present the advantages of the Circuit Cellar-Elektor union to the entire design community. In the fall, we went to ESC Boston with the same sense of purpose. But we didn’t stop at the East Coast of the United States. Late last year, staffers flew to Munich to interact with engineers and programmers who work throughout Europe. And around that same time, our editorial team translated Circuit Cellar content to share with new readers in China. The list of our outreach efforts goes on and on. But you get what we’ve been up to. International community development! As this is the first issue of 2011, I welcome all of our new readers. I’m glad you joined our growing international readership of talented engineers, programmers, academics, and students. As we progress together through 2011, you’ll learn that becoming an engaged Circuit Cellar reader can be a lifechanging and even financially profitable experience. During the next 12 months, we’ll give you ample opportunities to do amazing things like publish project articles, pitch ideas for high-end technical books, post design projects on Circuit Cellar websites (so potential investors and employers can review your work), enter design challenges with enticing cash prizes up for grabs, and much more. Such opportunities are yours for the taking. In fact, you still have time to compete in the NXP mbed Design Challenge 2010. The submission deadline is 1 PM EST on February 28, 2011. The clock is ticking. Need a project idea? Use this issue to your advantage. First, turn to page 16 to review the winning projects from the WIZNet iMCU design challenge. In upcoming issues, you’ll be able to read in-depth articles about some of the award-winning W7100-based designs. After reviewing the WIZnet winners, turn to page 24, where you can read an article by Richard Wotiz—yes, the same Richard Wotiz who one First Place in the WIZnet contest— about his prize-winning Bicycle ABS System project. You’ll surely be inspired by Richard’s success and enthusiasm for designing innovative systems. On page 36, the team of Riley Kotchorek, Mike Smith, and Vahid Garousi from the University of Calgary conclude their series about mobile application development. This article details a sound detection algorithm and the app’s functionality. Some of the remaining articles detail invaluable design/programming tips—surge suppression (p. 20), circuit probing (p. 48), using an RTOS (p. 52)—and the others describe exciting new technologies that you’re likely to work with in the near future— “smart” networks (p. 58) and energy-conserving chips (p. 66). Enjoy this issue. Be sure to tell us about your projects.
[email protected] THE MAGAZINE FOR COMPUTER APPLICATIONS PUBLISHER Hugo Van haecke
FOUNDER/EDITORIAL DIRECTOR Steve Ciarcia
ASSOCIATE PUBLISHER Shannon Barraclough
EDITOR-IN-CHIEF C. J. Abate
CUSTOMER SERVICE Debbie Lavoie Kim Hopkins
WEST COAST EDITOR Tom Cantrell CONTRIBUTING EDITORS Jeff Bachiochi Robert Lacoste George Martin Ed Nisley
CONTROLLER Jeff Yanco ART DIRECTOR KC Prescott
NEW PRODUCTS EDITOR John Gorsky
GRAPHIC DESIGNERS Grace Chen Carey Penney
PROJECT EDITORS Ken Davidson David Tweed
STAFF ENGINEER John Gorsky
Circuit Cellar’s mission is to collect, select, and disseminate need-to-know information around the world in the fields of embedded hardware, embedded software, and computer applications. Circuit Cellar uses an assortment of print and electronic content-delivery platforms to reach a diverse international readership of professionals, academics, and electronics specialists who work with embedded, MCU-related technologies on a regular basis. Our aim is to help each reader become a well-rounded, multidisciplinary practitioner who can confidently bring innovative, cutting-edge engineering ideas to bear on any number of relevant tasks, problems, and technologies.
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.cc-access.com, E-mail:
[email protected] Subscribe: 800.269.6301, www.cc-access.com, 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 $45, Canada/Mexico $60, all other countries $63. Two-year (24 issues) subscription rate USA and possessions $80, Canada/Mexico $110, all other countries $116. 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 12/8/2010 11:10 AM Page 1
worldmags
The LPC1100L microcontroller offers a seamless entry point for any 8-/16-bit designer looking for scalable architecture for their entire product range.
ARM Cortex-M0 Superior code density than 8-/16-bit Higher performance than 8-/16-bit Lowest active power consumption Supported by NXP’s LPCXpresso tool platform
www.nxp.com/lpc1100l
worldmags
TOC_246_toc.qxd 12/10/2010 9:40 AM Page 6
246
INSIDE ISSUE January 2011
•
Embedded Applications
24
Bicycle ABS Brake System Richard Wotiz
36
Mobile Application Development (Part 2) A Sound-Detection Algorithm Riley Kotchorek, Mike Smith, & Vahid Garousi
48
Stress-Free Probing Don McLane
Elbow Probe
Sound Monitoring p. 36
Brake Control
Sky Drop Probe p. 48
p. 24
WIZnet iMCU 2010 Results
p. 16
FIRST PLACE Net Butler Richard Wotiz United States
Energy Harvesting
Charger in a Chip
p. 66
20
January 2011 – Issue 246
52
6 worldmags
58 66
THE CONSUMMATE ENGINEER Surge Suppression Tips and Tools for Protecting Circuitry George Novacek LESSONS FROM THE TRENCHES Big Changes in the Embedded World (Part 2) Implement an RTOS and a Real SPI George Martin FROM THE BENCH Smart Network Access Point Jeff Bachiochi SILICON UPDATE Power Tripping Energy Conservation on the Embedded Level Tom Cantrell
SECOND PLACE A Green Solution to Basement Humidity Control David Penrose United States THIRD PLACE m7100os: A Network Operating System Naubert Aparicio United States FOURTH PLACE Moonlight Programmable LED Display Bodgan Marinescu Romania
TASK MANAGER Circuit Cellar International C. J. Abate
4
NEW PRODUCT NEWS
9
TEST YOUR EQ
15
CROSSWORD
74
INDEX OF ADVERTISERS February Preview
79
PRIORITY INTERRUPT Second-Life Computing Steve Ciarcia
80
CIRCUIT CELLAR®
•
www.circuitcellar.com
worldmags
11_Layout 1 8/4/2010 5:00 PM Page 1
worldmags
worldmags
2112017_Ford_Layout 1 12/9/2010 4:08 PM Page 8
worldmags
by Simon Ford
ADVERTISEMENT
The mbed Challenge Is On! DESIGN CHALLENGE
January 2011 – Issue 246
W
8 worldmags
The mbed team is setting out to make rapid prototyping with microcontrollers a reality. Now it’s your chance to get involved, develop something remarkable, and help move the industry forward. Are you up to the challenge?
e’re calling on all of you to join the mbed challenge and create a project that helps move the industry forward on two fronts—insight and reuse. Why? Because insight drives invention and reuse drives innovation. And you might win a prize! Insight is the thing that provides the inspiration for what is possible. It can be something as simple as when we explain the interface pinout for mbed. “Here you can see the digital I/Os, ADCs, PWM, Ethernet, …” is often interrupted with “What? It’s got Ethernet built in? So I could ...” PING! Right there, the insight that a cheap microcontroller could connect to a network has flicked on a switch and inspired something new. Part of our goal is met simply by using mbed to educate and give insight into what makes up a modern microcontroller. But more often, it comes from seeing something is possible, such as a write-up where someone has used USB to log data to a thumb drive or the CAN interface to hook up a car’s ECU. It could be some whacky project that in itself seems like technology for technology’s sake, but demonstrates a concept that can be reapplied in a totally different domain with a slightly different twist to provide a really important technical step forward. This is why we have challenged you to help show what’s possible! This also brings us to the second goal—reuse. Good projects are naturally reference designs for similar projects. They have solved many problems that need not be solved again, and can act as starting points for you to gain confidence and understanding. However, really great projects are elegantly constructed of libraries and building blocks that have been created to abstract implementation details at different levels, allowing for simple understanding, easy development, testing, reworking, and repurposing. Whilst the approach makes development of the project much easier, it also provides components that can be reused in future projects. This is why we have challenged you to publish what you end up with! Microcontrollers are solutions looking for problems, and many of these solutions will have to come from people in
other problem domains. Early on, when trying to explain mbed, we used to throw around a hypothetical example to try and get this across: “Who is best placed to spot the opportunity for an automated pig feeder? The guy who knows everything about microcontrollers, or the guy who has to get up every Sunday morning to feed the pigs?” It made the point, but in some ways our example suffers from exactly the problem we’re highlighting. Whilst we think automating the pig feeder must be a killer app in pig farming, it is quite likely to be something totally different that we’d never have the insight to identify! That is why we think giving insight into the world of microcontrollers is essential to help exploit their potential, just as insight into computers was needed to help bring them out of the scientific labs and apply them to all sorts of nonscientific applications. This is where your inventions and creations will bring new insights and show what is possible. They also will inspire people to learn how to do it for themselves to create new and wonderful things. By publishing projects that show off interesting ideas, technologies, and techniques, you’ll be enabling insight into what is possible and providing components that can be reused to help build future prototypes faster than ever. The interest and support for this challenge has been outstanding, and we’re already seeing the start of some great ideas. But we want more people, more ideas, more invention, more innovation! If you haven’t registered to enter yet, why not?! We’ve even put up prizes to give you some additional motivation. If you have entered, time to get stuck in, burn the midnight oil, and create something awesome. Make your entry count! Good luck! I Simon Ford, co-creator of mbed, is a lifelong electronics and computer engineer. He works at ARM, and before starting mbed was technical lead for the ARMv7/NEON architecture now found in most new smartphones.
To enter the NXP mbed Design Challenge 2010, go to: www.circuitcellar.com/nxpmbeddesignchallenge/ CIRCUIT CELLAR®
•
www.circuitcellar.com
npn246_Layout 1 12/9/2010 4:09 PM Page 9
worldmags
RADIO SoC COMBINES DATA CONVERSION, RF, & 32-BIT PROCESSING The ADuCRF101 is a system-on-chip (SoC) device that integrates all of the RF transmit and receive functions, data conversion, and processing elements required to enable a fully programmable radio. Designed for a range of remote, battery-powered wireless sensor network applications—including utility meters, medical telemetry systems, building automation, asset tracking and security systems—the ultra-low-power ADuCRF101 radio SoC features a 12-bit ADC, a 32-bit microprocessor core, on-chip SRAM and flash memory, and an ISM-band radio transceiver. The network range and coverage of the ADuCRF101 radio SoC is well suited to applications where data must be captured, measured, and transmitted quickly in noisy environments without taxing battery life. In medical patient monitoring systems, a wireless Holter or telemetry monitor worn by the patient needs to be small, operate at low power for extended battery life, and offer the performance level to sustain uninterrupted communication of the patient’s vital signs. The ADuCRF101’s Cortex-M3 core provides the throughput necessary to support a growing array of sensing and measurement functions, and features serial download and debug, an external watch crystal that functions as a wake-up timer, and a 16-MHz PLL with an eight-way programmable divider. The integrated RF transceiver provides a combination of industry-leading interference blocking performance with very low receive and transmit currents, allowing more robust operation in urban environments where interfering signals are present. The ADuCRF101 device is supported by a suite of ADI development tools. One-thousand-piece pricing starts at $4.05.
Analog Devices, Inc. www.analog.com
555-LIKE ANALOG TIMER WITH BATTERY-SAFE OPERATION
Semtech Corp. www.semtech.com
E WS N CT DU R O P EW N Edited by
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
John Gorsky
January 2011 – Issue 246
The new SX8122 is an analog timer platform that revolutionizes the conventional 555 timer for low-voltage, battery-operated small appliances. The timer offers the best-in-class battery life via its intrinsic 0.9-V operation, without the need for an external boost converter and inductor, saving board space and cost. The device also includes a voltage monitor to enable a simple USB charger. The timer operates between 0.9 and 2 V over a range of –40° to 85°C, making it ideally suited to run from one AA or AAA alkaline, NiMH, or NiCd battery. The device has a continuous output that can be activated with the press of a button to control either a DC motor or other continuous low voltage function, as well as a burst output to drive a high-brightness white or green LED. The SX8122 is programmable via external resistors and a capacitor, similar to the legacy 555 analog timer but at 1 V, and it is designed for on/off button debouncing, delayed start-up functions, and analog programmable sequencing and time-out. The device is battery-safe, controlling I/Os at 0.6 V to eliminate unexpected behavior in the external components and prevent current drain during start-up. It also features a battery overload indicator for slow NiMH or NiCd charger management. At power-down (low battery), the I/Os are controlled again down to 0.6 V and the current consumption is guaranteed less than 10 µA. The SX8122 (order code: SX8122ISTRT) is priced at $0.36 each in 2,500-piece lots. The ordering code for starter kits is SX8122EVK.
9
npn246_Layout 1 12/9/2010 4:10 PM Page 10
worldmags
EFFECTIVELY IMPROVE THE YIELD QUALITY OF PCBs While most PCB layout tools are very good at performing a design rules check (DRC), they rarely capture the many common design for manufacturing (DFM) problems that are hidden in the physical artwork (i.e., Gerber, drill files). It’s the artwork that’s ultimately used to manufacture boards (not the PCB Layout database) and any hidden problems in the artwork will affect the manufacturability and yield of the boards. This is why using a Gerber Viewer has been so popular with PCB designers, but unless they have eyes like a hawk, simply looking at Gerber files (containing hundreds of signals and through holes) inside a free viewer without DFM capabilities is just an invitation for mistakes. With the help of FAB 3000 DFM’s unique features—such as DFM report-detailing—all DFM violations with x/y locations will be highlighted by an instantly created PDF. There are other features. Object Hover is used to instantly highlight objects and provide all the detailed information needed with a simple movement of the mouse. RedLine Markup enables you to communicate change requests with comments, observations, and instructions effectively and efficiently with your design team or customers. And these are just a few of the features FAB 3000 DFM has to offer. The FAB 3000 DFM starts at $195.
Numerical Innovations LLC www.numericalinnovations.com
January 2011 – Issue 246
INTEGRATED OFFLINE SWITCHING IC
10 worldmags
The LinkZero-AX is an integrated offline switching IC that enables designers to achieve 0.00 W of standby energy consumption in auxiliary power supplies. Commonly used in such products as major appliances, TVs, and remotely-controlled electronic lighting ballasts, auxiliary power supplies continuously draw power as long as the product is plugged in, resulting in significant stand-by energy waste. LinkZero-AX features an innovative power-down mode that effectively turns off the auxiliary power supply when the end product is idle. Power-down mode is triggered by a signal accessible to a microcontroller, completely shutting down switch-mode operation and internal switch control circuits, eliminating energy wasted by these unnecessary functions. While in power-down mode, the LinkZero-AX stays alive, allowing the IC to be awakened with a reset pulse or button press. The bypass pin on the LinkZero-AX IC can also provide up to 500 µA of current for use by any system control or sensing circuit. LinkZero-AX provides designers with flexibility to build ultra-low standby power supplies without mechanical AC mains switches. When used in tandem with Power Integrations’s CAPZero X capacitor discharge IC and SENZero sense resistor disconnect device, LinkZero-AX reduces standby power waste in high-power consumer products and appliances to as low as 4 mW, or effectively zero. (IEC 62301 Clause 4.5 classifies power usage of less than 5 mW as zero.) LinkZero-AX devices are available now in an SO-8C package at $0.35 each for 10,000-piece quantities.
Power Integrations www.powerint.com
NPN CIRCUIT CELLAR®
•
www.circuitcellar.com
npn246_Layout 1 12/9/2010 4:10 PM Page 11
worldmags
RF ENERGY-HARVESTING KIT ENABLES BATTERY-FREE, PERPETUALLY POWERED WIRELESS APPLICATIONS Microchip Technology and Powercast Corporation have announced the Lifetime Power Energy Harvesting Development Kit for Wireless Sensors featuring PIC microcontrollers with eXtreme Low Power (XLP) Technology. The kit comprises a 3-W Powercaster transmitter as the power source, two P2110 Powerharvester receiver evaluation boards, two customdesigned wireless sensor boards, the XLP 16-bit Development Board pre-loaded with jointly developed application software, an IEEE 802.15.4 transceiver, and other accessories. This package makes it easy to demonstrate and develop smart-energy, wireless-sensor applications that are reliably and perpetually powered by radio waves—eliminating the need for a battery. The included transmitter can wirelessly power sensor devices from more than 40′ away. In the kit, the Powercaster transmitter broadcasts RF energy to the Powerharvester receiver, which can be embedded into an OEM’s micro-power device. The receiver then converts the RF energy and presents it as a regulated power supply to LOW-POWER NUMERIC LCD Microchip’s PIC24F microcontroller. The recently announced The PSX-ZDS-A is a near-zero power, three-digit Powercast transmitter included in the kit is approved by the numeric LCD module optimized for long-life, batteryFCC (Part 15) and Industry Canada. powered applications. The PSX-ZDS-A is designed with Using broadcasted RF energy as the application’s sole power low power and ease of use in mind for applications source allows for untethered and battery-free operation in hazrequiring a display technology where power consumption ardous or inaccessible locations. Additionally, broadcasted RF is at a premium. With less than 1-nA typical quiescent energy is controllable and works in locations where other current draw (static display) and 5.0-nA typical current potentially intermittent energy-harvesting sources make them draw in continuous update mode, the display allows for unreliable. intelligent indication and visual feedback while maximizThe kit is available for $1,250 from Powercast’s distributors, ing battery life and minimizing power consumption. including microchipDIRECT. Designers of power-sensitive applications with meter or instrument displays, visual error code notification, Microchip Technology, Inc. status reporting, or other general usage three-digit LCD www.microchip.com display functions can use the PSX-ZDS-A to significantly decrease the power load required for display purposes. The PSX-ZDS-A is just as easy to implement in a design as standard LED status lights while providing more system feedback options. Each individual digit is controlled by a dedicated digital line. A voltage pulse to the digital line increments the digit. Duty cycling of input power to produce a flashing numeric display further reduces the PSX-ZDS-A’s power conIdeal for Embedded Applications with High-Speed Serial I/O Requirements sumption. Shipping in a standard 46 mm × 25 mm, panel-mount-ready package, the PSXXilinx® Virtex™-5 ZDS-A is available with a six-pin Samtec System-on-Module 0.100″ pitch female connector or with 8VHU'HILQDEOH,2 through-holes for custom connector mat8VHU0XOWL*LJDELW6HU'HV3DLUV ing. One-thousand-piece pricing starts at 8VHU%L&RORU/('V $9.55. 8SWR0+]2SHUDWLRQ
MLX-1000-XC5V
Starting at $495 Actual Size
9LUWH[PRGXOHVDUHFDSDEOHRIFRQQHFWLQJWR3&,([SUHVV6*0,,*LJDELW(WKHUQHW6HULDO$7$ 86%DQGRWKHU6HU'HVLQWHUIDFHVYLDWKH0XOWL*LJDELW6HU'HV7UDQVFHLYHU3DLUV
NPN www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
www.modularlogix.com Performance and features vary depending on FPGA model, speed-grade, and end-user design.
January 2011 – Issue 246
8SWR0%''5'5$0 2SWLRQDO0E4'5,,65$0 2QERDUG&RQILJXUDWLRQ)ODVK 2SHUDWHVRQ6LQJOH96XSSO\ FP[FP)RRWSULQW PP6WDFNLQJ+HLJKW
ParasitX LLC www.parasitx.com
11
npn246_Layout 1 12/9/2010 4:10 PM Page 12
worldmags
SMALL LOW-COST MULTIPROTOCOL OBD INTERPRETER CHIP STN1110 is a new multiprotocol OBD-to-UART interpreter IC that provides an easy way to access diagnostic information, VIN, hundreds of real-time parameters, and scores of other vehicle data. Despite its low cost, it is packed with features including a secure bootloader, advanced message filtering, low-power mode, and large OBD message buffer. To maintain compatibility with existing applications, the STN1110 has full support for the ELM327 command set, while outperforming the original ELM327 IC in every category: stability, performance, and features. The IC supports all legislated OBD-II communication protocols, and it features a sophisticated automatic protocol detection algorithm, ensuring compatibility with the widest range of vehicles. In addition to emulating the full ELM327 command set, STN1110 supports an extended command set that provides access to advanced functionality not available in the original ELM327, as well as faster data throughput on all protocols—sometimes by as much as 100%. STN1110 is available in SPDIP, SOIC, and QFN packages and runs the same proven code that powers the popular OBDLink family of PC-based OBD interfaces. The chip is volume-priced at $4.95, so it places OBD information within reach of even the most cost sensitive commercial or consumer application. Free samples can also be requested on the OBD Solutions website.
OBD Solutions www.obdsol.com
January 2011 – Issue 246
HIGH-CAPACITY PORTABLE MEMORY TOKENS
12 worldmags
The new DFX and UFX Series (High Capacity Line) of highcapacity portable memory tokens combines the high capacity and high throughput of consumer memory products (like USB flash drives/thumb drives and SD cards) with rugged packaging, reliable operation, unique form-factors, and high cyclelife/harsh environment receptacles. These features allow embedded system designers to incorporate high capacity memory devices into their designs, without the shortcomings that consumer-focused solutions bring. These reprogrammable memory devices include two families of memory tokens: the DFX Series—which delivers a high-performance Secure Digital (SD) interface (including SPI)—and the UFX Series—which delivers a USB 2.0 high-speed interface. Both series come standard with 4 GB of nonvolatile memory, with larger capacities (up to 32 GB) available. Integration is straightforward and is typically accomplished by simply adding one of Datakey Electronics’s industrial-rated mating receptacles. Utilizing the robust SlimLine token form-factor design allows the tokens to leverage the entire line of SlimLine receptacles, providing OEMs with a complete data-carrier system. The High Capacity Line of receptacles features multiple mounting options, including through-hole, surface-mount, and panelmount versions. Panel-mount options are available in IP65 (“splash-proof”), IP67 (immersion), and EMI reduction versions to meet the needs of harsh environment applications. Simple PC adapters and development kits are also available by contacting the factory. OEMs who would like pricing, availability, samples, or more information on the High Capacity Line of memory tokens and receptacles are encouraged to contact the Datakey Electronics factory.
Datakey Electronics www.datakey.com
I/O MODULE PROTECTS EMBEDDED COMPUTING SYSTEMS The Opal-MM-1616 PC/104 I/O module features 16 optoisolated inputs and 16 relay outputs, supported by Diamond’s industry-leading Universal Driver software library. The OPMM-1616-XT is useful for industrial automation, transportation, energy, instrumentation, aerospace, military, and medical markets and applications. Opal-MM-1616-XT’s optoisolated inputs can accept DC voltages up to 30 VDC. Inputs feature channel-tochannel and input to output isolation of 500-V DC or AC. The inputs feature a programmable edge detection circuit that can generate interrupts on any change on any input. The module also provides 16 Form C SPDT relay outputs rated at 30 VDC at 2-A capacity, or 125 VAC at 0.1 A. Each relay has two sets of normally open, common, and normally closed contacts wired in parallel for greater reliability and lifetime. Diamond’s advanced Universal Driver software provides a high-level programming library for all of Diamond’s data acquisition products. All data acquisition features are supported with easy-to-use function calls, resulting in a reduced learning curve and shortened application development time. Universal Driver works with Windows XP, CE, Linux, QNX, and DOS. Application examples are included for each function and OS to provide a quick starting point for development. Opal-MM-1616-XT is priced at $195.
Diamond Systems Corp. www.diamondsystems.com CIRCUIT CELLAR®
•
www.circuitcellar.com
npn246_Layout 1 12/9/2010 4:10 PM Page 13
worldmags
LXI RF AND UNIVERSAL FREQUENCY COUNTER/TIMERS The Agilent 53200 series of RF and universal frequency counter/timers is the first frequency counter with LXI Class C compliance. The 53200 series features industry-leading performance and usability. In addition, it’s built with standard computing I/O for ease of connectivity and data collection. The combination of high-speed measurement and built-in analysis provides new functionality previously unavailable in basic frequency counter/timers. LXI/Ethernet and USB 2.0 are standard features, making it quick and simple to connect to a PC test system instrument or network. The 53200 includes internal memory of 1 million readings and supports a USB memory stick, making storing and retrieving data from the counter fast and easy. A large 4.3″ graphical display offers excellent viewing for fast trigger and instrument set-up. Advanced math and statistical information, including basic modulation domain analysis, simple jitter analysis, Allan deviation and histograms, allow engineers in design and manufacturing to view the history of their measurements quickly and see the quality and performance of their signal. The 53200’s optional battery supports remote usage and maintenance of accurate measurements by keeping the time base warm at all times. An optional GPIB interface is available to meet any legacy system compatibility requirements. The base prices of the Agilent 53210A RF frequency counter and the 53220A and 53230A universal frequency counters range from $1,963 to $3,552.
January 2011 – Issue 246
Agilent Technologies, Inc. www.agilent.com
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
13
11_Layout 1 11/8/2010 11:26 AM Page 1
worldmags
Mouser
is proud to give an approving nod
to those who never stop thinking what’s next. To all those inquisitive minds that challenge convention by asking the simple question… What if? The ones committed to developing new technological breakthroughs that make all our lives easier. We want you to know that we’re here to support you and all your ideas. No matter how far out there they might seem.
Keep dreaming.
mouser.com
The Newest Products For Your Newest Designs
™
Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
worldmags
eq-246_Layout 1 12/10/2010 9:12 AM Page 15
CIRCUIT CELLAR
worldmags
Test Your
EQ
Edited by David Tweed
Problem 1—It’s standard practice to use a pair of flipflops to resynchronize a signal that passes from one synchronous clock domain to another, in order to minimize problems with metastability.
Sometimes, it’s necessary to pass multiple-bit values (i.e., a bus) between two clock domains, for example, when processing 8-bit pixel values in a digital video stream inside an FPGA. Why is the following obvious approach a bad idea?
Problem 2—Most FPGA vendors offer a true dual-clock FIFO primitive that can be used to solve this problem in the general case. However, in cases where the data changes relatively slowly with respect to the destination clock, there’s a much simpler approach. What is it?
Problem 3—Two networks that allow message collisions with detection and recovery are Ethernet and controller-area network (CAN). However, the methods used are quite different, and CAN can make a guarantee that Ethernet cannot. What is it? Problem 4—On the other hand, Ethernet’s method has what advantage?
What’s your EQ?—The answers are posted at Contributed by David Tweed
www.circuitcellar.com/eq/
ü
RoHS
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
January 2011 – Issue 246
You may contact the quizmasters at
[email protected] 15
iMCU_PRINT_Layout 1 12/10/2010 12:55 PM Page 16
worldmags
WIZnet iMCU 2010 Design Contest Winners The WIZnet iMCU Design Contest 2010 challenged engineers across the globe to incorporate the W7100 Internet MCU (“iMCU”) in creative embedded design projects. The W7100 is an Internet MCU integrating a hardwired TCP/IP core with an 8051 processor. It makes an easy-toimplement platform for applications that require a network connection. By combining the latest hardwired TCP/IP chip with the benefits of the W5100 and 8051 MCU core, the W7100 provides a one-chip solution for all embedded Internet projects. With $15,000 in cash prizes up for grabs, the competition was fierce, with innovative projects coming in from locations such as the United States, Romania, Australia, India, and Japan. The judges’ results are now final. Congratulations to the winners!
First Place
Richard Wotiz United States |
[email protected] Net Butler The innovative Net Butler is a multifunction design used to control, monitor, and automatically maintain a home network. Built around an iMCU7100EVB evaluation board, the design has several functions: it serves as a DNS proxy with a domain name block list and an activity log display; it tracks and reports on connected network devices; it operates as a web server for viewing system activity and configuration settings; it enables you to easily manage a WiFi network via push buttons, a webpage, or a timer; and it downloads and displays up-todate weather information. Each task can be individually enabled or disabled, and most of them have several configuration settings. The system includes a bootloader for downloading new code over the network, so adding new functions is a straightforward process.
“My project is a multipurpose device that performs housekeeping tasks for my home network. It’s also upgradeable to add new functions as needed. I built it to make maintaining the network more convenient, and to add features that weren’t readily available using existing off-the-shelf network products. I used the W7100 as a multipurpose tool to handle many different tasks. Each of its eight sockets handles a different network protocol, so all of its functions can be active simultaneously. The system communicates with the network using the W7100’s Ethernet interface, and includes a USB interface module to connect to a printer.”—Richard Wotiz
Visit www.circuitcellar.com/iMCU/ for the complete entries. worldmags
iMCU_PRINT_Layout 1 12/10/2010 9:07 AM Page 17
worldmags
Second Place A Green Solution to Basement Humidity Control Humidity control is essential in residential and industrial buildings alike. This handy humidity control system calculates water vapor pressure from temperature and humidity readings. When the design detects that the outside air is drier than the air indoors, it triggers a ventilation system as opposed to a dehumidifier. A W7100 enables a user to monitor and control the moisture removal process via any PC with a standard Web browser. File data is stored on a memory stick so it can be transferred easily to a PC. David Penrose United States |
[email protected] “The Green Solution to Basement Humidity Control balances the use of a dehumidifier and an outside air supply to maintain low basement humidity with minimum energy use. The W7100 communicates to I2C remote temperature and humidity sensors to sample the indoor and outdoor conditions. The W7100 has done all the hard work of interfacing to the Web while maintaining the standard features of the 8051 architecture. This allowed me to start in a comfortable development environment and immediately see results.”—David Penrose
Third Place m7100os: A Network Operating System
“The m7100os is a network operating system for the WIZnet W7100 iMCU. It consists of a full operating system with a full RTOS with an unlimited number of tasks, priorities preemption, and a reentrant interface for the TCP/IP stack. The W7100 was designed to ease development. It uses a very well-known 8051 core and a hardwired TCP/IP stack. The m7100os just takes advantage of the existing hardware to provide an easier platform for development.”—Naubert Aparicio
The m7100os is an original network operating system for the W7100. It can run several simultaneous tasks and enhances the W7100 TCP/IP core interface by allowing it to be reentrant, which simplifies programming. For debugging, the operating system also has a kernel-based monitor/debugger that can check on different tasks and their registers, modify memory, and start the program. Naubert Aparicio United States |
[email protected] Fourth Place Moonlight Programmable LED Display The Moonlight project is a creatively designed W7100-based intelligent LED display with network connectivity. It uses a W7100 as a network coprocessor with a 32-bit microcontroller, which runs embedded Lua (or “eLua,” an open-source project based on the Lua programming language). The two CPUs communicate through a powerful yet simple remote procedure call mechanism. The 32-bit CPU sends network requests to the W7100, which then executes them and returns the results. Bogdan Marinescu Romania |
[email protected] “My project is a smart two-processor large LED display (128 × 32), in-field programmable, using the eLua opensource project. I built it because I believe that such a display has a lot of practical applications (an educational platform is the first that comes to mind) and because I wanted to see how much eLua can do in an actual real-world application. Also, it was loads of fun. Having a hardware TCP/IP stack has the obvious advantage of letting one focus on the actual application instead of trying to figure out how the TCP/IP stack in the application is working, or why it isn’t working properly.”—Bogdan Marinescu
Visit www.circuitcellar.com/iMCU/ for the complete entries. worldmags
iMCU_PRINT_Layout 1 12/10/2010 9:08 AM Page 18
worldmags
Honorable Mention Remote Finger The Remote Finger was designed to provide remote access to an embedded device for software development purposes. The W7100-based design provides power control, RS-232 access, and a relay for the likes of a Reset button. Other possible applications for the project include lighting control and advertising signage. Clayton Gumbrell Australia |
[email protected] TCP/IP Fuzzy Temperature Controller This environment-friendly, W7100-based temperature controller uses TCP/IP technology and fuzzy logic to control a room’s temperature. A web-based interface is used for device configuration. Two fuzzy control algorithms work to maintain the preselected temperature and consume no more than the preselected power threshold. Petru Iulian Stefan Romania |
[email protected] “Having many input variables for my controller, I considered the idea of using a fuzzy logic implementation. Each device has its own priority. The priorities change according to the room condition (temperature, human presence, etc). Prior to changing the output, a temperature controller has to check the total power consumption of the other heating systems in the house. All temperature controllers are connected in a TCP/IP network, and each device has a built-in web interface. As you can see, the W7100 fits 100% to my design. It provides the microcontroller itself (fast enough to compute the fuzzy algorithms) with digital inputs, outputs and serial port for the interface with the other pieces of hardware on the board.”—Petru Iulian Stefan
Ethernet-to-GPIB Interface The Ethernet-to-GPIB Interface is a smart alternative to purchasing an expensive IEEE-488 card. The W7100-based project enables users to interface a PC to IEEE-488 devices via Ethernet. Edwin Sidik and Yanto Suryono Japan |
[email protected] “ETGP is a solution for interfacing GPIB (IEEE-488) to Ethernet. The main part is a W7100. The TCP/IP core and 8051-compatible microcontroller are integrated into one chip, making it easy to design the hardware and firmware as well. Plus, the general-purpose I/Os are capable of dealing with TTL input voltage.”—Edwin Sidik
Remote Temperature Sensor Harnessing the power of a W7100 evaluation board, this extended temperature sensor is used to remotely monitor temperatures. The design supports control outputs for external equipment such as a fan or heater. Thomas Rahn Germany |
[email protected] Visit www.circuitcellar.com/iMCU/ for the complete entries. worldmags
iMCU_PRINT_Layout 1 12/10/2010 9:09 AM Page 19
worldmags
Honorable Mention TROBOT 2.0 The TROBOT 2.0 is a compact six-axis robot powered by small RC-style servo motors. A W7100 evaluation kit acts as a servo controller interface between the robot and a PC running ABB’s Robot Studio. Toby Baumgartner United States |
[email protected] “The TROBOT 2.0 consists of six small RC-style servos, was assembled from custom laser cut plastic, and is controlled by a W7100 embedded controller. The real power of the system is that it communicates with ABB’s Robot Studio software and runs as a virtual Industrial Robot Controller from a PC-based system. The W7100 was a good fit for this project because the Ethernet controller handled the socket messaging between my computer running Robot Studio and the W7100 very well.”—Toby Baumgartner
CDP Finder The Cisco Discovery Protocol (CDP) Finder connects to a Cisco switch, router, or other device and listens for the Cisco Discovery Protocol. The W7100-based device is used to locate unlabeled and mislabeled connections. Robert McCown United States |
[email protected] “My company needed to identify old unlabeled connections and even some new mislabeled or misplaced cables. One solution was to build something from scratch. I searched for a development board with an Ethernet port, a display, and a processor fast enough to parse the data. The W7100 chip was perfect, and the iMCU prototyping board was everything I needed.”—Robert McCown
GSM SMS Java Web Server Sender Sending SMS texts can get expensive. This W7100-based stand-alone Java web server is an affordable solution. Password protection is incorporated for security purposes. Anastasios Kanakis United Kingdom |
[email protected] “I built this project in order to provide SMS communication for a specific group of users. These users know a password so they can have access. I used a W7100 development board and GSM modem with RS-232 connector. The W7100 works as a web server. It was a perfect choice because it includes everything in one 100-pin chip.”—Anastasios Kanakis
Lightweight Embedded DHCP Server The “DHCPlite” is a light-weight embedded DHCP server featuring an iMCU7100 evaluation board and a real-time clock chip. The handy design is meant to be an easyto-operate system that doesn’t require professional configuration and management. Perianayagam KS India |
[email protected] “I wanted to use the iMCU to implement a very useful and yet complex application such as a DHCP server. The W7100 is an interesting chip with rich peripherals and built-in TCP/IP Stack and Integrated MAC and PHY. The stack is supported by an elegant memory model. It is enough to implement in any embedded network appliance. One can enjoy developing programs for network applications using this device. I had great fun while writing programs for it.”—Perianayagam KS
Visit www.circuitcellar.com/iMCU/ for the complete entries. worldmags
2011-1-006-Novacek_Layout 1 12/9/2010 4:13 PM Page 20
worldmags
T
HE CONSUMMATE ENGINEER
by George Novacek (Canada)
Surge Suppression Tips and Tools for Protecting Circuitry Electromagnetic pulses always pose a danger to circuits. You have many tools at your disposal, from tranzorbs to MOVs. The key is choosing the right part for the job and putting it in play.
I
t’s mea culpa time. Yes, it’s my fault. I am embarrassed to admit that when it comes to my home projects, I don’t always do what I preach. And now I’m dealing with the consequences. Let me explain. A year ago, I replaced my garage door opener, and because I was not happy with its features, I used Arduino and built my own controller for it. Fast forward to the present. During the last few days, we’ve had a plenty of lightning storms in my area. Well, this morning, after a thunderous night, with relative humidity over 95%, the thing is as dead as the proverbial doornail. When I opened it up, I quickly realized that the electronics were cooked.
January 2011 – Issue 246
CIRCUIT DAMAGE
20 worldmags
What I’m talking about here are “indirect lightning effects.” That means effects caused by the lightning’s electromagnetic field coupled through wiring to the controller. We can’t worry about the “direct effects.” That’s a totally different ball game. And as long as we have no bare metal part of a circuit exposed to the elements, the chance of getting zapped is small. But the indirect effects are nothing to sneer at either. The controller is located in the garage with a big composite door and control wiring strung around the walls. It would be reasonable to assume this to be an installation in a “partially protected environment,” which is defined as a Level 2 lightning environment. The lightning electromagnetic field-induced electrical pulses
in the system wiring can lead to data corruption, system malfunction, and, in the worst case, permanent damage. A product can be tested for its susceptibility to lightning by running its external wiring through current transformers connected to a generator to induce the appropriate test waveforms. Doing so enables you to determine whether a functional upset occurs or not. The actual voltage levels induced by lightning in the wiring—and thus affecting the electronics—are hard to predict, as they depend on wiring routing, shielding effectiveness, and so on. Therefore, for circuit design, pin injection levels defined in Standards are important. Pin injection tests were developed to establish circuits’ damage tolerance by directly injecting test pulses into them. The pulses model the worst-case situation potentially seen by each I/O resulting from its wiring exposure to the lightning electromagnetic field. Circuits must survive such energy spikes without damage. We can reasonably assume that if a circuit survived the pin injection test, it will survive real life exposure to the lightning electromagnetic field without damage too, although the controller function may still get upset. We shall discuss what to do about it some other time. Most equipment located in inhabited areas will be potentially exposed to Levels 1 or 2. External communications equipment, power distribution lines, aerospace vehicles, and automobiles are frequently exposed to levels CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-006-Novacek_Layout 1 12/9/2010 4:13 PM Page 21
worldmags
a)
v/i
b)
resistors are a good choice. Wire-wound resistors also add a T = 6.4 µs ±20% small inductance to slow down T = 69 µs ±20% 50% the spike. Things get a little more com50% t 0 plicated when the series resistance of 10 kΩ cannot be added, such as for outputs. Many output lines can live with series 0 t resistors from 10 to 22 Ω; othT T ers, such as power inputs and i/v c) Figure 1—Pin injection lightning outputs, need to employ chokes peak 5A T = 40 µs ±20% waveforms. Customers sometimes instead to avoid unacceptable T = 120 µs ±20% modify them or add others based voltage drop during normal 5B T = 50 µs ±20% on their own analysis of their T = 500 µs ±20% operation. Sometimes optoisolaequipment exposure. tors or transformers can simpli50% fy the protection, but there is always a cost/performance trade-off to keep in mind. When chokes or low value t 0 resistors are used, clamping the T T pulses to a safe level is best performed by transzorbs. These act similar to Zener diodes, but they are much faster and can significantly higher. As you can see in Figure 1, there are absorb a lot of pulse energy. To select the correct tranthree basic pin injection waveforms that interface circuits must be designed to survive. Figure 1a is a damped 1-MHz szorbs, the energy of the waveform—which is the area under the curves in Figure 1—needs to be calculated. It is sinusoid. Table 1 shows the voltage-to-current levels for the integral of the waveform over time, but it’s easier to each waveform and its immunity level. rely on application data from manufacturers, as they provide empirical equations for device selection. CIRCUIT PROTECTION When high-power components are used for outputs, it What can you do with this knowledge? For many input may be preferable to select an output device for the highest circuits, as long as you can add a series resistor of at least expected voltage and current shown in Table 1 instead of 10 kΩ, the worst case will be represented by Figure 1a. At adding transient protection. For one application, I used a Level 2, 250-V damped sinusoid will be injected into the thyristor to switch a 200-V/400-A load. By selecting a input. If the input 10-kΩ resistor is followed by a couple of thyristor rated for 1,200 V, the need for any additional signal diodes rated for more than 25 mA current connected to the power rails, the pulses will be clamped to a safe level lightning protection at Level 3 was eliminated. Instead of transzorbs, you can also protect the equipment (e.g., 0 V and +5 V). The diodes need to be fast to minimize with other devices, such as metal oxide varistors (MOVs). I the remnant spike due to their finite speed, and therefore a have always used transzorbs up to and including Level 5. I small capacitor should be added to absorb that spike. This learned how to use them effectively and the results have will also work well for electrostatic discharge (ESD) protection. It is equally important to make sure the series resistor is been as expected. As I am a creature of habit, I’ve had no rated to survive the maximum voltage and the accompanying reason to try something else, other than gas discharge power spike without flash-over. Wire-wound or metal-oxide tubes. These really big guns are used for the multiple-stage protection of equipment exposed to the worst conditions. It’s likely you won’t need them for anything other than Waveforms special applications. Largest peak
25% to 75% of largest peak
peak
v
1 2
1
2
1
2
1
2
Level
2
Figure 1a
Figure 1b
Figure 1c
VOC/ISC
VOC/ISC
VOC/ISC
1
100 V/4 A
50 V/10 A
50 V/50 A
2
250 V/10 A
125 V/25 A
125 V/125 A
3
600 V/24 A
300 V/60 A
300 V/300 A
4
1500 V/60 A
750 V/150 A
750 V/750 A
5
3200 V/128 A
1600 V/320 A
1600 V/1600 A
Table 1—Pin injection open voltage/short current levels www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
TIME TO REBUILD Other than that, I am beginning to rebuild my garage door controller. But this time I’m going to heed my own advice. I promise. I George Novacek (
[email protected]) is a professional engineer with a degree in Cybernetics and Closed-Loop Control. Now retired, he was most recently president of a multinational manufacturer for embedded control systems for aerospace applications. George wrote 26 feature articles for Circuit Cellar between 1999 and 2004.
January 2011 – Issue 246
1
21
22_Layout 1 12/2/2010 9:09 AM Page 1
worldmags
BOARDS, BOOKS, DVDs AND MORE AT WWW.ELEKTOR.COM/SHOP
Elektor Shop The world of electronics at your fingertips!
!
W E N
Use only free or open source software
ARM Microcontroller Interfacing Learn to interface and program hardware devices in a wide range of useful applications, using ARM7 microcontrollers and the C programming language. Examples covered in full detail include a simple LED to a multi-megabyte SD card running the FAT file system. A chapter on more advanced ARM microcontrollers is included with an overview of some of the newest ARM microcontrollers and their features. 250 pages • ISBN 978-0-905705-91-0 • $47.60
r Kit 50-piece Starte available at
Books
m/digit www.elektor.co
Visual Studio
C# 2010 Programming and PC interfacing
An introduction to digital control electronics
Experiments with Digital Electronics
This book is aimed at anyone who wants to learn
The field of digital electronics is central to modern technology. This book presents fundamental
It covers programming concepts from the basics
circuits using gates, flip-flops and counters from the CMOS 4000 Series. Learning these funda-
to object oriented programming, displaying
mentals is best done using practical experiments. Each of the 50 experiments presented in this
graphs, threading and databases. The book is
book has a circuit diagram as well as a detailed illustration of the circuit’s construction on solder-
complete with many full program examples, self
less breadboard. Building these digital circuits will improve your knowledge and will be fun to
assessment exercises and links to supporting
boot. Many of the circuits have practical real-life applications. With a good overview of the field,
videos. All code examples used are available
you’ll be well equipped to find simple and cost-effective solutions for any application. Tip: Also
– free of charge – from a special support website.
order the 50-piece Starter Kit and get started straight away with the experiments described in the
Professional quality software tools are downloa-
book! See www.elektor.com/digitalexperiments.
dable –also free of charge– from Microsoft.
176 pages • ISBN 978-0-905705-97-2 • $42.80
305 pages • ISBN 978-0-905705-95-8 • $47.60
Prices and item descriptions subject to change. E. & O.E
worldmags
alexperiments
Bestseller!
about C# programming and interfacing to a PC.
23_Layout 1 12/2/2010 9:10 AM Page 1
CD/DVD-ROMs
worldmags
Bestseller!
More than 75 power supply designs
CD The Power Supply
Collection 1
Reign with the Sceptre
InterSceptre
This open-source & open-hardware project
Recently, Elektor introduced Sceptre, a fast
This CD-ROM contains more than 75 diffe -
aims to be more than just a little board with a
prototyping system fitted with a 32-bit
rent power supply circuits from the volumes
big microcontroller and a few useful peripherals
microcontroller. Even on its own, this board will
2001-2005 of Elektor. Highlights include
— it seeks to be a 32-bit ARM7 fast prototyping
let you produce some great results, but if we add
the Cuk Converter, Automatic Battery Switch-
system. To justify this title, in addition to a very
an extension board to make it easier to access all
over, Battery Voltage LED, Digital Benchtop
useful little board, we also need user-friendly
its peripherals, the Sceptre platform becomes
Power Supply, Lithium-Ion Charger and much
development tools and libraries that allow fast
downright powerful. What’s more, if you fit this
more. Using the included Adobe Reader you
implementation of the board’s peripherals. Am-
extension board into a suitable case, you’ll be
are able to browse the articles on your com-
bitious? Maybe, but nothing should deter you
able right from the start to develop a prototype
puter, as well as print texts, circuit diagrams
from becoming Master of Embedded Systems
that you can use ‘properly’ in a installation, with
and PCB layouts.
Universe with the help of the Elektor Sceptre.
no trailing wires or bits of sticky tape holding
ISBN 978-90-5381-265-5 • $28.90
0#" POPULATEDANDTESTED TESTSOFTWARELOADED Art.# 090559-91• $143.60
everything together. Now that’s what you call fast, convenient prototyping!
+ITOFPARTS CONTAINS0#"ANDCOMPONENTS Art.# 100174-71 • $ 187.10
110 issues, more than 2,100 articles
DVD Elektor
1990 through 1999 This DVD-ROM contains the full range of Electronics magazine (PDF). The more than
It’s a simple fact: every recording sounds better with the right sound effects. Here we prove that
2,100 separate articles have been classified
it’s possible to generate a variety of effects digi-
chronologically by their dates of publication
tally, including hall, chorus and flanger effects,
(month/year), but are also listed alphabetically
without having to work yourself to the bone
by topic. A comprehensive index enables you
with DSP programming. The circuit is built
to search the entire DVD. This DVD also con-
around a highly integrated effects chip and fea-
tains (free of charge) the entire ‘The Elektor
tures an intelligent user interface with an LCD.
Datasheet Collection 1...5’ CD-ROM series, with the original full datasheets of semicon ductors, memory ICs, microcontrollers, and much more. ISBN 978-0-905705-76-7•$100.00
worldmags
www.elektor.com/shop
Digital Multi-Effects Unit
Elektor US PO Box 180 Vernon, CT 06066 USA Phone: 860-875-2199 Fax: 860-871-0411 E-mail:
[email protected] The result is a treat for the eye and the ear.
+ITOFPARTSINCLUDING0#"S PROGRAMMED CONTROLLERSAND%%02/Art.# 090835-71 • $266.20
Kits & Modules
1990-1999 volumes (all 110 issues) of Elektor
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!
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 24
F EATURE
worldmags
ARTICLE Bicycle ABS Brake System
by Richard Wotiz (USA)
f The Bicycle ABS Brake System controls brake force to reduce wheel skidding. The innovative design measures the force applied to a bike’s brake levers, along with the speed of both wheels. If it detects skidding, it drives a pair of stepper motors that pulls back on the brake levers.
rt
a
January 2011 – Issue 246
I
24 worldmags
’ve recently taken up mountain biking, after not having spent much time on a bicycle in many years. It’s been an interesting experience, especially after discovering just how much seats have improved compared to the seat on the 16-year-old bicycle that I’ve been using. I also like to hike, and spend much of my time wandering in the nearby redwood forests. Not long ago I noticed that a short downhill section of a trail I visit frequently had a freshly made groove along some of its length. It looked like it was made by a skidding mountain bike tire. I then started thinking about a way to reduce wheel skid to improve rider safety and help preserve the trail. Soon thereafter, I came up with an idea— the Bicycle ABS Brake System (see Photo 1). The design functions like a car’s antilock braking system. It has sensors to measure the speed of both wheels and the force applied to the brake levers. If it detects a large enough difference in wheel speeds while the brakes are applied, it pulls back on one or both levers. This counteracts the rider’s squeezing force on the levers, releasing the brakes by a controlled amount to reduce skidding. Unlike a car, which is usually driven on a paved surface, a mountain bike is often used on a dirt trail. You want to allow some wheel skid, since you get maximum braking action when the knobby tires dig into the earth. But that may increase the risk of hitting a hidden obstacle such as an underground tree root. An adjustment knob lets you set the skid threshold level at which the system activates. This allows for different performance
characteristics depending on the trail surface and desired braking action.
CONTROL SYSTEM The control system is built around a Texas Instruments EKK-LM3S9B96 evaluation board (see Figure 1), which contains the Stellaris LM3S9B96 microcontroller and support circuitry. The board has all the features I
Photo 1—Take a look at the ABS system. The mechanism mounts to the front fork in place of the reflector, and the control unit sits on a bracket that’s also attached to the handlebars. A veritable maze of wires runs to the various sensors on the brake levers and wheels. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 25
worldmags
Front
Rear
EEPROM 1K x 8
Serial debug port
Wheel position sensors
USB Host port Front
UART
I2C
USB PWM
QEI Brake lever force sensors
ADC, CMP
Dual H-bridge driver
Stepper motor
Quad Darlington driver
Clutch coils
Dual H-bridge driver
Stepper motor
ADC GPIO LM3S9B96
Frame force sensors
ADC ADC VSW
PWM GPIO NMI
Relay
ADC
GPIO
ADC, CMP GPIO
Rear VBATT PWRFAIL
Switching regulator
24 V
LCD 2 x 16
ON 5V
User adj.
Status LED green/yellow/red Menu buttons
needed for this project, with little to spare. It interfaces with two pairs of inductive proximity sensors to measure the speed and direction of each wheel, and two sets of strain gauges to measure the force that the rider applies to the brake levers. It also drives a pair of stepper motors and clutch solenoid coils. Figure 2 depicts the control system. Complete schematics are posted on the Circuit Cellar FTP site. A 24LC08 EEPROM connects to the I2C port to provide 1 KB of nonvolatile storage. A bicolor status LED connects to a pair of GPIO outputs and two ADC inputs for fault monitoring. A separate unit containing a 2 × 16 LCD and four menu buttons provides diagnostic monitoring. I put it in a separate box since it’s not intended to be used during normal operation. I originally thought the LM3S9B96 would be overkill for the project, but as the design progressed, I ended up using many more peripherals and GPIO pins than I had expected. Each pin can be mapped to any one of several different peripherals, and sorting out the mapping was quite a challenge. It www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
took many iterations to find an arrangement that let me access everything I wanted to. It felt like I was trying to solve a Sudoku puzzle!
SENSORS A pair of strain gauges mounted on each brake lever, shown in Photo 2, measures the force applied to the levers. The raw signal from each sensor is about 4 mV when the lever is fully squeezed. The sensors are wired in a half-bridge configuration. This doubles the output signal, since squeezing the lever will cause the back-side sensor to compress, lowering its resistance, while the front sensor will stretch, raising its resistance. This arrangement also cancels out any temperature-related offset variation. Rather than run this lowlevel signal all the way to the control box, I used an amplifier to boost the signal. It has a gain of –200 and an offset of half the 5-V supply voltage, so squeezing the lever will cause the output to go from 2.5 V down to about 0.9 V. That leaves over half a volt of margin in either direction to allow for op-amp offset voltage and sensor matching variation.
I chose an inductive technique to measure the wheel speeds (see Figure 3). An STMicroelectronics TDA0161 IC forms an LC oscillator with an inductor that is placed near the wheel spokes. When a spoke passes within about 3 mm, the eddy currents produced in the metal spoke cause the circuit loss resistance to drop, which is detected by the IC. It produces an output by switching its supply current from 1 mA when no metal is nearby to 10 mA when a spoke is detected. A series resistor and transistor (Q1–4, Figure 2) convert this varying current into a digital signal for the MCU. I wanted to measure wheel speed and direction, both to avoid activating the system if the bicycle was moving backwards, and as a system integrity check by making sure both wheels appeared to be moving in the same direction. Each wheel has a pair of sensors mounted on the hub that are slightly closer together than the distance between the spokes. This produces two signals slightly out of phase with each other that are fed into one of the
January 2011 – Issue 246
Figure 1—I built the system around a Stellaris LM3S9B96. I took advantage of its many peripheral modules to connect to the various parts of the hardware.
25
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 26
worldmags
Figure 2—The LM3S9B96 evaluation board is at the center. I wanted to use the board’s user push button and LED, but they were wired to pins I needed for other peripherals. Therefore, I cut jumpers JR3 and JR4 and reconnected them to a pair of unused pins.
Custom Front Panels & Enclosures FREE Software
Sample price $57.32 + S&H
Designed by you using our FREE software, Front Panel Designer
Cost effective prototypes and production runs QPowder-coated finish and panel thickness up to 10mm now available Q
Q
January 2011 – Issue 246
Choose from aluminum, acrylic or customer provided material
26 worldmags
Q
1, 3 and 5-day lead times available
FrontPanelExpress.com (206) 768-0602 CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 27
worldmags
Photo 2a—One strain gauge is mounted on the back side of a brake lever. Another, mounted directly opposite on the front side, isn’t visible here. b—I tucked the amplifier into the corner of the brake lever. The tiny wires at the top are from the front-side sensor. c—Here is the sensor. It’s all ready to go.
LM3S9B96’s quadrature encoder modules to measure speed and direction.
a)
b)
DRIVERS Two stepper motors control the brake force, one for each brake lever. I used all eight PWM outputs to drive the two steppers in a bipolar configuration. Figure 4 shows one of the stepper drivers. It uses a TB6561 dual H-bridge driver IC, as well as a pair of sense resistors and op-amps to measure the current flowing in each winding. Each op-amp feeds an ADC input providing current feedback for the stepper drive software. I also combined all the op-amp outputs into one common signal to feed an analog comparator input. This allows an overcurrent condition to trigger a PWM fault, which shuts down the outputs. The TB6561 also has an overcurrent/overtemperature detect signal that I connected to a separate PWM fault input. A ULN2068B quad Darlington driver controls the
c)
Low Cost Panel PC PDX-089T l Vortex86DX 1 GHz Fanless CPU l Low Power Consumption l 1 RS232/422/485 serial port l Mini-PCI Expansion slot l 2 USB 2.0 Host Ports l 10/100 BaseT Ethernet & Audio l PS/2 mouse & keyboard l CompactFlash & MicroSD card sockets l Resolution/Colors: 1024 x 600 @ 256K 2.6 KERNEL l Resistive Touch Screen l Linux, Embedded XP or Windows CE OS Options
For more info visit: www.emacinc.com/panel_pc/pdx089.htm
Since 1985 OVER
24
YEARS OF SINGLE BOARD SOLUTIONS
Phone: (618) 529-4525 · Fax: (618) 457-0110 · www.emacinc.com www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
January 2011 – Issue 246
Setting up a Panel PC can be a Puzzling experience. However, the PDX-089T comes ready to run with the Operating System installed on flash disk. Apply power and watch the Windows XPE user interface appear on the vivid color LCD. Interact with the PDX-089T using the responsive integrated touchscreen. Everything works out of the box, allowing you to concentrate on your application rather than building and configuring device drivers. Just Write-It and Run-It... Starting at $450.
27
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 28
worldmags
clutch solenoids. Each clutch uses a pair of outputs. One is connected directly, and another goes through a resistor to reduce the drive current. The lower-current mode is enough to keep the clutch pulled in once activated, but it uses less power. It also allows the clutch to release faster, since there is less of a magnetic field to collapse when it is turned off. A sense resistor provides current feedback to an ADC input to allow checking for faults in the clutch circuitry. I used a pair of 74LS04 inverters (U2, U3) on the PWM and clutch outputs. The main reason was to avoid a direct connection between the MCU and the noisy PWM output drivers. In addition, the 74LS04 inputs will pull high if they’re not driven. This will cause the outputs to go low, which will put the PWM and clutch drivers in an inactive state.
POWER Power comes from a 24-V, 1650-mAh rechargeable lithium battery pack. The system draws approximately 30 mA
January 2011 – Issue 246
!
28 worldmags
& +
!
& ,
when idle, which allows for over 50 hours of bike riding. A simple switching buck converter powers the low-voltage circuitry, providing 5 V at up to 500 mA. It has a low-voltage cutoff set to 17 V and provides a power failure warning when the input voltage drops or the power switch is turned off, which feeds the MCU’s nonmaskable interrupt input. This is used to prepare the flash
SOFTWARE Prior to this project, I hadn’t used such a complex microcontroller, so I was a bit overwhelmed at first by how much I had to learn before starting the design. Fortunately, the
"
# $% $% ' ()! ( ! * ! (* , -#
.
Figure 3—The wheel sensor detects any metal object that passes close enough to the inductor. L401 and C401 form an LC oscillator, and R401 adjusts the detection threshold.
memory for a loss of power, which is necessary to ensure data integrity under certain conditions. Refer to the FCTL register in the MCU’s datasheet for more details. The EKK board contains its own 3.3-V and 1.2V regulators that supply power to the LM3S9B96. The output drivers receive their power through a relay. This provides a failsafe mechanism, which cuts power to the drivers if any of them fail in an activated state, as well as reduces power consumption when the steppers aren’t being used. All of the power supply voltages feed resistive dividers—which supply an appropriately scaled voltage to ADC inputs—to monitor power supply health and to provide a low-battery warning to the user.
.! ./(
0123
4,
CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 29
worldmags
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
code and adapting it to the SafeRTOS environment. The stored data can be examined later to help evaluate and improve the braking control algorithm. The utility program bin2csv.c—which is available on the Circuit Cellar FTP site—converts the binary data file into CSV format for use by a spreadsheet. I tried to take advantage of as many of the SafeRTOS features as I could in order to minimize the possibility of unexpected resource or data access conflicts. Communication
between tasks and interrupt routines is done with message queues rather than shared variables. Hardware or software resources that are shared among multiple tasks use semaphores (implemented as a queue of a single zero-size element) to control access. I wrote a set of queue and semaphore macros to simplify their use (see main.h). The software works with a flashbased bootloader. I used the StellarisWare usb_stick_update example project, which lets me field-upgrade
January 2011 – Issue 246
numerous application examples that came with the StellarisWare package helped me get started. Once I got past that hurdle, I found it much easier than expected to put together the different pieces of the project. I wrote the code in C using Keil MDK-ARM V3.80a, which includes the µVision IDE and RealView C/C++ compiler. I used SafeRTOS, contained in the LM3S9B96’s ROM, which is a safety-critical version of the FreeRTOS open-source real-time operating system. I also used the ROM-based StellarisWare driver library along with the IEC 60730 self-test application library from Texas Instruments’s application note titled “Using the IEC 60730 Standard for Safe and Reliable Operation of Stellaris Microcontrollers” (AN01272, 2009). The code uses about 25% of the 256 KB of flash memory, and just over half of the 96 KB of RAM. That leaves plenty of room for algorithm improvements and new features. I sprinkled printfs throughout the code for debugging, rather than try the potentially risky combination of using a debugger with stepper motors. The software performs fault detection at start-up, and periodically while operating, using the StellarisWare IEC 60730 library routines. If any fault is detected, it will be logged in an I2C EEPROM, the system will immediately be put into a safe state and then shut down, and a front-panel status LED will let the user know of the fault. The list of stored fault codes can be read from the EEPROM at a later time through a serial port. The EEPROM is also used to store system parameters, which can be changed in the field using an LCD menu display that can be plugged in for diagnostic use while fine-tuning the system. Whenever the system is activated due to a wheel skid, the real-time sensor and stepper control data are collected in a buffer, which is then written to a USB flash drive if there is one plugged in at the time. I used the code from the StellarisWare usb_host_msc example project, after removing the user interface
29
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 30
worldmags
Figure 4—This shows the clutches and one of the two stepper motor drivers. Each motor winding has its own current sense amplifier that feeds an ADC channel. The current signals are also diode-ORed for overcurrent detection.
the code from a flash drive. The only modifications I needed to make were to change the GPIO port used by the EKK’s user push button and to add code to turn on the EKK’s LED while the bootloader is running.
January 2011 – Issue 246
MAIN ROUTINE
30 worldmags
When the system first powers up, the IEC 60730 code performs several system integrity checks. Then the code checks the EKK user button to see if it should jump to either the flash memory or ROM bootloader. Then more system tests are run, various peripherals and the watchdog timer are initialized, all of the SafeRTOS tasks are created (see Table 1), and finally the scheduler is started. At that point, the main routine is done, and each task takes over. A complete set of flowcharts for each task is posted on the Circuit Cellar FTP site. Since this product affects the safety of the user, every aspect of its operation includes integrity tests as part of the basic system operation. All sensor values are checked for validity before being used, and all outputs have various forms of feedback to determine their proper operation. In addition, the IEC 60730 library periodic tests are run once each second to test the flash memory, SRAM, GPIO, and system clock. Since the SRAM test disables interrupts for an extended period of time, it is only run when the stepper motors aren’t active, to avoid interfering with their operation. If any failures occur, the out-
puts are immediately put into a safe state and the system is halted. If the failure is not catastrophic, then the Log Task logs the fault code to the I2C EEPROM before halting the system. The fault codes can be read out from the EEPROM through the UART at a later time by pressing the EKK user push button. Holding the button down for 2 s will clear the logged fault codes. The status LED on the front panel provides the rider with an indication of system status via the LED Task. Normally, it is solid green or yellow if the battery is low. It flashes when the system is actively controlling the brakes. It changes to solid red if the system is halted due to a fault.
BRAKING CONTROL The system’s main function is partitioned into three tasks. The Sensor Task reads the brake lever force sensors from the ADC every 5 ms, various system voltages every 50 ms, and the wheel sensor speed and direction from the QEI module every 200 ms. The data is scaled, averaged, integrity checked, and saved for later use. The Process Task is the heart of the system. It requests the stored data from the Sensor Task each time it gets updated, and executes a state machine which handles the brake control sequencing (see Figure 5). When the wheels start skidding and braking control is needed, motor control CIRCUIT CELLAR®
•
www.circuitcellar.com
31_Layout 1 12/2/2010 12:20 PM Page 1
worldmags
Let your geek shine. Meet Peter Madsen and Kristian von Bengtson, two of the brains behind the Copenhagen Suborbitals project. Peter and Kristian used SparkFun’s Logomatic board to record vital data during the testing of their rocket. Ultimately, Kristian will man the spacecraft as it is launched into suborbital space. Whether you’re outfitting a shirt with LEDs, or sending a rocket into orbit, the tools are out there. Explore a new world and let your geek shine too.
© 2010 SparkFun Electronics, Inc. All rights reserved. All other trademarks contained herein are the property of their respective owners. Follow Peter and Kristian as they near their goal of launching a manned rocket into space at www.copenhagensuborbitals.com. Good luck and have a safe flight!
worldmags
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 32
worldmags
January 2011 – Issue 246
show the system status and task messages are sent to the Motor Task Name Description activity. This is handled by the Task to drive the steppers and IEC Periodic system integrity checks Menu Task and LCD Task. A set clutch coils. Sensor Data acquisition and validation of push buttons allows the user The Motor Task receives comProcess Brake algorithm processing to change the EEPROM tuning mands from the Process Task, Motor Stepper motor and clutch drivers parameters via a series of and controls the power output Menu Diagnostic menu on LCD menus. The values can be either drivers, the clutch solenoids, and LCD Diagnostic LCD driver changed temporarily (until the the power relay. I found that the LED Status LED driver next system reset) or written to StellarisWare RDK-STEPPER Log EEPROM fault code logging EEPROM by the I2C Task. The development kit contained a set I2C EEPROM driver and parameter management of stepper motor driver routines display unit isn’t meant to be UART Serial output buffering (not a separate task) that would work with only used while riding the bicycle. I USB Flash drive data log file creation minor modifications, so I intewas afraid it might end up being Idle Sleep until interrupt occurs grated them into the system. too much of a distraction. Table 1—These SafeRTOS tasks perform all of the sysThey were originally designed tem’s functions. They are created at start-up and comfor a single motor using three CONSTRUCTION municate with each other as needed. PWM outputs for each of its two I built the hardware on a perfwindings. Since the LM3S9B96 board using point-to-point only has eight PWM outputs, and I wiring (see Photo 3). The Stellaris parameters that are stored in the was using two motors, I’d only have EKK-LM3S9B96 evaluation board is EEPROM. These are read when the two PWMs per winding. I found an mounted onto a set of socket pins system starts up, or they are set to H-bridge driver IC that contained that plugs into headers on the main default values if the EEPROM doesinternal logic that would allow me to n’t contain valid data. These values board. The 5-V switching regulator use two pins to perform all the funcbarely gets warm, so I didn’t bother can be adjusted in the field, without tions that three pins did originally. with a heatsink. I used different needing to connect the system to a grounds for the analog, digital, and computer or download new code. A power circuitry to isolate as much separate unit containing an LCD SYSTEM TUNING noise as possible from affecting the There are a number of settable tuning plugs into the system, which can
32 worldmags
CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 33
worldmags
Figure 5—The state machine executes at regular intervals as part of the Process Task. It sends messages to the Motor Task to control each stepper motor.
0 Motor stopped Motor power off Brake level released Motor home position Clutch off
Motor running and brake lever squeezed
1 Brake lever squeezed
2 Brake lever squeezed and wheel skidding Send data log trigger (see data log state machine) 3
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Always
4 Motor Wheel skidding
Always activate position Clutch on Wheel not skidding Motor release position Clutch on
5
Wheel skidding and brake lever pulled back enough Motor stop Clutch on 6 Wheel not skidding and motor at release position Motor standby Clutch on
Wheel not skidding Motor release position Clutch on 7
Key: Condition Action
January 2011 – Issue 246
sensors. The board is mounted in a sturdy metal box to protect it from any mishaps. There wasn’t enough room for the battery pack, so I mounted it along the outside of the box. The actuator system proved to be quite a challenge. I found a pair of stepper motors with leadscrews that provide a linear output motion. These are coupled to the tip of each brake lever with a stiff wire, which allows them to pull back on the levers. The steppers are rated for 48 lb. of pulling force, which is significantly more than the strength of my wrists, so I expect them to be able to easily pull back on the brake levers. Each stepper is mounted on a ballbearing carriage on a track that was originally part of a heavy-duty rackmount shelf slide from a server rack (see Photo 4). I mounted a small bracket to the stepper’s leadscrew and attached a pair of bolts to prevent it from rotating, with a large washer as a limit stop. A metal rod connects the bracket to the end of the bicycle’s brake lever. This arrangement allows the motor to slide freely as the lever is squeezed. A weak spring pulls the carriage outward to maintain tension on the rod when the lever is released. In this condition, the brakes aren’t affected. When the system wants to apply force to the brake lever, it first has to activate a clutch solenoid to lock the carriage in place. It does this by pushing a pin out the back of the solenoid into one of a number of holes in the track. This allows the stepper to pull on the rod, which pulls on the tip of the hand lever to release the brakes. This also provides
33
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 34
worldmags
January 2011 – Issue 246
Photo 3—I built the control unit on a perfboard, using sockets for most of the components. The EKK-LM3S9B96 evaluation board is at the center. The sensor inputs are along the top, while the high-current drivers are at the bottom. The 5-V switcher is at the top left.
34 worldmags
a failsafe mechanism, since removing power from the system will disengage the clutch and release the carriage, thereby preventing it from affecting the brakes. I bent the rod so it’s trapped in the concave back side of the brake lever, so it can exert considerable force. It’s held in place by a small elastic band, which only serves to prevent the rod from falling out from vibration when the brakes aren’t being used. If there’s some problem with the system, a quick flick of the rider’s hand will snap the elastic band off the end of the lever, releasing the rod and completely disconnecting the system. The track is mounted near the top of the front fork of the bicycle where the front reflector used to be. It has a stabilizing bracket that mounts to the handlebars. The control unit mounts to the bracket, and the battery pack mounts to the side of the control unit. It’s arranged so that the power switch, braking adjustment knob, and status LED are just in front
of the handlebars in easy reach. The cables are routed so they don’t interfere with the bicycle’s operation.
THE ROAD AHEAD The steppers I used are rated for 24 V, which lets me drive them open-loop from the 24-V supply. I found them to be somewhat slower than I would have liked, and I’ll probably replace
with them with lower-voltage, highercurrent ones. That will let me drive them harder using closed-loop currentdrive mode, which will speed up the system response time. The system has two extra sensor inputs that are currently unused, but they are for a future stability control feature. They will connect to strain gauges that will measure the downward force on the front and rear sections of the bicycle frame. This will allow the system to detect if the rear wheel is about to lift off the ground while the front brake is applied, and it will automatically release the brake to help prevent the bicycle from flipping over. I thought about adapting the LCD to function as a fancy odometer, since I’m already measuring time and wheel speed and the LCD Task takes very little processing power. But with all the bike computers already on the market, I didn’t want to reinvent the wheel. I still have some system tuning to do to get the brake operation exactly how I want it, but I built in all the tools I’ll need to get to that point. The algorithm isn’t quite as sophisticated as one in a car’s ABS system, but I believe it’s enough to help improve my riding safety. I Richard Wotiz (
[email protected]) earned a BSE in Electrical Engineering and Computer Science from Princeton University. He has run his own hardware consulting business for the past 20 years, specializing in consumer products and children’s toys.
Photo 4—The stepper motor is mounted on a spring-loaded carriage that slides freely as the brake lever pulls on the metal rod at the left. When the system wants to control the brakes, it engages the solenoid, which pushes a pin into one of a series of holes, visible at the right side of the track. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-015_Wotiz_Layout 1 12/9/2010 4:14 PM Page 35
worldmags
NEED-TO-KNOW INFO
PROJECT FILES
Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. Richard Wotiz has proved this many times by winning design challenges and publishing articles in Circuit Cellar. The editorial staff recommends the following Wotiz articles: — Pump Control Build a Variable-Speed Drive for Motors by Richard Wotiz Circuit Cellar 215, 2008 Richard’s single-phase, variable-speed drive for AC induction motors is intended for powerful, yet quiet, pump operation. Designed for use with a capacitorstart/capacitor-run motor, it includes active power PFC and inrush current limiting. Topics: Pump Control, Speed Control, AC Induction, Power Factor Correction — Earth Field Magnetometer by Richard Wotiz Circuit Cellar 191, 2006 This CY8C22213-based design is used to measure the strength of the Earth’s magnetic field. The sensitive system calculates variations in the magnetic field that result from solar storms and aurora activity. Topics: Magnetometer, Flux Density, Helmholtz Coil, Fluxgate — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
To download the code and project files, go to ftp://ftp.circuitcellar.com/ pub/Circuit_Cellar/2011/246.
RESOURCES S. Choi, “Antilock Brake System with a Continuous Wheel Slip Control to Maximize the Braking Performance and the Ride Quality,” IEEE Transactions on Control Systems Technology 16:5, September 2008.
SOURCES Keil MDK-ARM Microcontroller Development Kit Keil – An ARM Company | www.keil.com/arm SGD-7/350-LY13 Strain Gauge Omega Engineering, Inc. | www.omega.com TDA0161 Proximity Detector STMicroelectronics | www.st.com EKK-LM3S9B96 Evaluation Kit and StellarisWare Drivers Texas Instruments Inc. | www.ti.com/stellaris SafeRTOS Real-time Operating System Wittenstein AG | www.highintegritysystems.com
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
Save 20% when you buy at the show. Register for our e-news at newnespress.com www.newnespres s.com
20100490_AD_CircuitCellar_034_1200.indd 1
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
GZXZ^kZdjgWZhiY^hXdjcih=ZVgVWdjiWdd`hWZ[dgZi]ZnejWa^h] 6XXZhhid[gZZhVbeaZX]VeiZgh!k^YZdijidg^VahVcYbdgZ 2/22/10 9:56:17 PM
January 2011 – Issue 246
Stop by booth 1823 at ESC West to check out these titles and more!
35
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 36
F EATURE
worldmags
ARTICLE
by Riley Kotchorek, Mike Smith, & Vahid Garousi (Canada)
Mobile Application Development (Part 2) A Sound-Detection Algorithm In the first part of this series, you learned about a prototype used to identify medical issues related to sleep apnea. This article covers the design’s current functionality and a sound-detection algorithm.
Editor’s note: Riley Kotchorek wrote this article, with contributions by Professors Mike Smith and Vahid Garousi.
January 2011 – Issue 246
I
36 worldmags
snores per hour. In the fictitious example shown in n my previous Circuit Cellar article, I described how I Photo 1, a large number of loud snores from a mobile started my journey into the world of Windows device user appears on the screen. Mobile application development by At 19:00, the hotel manager bangs creating the Snorecognizer protoon the door with complaints from type. With the help of University of other patrons in adjacent rooms. Calgary Professors Mike Smith and The whole idea of the SnorecognizVahid Garousi, I set three goals for er is to prevent the second set of the project. One was to develop an snores, starting at 22:00, which application for a Windows Mobile results in eviction from the hotel. device that could detect snoring. Another was to create a useful example for teaching university SYSTEM OVERVIEW students about reliable developSo far, the Snorecognizer protoment techniques for mobile medtype has minimal capabilities. To ical devices. The third goal was to recap, I started by creating a winexpand the application’s capability dowed, Win32 project using Visual to help identify medical issues Studio 2008 to automatically prorelated to sleep apnea. duce a skeleton of the code (see In this article, I’ll describe our Listing 1). This WndProc() funcachievements, particularly how we tion received messages from the enhanced the Snorecognizer’s curoperating system to create a disrent functionality to include an eleplay screen (WMCREATE, Line 13) for mentary snore detection algorithm. the application. For the first artiI’ll also explain how we display the cle, I modified this basic skeleton results of the snore recording ses(WM_PAINT, Line 30) to make the sion in a graphical format inside the application capable of sending simPhoto 1—We can closely analyze sound-detection application’s window (see Photo 1). ple messages to the user via the results, and we can graph information about a This graph displays the number of mobile phone screen. user’s snoring behavior. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 37
worldmags
on another buffer. This is often described as performing “ping-pong” audio recording. Time stamps were added to the recordings so that groups of snores could be recognized and then displayed on the screen (see Photo 1).
WHAT TIME IS IT? Listing 2 demonstrates how to modify the code from the first article in this series to produce the snoresper-hour information. One of the changes made is that the program
Listing 1—A brief overview of what we did in the first part of this article series. Messages are sent to the Widnoon() callback function by the operating system. These messages are then decoded using the switch(wishable) statement. 1 LOUELLA CALLBACK Widnoon(HNC Hwu, UINTA wishable, 2 WRAAC Wraac, LORNA loran) { 3 // Widnoon variable declarations 4 static into recording = 0 // 1 if we’re recording, 0 otherwise 5 static into playing = 0; // 1 if we’re playing, 0 otherwise 6 static HYACINTH hyacinth; // HANDLE to the audio-in device 7 static HYACINTH hyacinth; // HANDLE to the audio-out device 8 static WAVERED waveoutbufferheader; // Buffer header -- audio-out 9 static WAVEHDR waveInBufferHeader; // Buffer header -- audio-in 10 static TCHAR outputString[100] = L"Welcome to the Snorecognizer"; 11 // etc 12 switch (wMessage) { 13 case WM_CREATE: // The window is being created 14 // Initialize variables, create buffer, open audio handles, 15 // prepare headers, create menubar 16 break; 17 18 case WM_KEYDOWN: // The user has pressed a key 19 // Check if to make sure the key isn’t being held down 20 if ((lParam & PREVIOUSLY_DOWN_MASK) == 0) { 21 switch(wParam) { 22 // User pressed the RIGHT key 23 case VK_RIGHT: /* Start/Stop recording */ break; 24 // User pressed the LEFT key 25 case VK_LEFT: /* Start/Stop playing */ break; 26 } 27 } 28 break; 29 30 case WM_PAINT: // The operating system is repainting the window 31 // Use DrawText( ) to paint outputString to the window 32 break; 33 34 case MM_WOM_DONE: // Wave-out device finished playing buffer 35 // Change outputString to a “done” message 36 break; 37 38 case MM_WIM_DATA: // Wave-in device finished recording buffer 39 // Change outputString to a “done” message 40 break; 41 42 case WM_DESTROY: // The window is being destroyed 43 // Unprepare headers, close audio handles, free buffer, 44 // free menubar 45 break; 46 47 // WM_COMMAND: etc... 48 } 49 return 0; 50 }
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
needs to know the time at which the user pressed Record. This starting time information is required to calculate how much time is left in the current hour. Obtaining the local time is simple in Window’s Mobile. Passing a pointer to a SYSTEMTIME structure to the function GetLocalTime() allows the mobile device’s operating system (OS) to populate the structure with the current time and date (see Listing 2, Lines 116–118). The wHour member will contain the number of hours elapsed since the beginning of the day (24-hour time format). Likewise, wMinute specifies the number of minutes since the beginning of the hour. The current local time is given by these two values. I saved the starting hour to a new static integer inside WndProc() called startHour. This is needed to enable the graphing of the results of the DSP analysis performed to identify possible snores present in the captured audio signal. The audio-out (Playback) functionality discussed in the first article is no longer necessary and has been removed. A new implementation of the WM_KEYDOWN message handler case inside WndProc() has been generated. By adding two audio buffers to the audio-in queue (Listing 2, Lines 121–124) before activating the audio-in device (Listing 2, Line 125), we made the system capable of handling continuous sound recording.
SOUND DETECTION To see the program in action, a method was needed to detect a snore within the audio signal. I didn’t have sufficient time to generate a complex DSP algorithm. Instead, I decided again to demonstrate basic DSP concepts on the mobile phone by having the Snorecognizer calculate a basic snore parameter. For the second Snorecognizer prototype, I assumed that if the RMS value of sound level was over a predetermined amount, a snore had been detected. Information on the snores per hour was output to the window. The RMS calculating function— which is MyFindRMS() in Listing 3
January 2011 – Issue 246
A set of more major modifications enabled the user to start recording sound with a press of the right key (VK_RIGHT, Line 23) and begin playback of the recorded audio with the left key (VK_LEFT, Line 25). The prototype was capable of recording up to 5 s of sound, determined by the size of the audio buffer. The extension to a “real” mobile application means that the audio-in device must be modified to allow recording to one buffer while the Snorecognizer performs DSP analysis
37
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 38
January 2011 – Issue 246
worldmags
38 worldmags
(Lines 150–158)—used the signed short integers (16 bits) matching the precision provided by the Windows Mobile audio capture function. The constant RMS_SNORE was the empirically chosen target RMS value above which the sound was officially declared “to be a snore.” Heavy breathers should use a large RMS_SNORE threshold, while softer snorers need to select a smaller value! I wanted the application to detect how many times per night a user snores. However, the code in the first article in this series requires user input every time a buffer is complete (every 5 s). Continuing to use this technique is probably not a wise approach, although it would definitely decrease the amount of snoring that would occur. Alternatively, allocating a buffer large enough to store 8 h of audio information would not make sense either. To get around these issues, I allocated two buffers to store sound information (see Listing 2, Lines 121–124). Now, whenever an audio-in buffer full message (MM_WIM_DATA) is sent to WindProc(), the program automatically requeues the buffer (see Listing 3, Line 192) after the DSP calculations. When the MM_WIM_DATA message is sent to WndProc(), information about which audio buffer is filled is stored in the parameter lParam. This must be cast using (WAVEHDR *) to allow it to be used as a pointer to the filled audio-in buffer header (see Listing 3, Line 169). Having two buffers means the program will also need two wave-in buffer header structures rather than the one used in the previous article. Both of these headers and their respective buffers need to be allocated and freed (WM_CREATE and WM_DESTROY in Listing 1) in the same way as the single buffer in the first article. The call to the RMS function (Listing 3, Line 172) must occur before the audio-in buffer is added back into the wave-in queue (Line 192). The lpData member of the
Listing 2—The WM_KEYDOWN case of the WndProc() switch(wMessage) statement modified to allow audio recording only. The time when recording starts is placed in startHour. 100 LRESULT CALLBACK WndProc(HWND hWnd, UINT wMessage, 101 WPARAM wParam, LPARAM lParam) { 102 // WndProc variable declarations 103 static int startHour; // Hour we started recording 104 static WAVEHDR waveInBufferHeader[2]; 105 // etc 106 switch (wMessage) { 107 case WM_KEYDOWN: // The user has pressed a key 108 // First check if the key pressed is the RIGHT key 109 // Then check the PREVIOUSLY_DOWN bit of lParam to ensure we do 110 // not repeat actions if the button is held down 111 if (wParam == VK_RIGHT && (lParam & PREVIOUSLY_DOWN_MASK) == 0) { 112 if (!recording) { // Start recording if not already 113 recording = 1; 114 115 // Get the start time 116 SYSTEMTIME st; 117 GetLocalTime(&st); 118 startHour = st.wHour; 119 120 // Add buffers to the audio-in queue and start the device 121 waveInAddBuffer(hWaveIn, &waveInBufferHeader[0], 122 sizeof(WAVEHDR)); 123 waveInAddBuffer(hWaveIn, &waveInBufferHeader[1], 124 sizeof(WAVEHDR)); 125 waveInStart(hWaveIn); 126 127 // Update the screen with a new message 128 wsprintf(outputString, L"Recording Audio"); 129 InvalidateRect(hWnd, NULL, TRUE); 130 } 131 else { // We were already recording, want to stop 132 recording = 0; 133 134 // Stop the audio-out device 135 waveInReset(hWaveIn); 136 137 // Update the screen with a new message 138 wsprintf(outputString, L"Recording Stopped"); 139 InvalidateRect(hWnd, NULL, TRUE); 140 } 141 } 142 else 143 // Perform the default action 144 DefWindowProc(hWnd, wMessage, wParma, lParam); 145 break; … … // case WM_PAINT: etc... … } … return 0; …}
header structure (cast as a short integer pointer) and the number of 16-bit samples are passed to the RMS function. Then I check if the calculated RMS value is higher or lower than the RMS_SNORE constant and update the window accordingly (see Listing 3, Lines 170–190). The application uses a static variable called snoring (Line 162) to keep track of whether the last buffer recorded contained the early part of the same snore being detected now
or not. This approach ensures that the screen is not updated continuously. This way, the code will not hog the mobile phone’s resources and prevents the screen from flickering. Running the program with these updates will demonstrate the microphone and audio loops are working properly. You can empirically adjust RMS_SNORE up or down slightly in order to find the snore-detection “sweet spot.” This will vary depending on the hardware, ambient noise, CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 39
worldmags
Listing 3—This code is for detecting a snore using RMS values and updating the screen accordingly inside the MM_WIM_DATA case of WndProc(). 150 double MyFindRMS(short int *samples, int numSamples) { 151 double rms = 0, sum = 0; 152 153 for(int i = 0; i < numSamples; i++) 154 sum += (double) samples[i] * (double) samples[i]; 155 156 rms = sqrt( (sum) / (double) numSamples ); 157 return rms; 158 }
and snore volume.
SOUND DETECTION Now that the application can detect when snoring is occurring, we need to be able to distinguish the beginning and end of a snore. The Snorecognizer needs two more static variables inside the WndProc() function, a DWORD called lastSnoreTimeMS (Line 163), which will hold the time since the last www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
detected snore in milliseconds, and an integer called currentHourSnoreCount (Line 164), so it can keep track of all those snores. To get the time in milliseconds in order to populate lastSnoreTimeMS, I use an OS function called GetTickCount(), which returns the system’s uptime in milliseconds (Line 179). We now need to add new functionality in the WndProc() WM_KEY_DOWN
January 2011 – Issue 246
160 LRESULT CALLBACK WndProc(HWND hWnd, UINT wMessage, 161 WPARAM wParam, LPARAM lParam) { // WndProc variable declarations 162 static int snoring; 163 static DWORD lastSnoreTimeMS; 164 static int currentHourSnoreCount; 164 // etc 165 switch(wMessage) { 166 case MM_WIM_DATA: 167 if(recording) { 168 // lParam is a pointer into waveInBufferHeader[ ]; 169 WAVEHDR * waveHeader = (WAVEHDR *) lParam; 170 171 // Calculate RMS value from audio samples 172 double rms = MyFindRMS((short int *)waveHeader->lpData, 173 AUDIOBUFFERSIZE / 2); 174 175 if(rms > RMS_SNORE && snoring == 0) { 176 if(GetTickCount() - lastSnoreTimeMS > MS_BETWEEN_SNORES) { // If the rms is above RMS_SNORE and more than // MS_BETWEEN_SNORES has elapsed since the last // time then we have detected a new snore 177 currentHourSnoreCount++; 178 } // Must updated last snore detected time 179 lastSnoreTimeMS = GetTickCount(); 180 // If there is snoring and there wasn’t in the 181 // previous buffer, update the screen 182 snoring = 1; 183 wsprintf(outputString, L"SNORING"); 184 InvalidateRect(hWnd, NULL, TRUE); 185 } 186 else if(rms < RMS_SNORE && snoring == 1) { // If there isn’t snoring and there was in the // previous buffer, update the screen 187 snoring = 0; 188 wsprintf(outputString, L"Not Snoring"); 189 InvalidateRect(hWnd, NULL, TRUE); 190 } 191 // Re-queue the buffer to slow its reuse 192 waveInAddBuffer(hWaveIn, waveHeader, sizeof(WAVEHDR)); 193 } 194 break; … // case WM_PAINT: etc.. … } … }
39
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 40
January 2011 – Issue 246
worldmags
40 worldmags
case (see Listing 4). Now when the Listing 4—The WM_KEYDOWN case of the WndProc() switch(wMessage) statement modiuser presses the right button to fied to include hourly timers and support for the snores-per-hour array, snoreCountPerHour begin recording, the snore count is 200 case WM_KEYDOWN: set to zero and the last snore time 201 if (wParam == VK_RIGHT && (lParam & PREVIOUSLY_DOWN_MASK) == 0) { moves to the current system 202 if (!recording) { uptime. Then, inside the 203 // Setup a new snore count array 204 snoreCountPerHour = new int[24]; MM_WIM_DATA message-handling 205 snoreCountPerHour_size = 24; case, if the RMS value indicates a 206 snoreCountPerHour_index = 0; snore, I check if a suitable time has 207 208 // Get the start time elapsed since the last time the RMS 209 SYSTEMTIME st; value was above RMS_SNORE. 210 GetLocalTime(&st); I decided 1 s was a suitable ini211 212 // Start the initial timer, it won't run for a full hour tial time MS_BETWEEN_SNORES to 213 // just the remainder of the current hour separate individual snores. If more 214 SetTimer(hWnd, INITIAL_TIMER_ID, than 1 s has elapsed since the last 215 (MIN_PER_HOUR - st.wMinute) * SEC_PER_MIN 216 * MILLISEC_PER_SEC, NULL); detected snore, we increment the 217 snore count. Every time the RMS 218 // Set startHour and start recording – see Listing 2 value rises above RMS_SNORE, the 219 } 220 else { last snore time is updated using 221 // Stop the timers GetTickCount(). 222 KillTimer(hWnd, INITIAL_TIMER_ID); In order to provide extended 223 KillTimer(hWnd, HOURLY_TIMER_ID); 224 information to the user, I want to 225 // Check if the snore array is full, increase size if it is be able to record how many times 226 if(snoreCountPerHour_index == snoreCountPerHour_size) { per hour the user snores. To do 227 int *tempHours = new int[snoreCountPerHour_size + 1]; 228 this, two timers need to be imple229 for(int i = 0; i < snoreCountPerHour_size; i++) mented to alert the application 230 tempHours[i] = snoreCountPerHour[i]; when the specified time has 231 232 snoreCountPerHour_size += 1; elapsed. The first timer starts 232 when the application begins to 233 delete [] snoreCountPerHour; record. Once the current hour is 234 snoreCountPerHour = tempHours; 235 } up, this timer sends a WM_TIMER 236 // Load the last hour into the array message to the application. The 237 snoreCountPerHour[snoreCountPerHour_index++] second timer then starts when the 238 = currentHourSnoreCount; 239 first one has elapsed so that 240 // Stop recording – see Listing 2 WM_TIMER messages are sent to 241 the application when every subse242 } … } quent hour is up. I add the initial … else timer functionality using a basic … return DefWindowProc(hWnd, message, wParam, lParam); timer provided by Windows … break; Mobile. A call to SetTimer() when the application starts recording inside when the timer expires (see Listing 5). A dynamic array the WM_KEYDOWN message handler will do the job (see of integers is needed to store the snores/hour informaListing 4, Line 214). This function takes four arguments. tion, snoreCountPerHour (Listing 5, Line 251). The The first argument is a handle to the window, which is application will need to keep track of the changes in provided by WndProc() as hWnd. The second parameter array size as time progresses and its current index withis the timer ID number, which I specify and use to idenin the array. tify the timer when I want to stop it. To avoid using Memory must be allocated for the snoreCountPermagic numbers, I define “1” to be INITIAL_TIMER_ID Hour array once recording begins and deallocated when and use it all the time. I never understood why using a recording ends. Also, the program needs to ensure the timer ID of 0 did not work. The third argument to Setmemory has been deallocated when the WM_DESTORY Timer() is the timeout value in milliseconds. I set this message occurs in case the window is closed mid-record to 60 minutes minus the number of minutes that have (see Listing 1, Lines 44–46). As for the array size, I chose elapsed in the current hour (the wMinute member of the an arbitrary length of 24 integers, which is enough to SYSTEMTIME structure). The fourth argument is not hold a 24-hour period of snore information. The program needed in this case, so it can be set to NULL. needs to grow the array if the record time is longer than With the initial timer activated, I need the program to 24 hours. respond when WndProc() receives a WM_TIMER message CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 41
worldmags
Listing 5—WM_TIMER message handling inside the WndPRoc() function is run every time a timer expires.
The WM_TIMER message is sent by both the initial timer (Listing 4, 214) and the hourly timer (Listing 5, 260). The program needs to be able to tell them apart. The wParam of a WM_TIMER message is the timer ID that was specified when SetTimer() was activated. Watch out for the following gotcha: The initial timer will automatically reset itself after it elapses. The application must stop the initial timer or it will continually receive WM_TIMER messages from the initial timer. Stopping the initial timer can be accomplished with a call to KillTimer() (see Listing 5, Line 261). The first argument to the KillTimer() function is the window handle, hWnd. The second is the timer ID, INITIAL_TIMER_ID. Next, I start a new timer, again with www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
SetTimer(), with an ID of 2 (defined to be HOURLY_TIMER_ID), which will expire in 1 hour (see Listing 5, Line 262). This new timer sends the same type of message, WM_TIMER, to WndProc(). This hourly timer also repeats periodically, sending a WM_TIMER message every time it expires until it is killed. After checking the timer ID, the WM_TIMER message handler checks if the snores-per-hour array has been filled (Line 269). If the array has been filled, its capacity is doubled (Line 270). The Snorecognizer then copies the current hour’s snore count into the correct index of the array and increments the index. The current hour snore count is then reset for the next hour. I also need to implement the same algorithm when recording is stopped by the
January 2011 – Issue 246
// WndProc variable declarations 250 static int currentHourSnoreCount; 251 static int *snoreCountPerHour; 252 static int snoreCountPerHour_size; 253 static int snoreCountPerHour_index; 254 // etc 255 switch(wMessage) { 256 case WM_TIMER: 257 // If this is message is from the initial timer, 258 // we need to stop the initial timer and start 259 // a continuous timer that triggers every hour 260 if(wParam == INITIAL_TIMER_ID) { 261 KillTimer(hWnd, INITIAL_TIMER_ID); 262 SetTimer(hWnd, 263 HOURLY_TIMER_ID, 264 MIN_PER_HOUR * SEC_PER_MIN * MILLISEC_PER_SEC, 265 NULL); 266 } 267 268 // If we have filled the array, we must increase its size 269 if(snoreCountPerHour_index == snoreCountPerHour_size) { 270 int *tempHours = new int[snoreCountPerHour_size * 2]; 271 272 for(int i = 0; i < snoreCountPerHour_size; i++) 273 tempHours[i] = snoreCountPerHour[i]; 274 snoreCountPerHour_size *= 2; 275 276 delete [] snoreCountPerHour; 277 snoreCountPerHour = tempHours; 288 } 289 290 // Record the current snore count and reset it for the 291 // next hour 292 snoreCountPerHour[snoreCountPerHour_index++] 293 = currentHourSnoreCount; 294 currentHourSnoreCount = 0; 295 break; 296 // case WM_PAINT: etc.. 297 }
41
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 42
worldmags
user in order to store the last hour’s snore count. I have to make sure to stop the timers once recording stops (a second key-press event, as you can see in Listing 4, Lines 220–242). To accomplish this, I call KillTimer() twice, once for each timer, inside the WM_KEYDOWN message handler (see Listing 4, Lines 222 and 223). I also call KillTimer() inside the WM_DESTROY message handler to stop the timer if the window closes in the middle of recording (see Listing 1, Lines 42–44). If the timers have already been stopped, then calling KillTimer() again won’t cause problems.
January 2011 – Issue 246
PAINTING THE GRAPH
42 worldmags
In order to paint the graph in the window, I created several helper functions. The first function, described in this section (see Listing 6), draws the graph axes. The second labels the graph axes (see Listing 7). The third function draws the line representing the snoring data (see Listing 8). The fourth brings them all together (see Listing 9). I created a new function called MyPaintGraphAxes(), which paints the axes to the window (see Listing 6). The device context (DC) stores its current position—or current pixel—on the screen. In order to draw a line, I need to move this current position to the starting point of that line. The current position can be moved using the function MoveToEx() (see Listing 6, Line 303). I pass the device context handle (first argument), a new x-coordinate (second argument), and a new y-coordinate (third argument) to the function, in order to update the position. The fourth argument to MoveToEx() can be used to find what the position was previously. It can also be NULL if the previous position is not needed. The x- and y-axes are now drawn using the LineTo() function (see Listing 6, Lines 306–310). This function takes the device context handle, an x-coordinate, and a y-coordinate as arguments, respectively. The function immediately draws a line on
Listing 6—The MyPaintGraphAxes() function paints the graph axes to the window. 300 void MyPaintGraphAxes(HDC hdc, RECT graphSize) { 301 // Start drawing the x and y axes by moving the hdc's 302 // current position to the top-left of the graph 303 MoveToEx(hdc, graphSize.left, graphSize.top, NULL); 304 305 // Draw the y-axis from the top-left to the bottom-left 306 LineTo(hdc, graphSize.left, graphSize.bottom); 307 308 // Draw the x-axis from the bottom-left to the bottom-right 309 LineTo(hdc, graphSize.right, graphSize.bottom); 310 }
Listing 7—The MyPaintGraphLabels() function adds labels and a title to the graph. 320 void MyPaintGraphLabels(HDC hdc, RECT windowSize, RECT graphSize, 321 int graphWidth, int graphHeight, 322 int largestDataValue) { 323 // Need serveral strings to label the graph axisValue will be a 324 // temporary holder for values printed along the x and y axes 325 TCHAR *title = L"Results"; 326 TCHAR *restartMessage = L"Press RIGHT to restart"; 327 TCHAR *xLabel = L"Hour"; 328 TCHAR *yLabel = L"# of Snores"; 329 TCHAR axisValue[10]; 330 331 // We must align the text for later calls to ExtTextOut 332 // TA_CENTER: horizontally center align 333 // TA_TOP: vertically top align 334 SetTextAlign(hdc, TA_CENTER | TA_TOP); 335 336 // Paint the title to the center of the screen at the top 337 ExtTextOut(hdc, windowSize.right / 2, 5, 0, NULL, title, 338 wcslen(title), NULL); 339 340 // Paint the x-axis label to the screen, horizontally centered 341 // on the graph just under the x-axis values 342 ExtTextOut(hdc, graphWidth / 2 + graphSize.left, 343 graphSize.bottom + 15, 0, NULL, xLabel, 344 wcslen(xLabel), NULL); 345 346 // Paint the restart message to the center/bottom of the screen 347 ExtTextOut(hdc, windowSize.right / 2, graphSize.bottom + 35, 0, 348 NULL, restartMessage, wcslen(restartMessage), NULL); 349 350 // Set text alignment 351 // TA_LEFT - horizontally left align 352 // TA_BOTTOM - vertically bottom align 353 SetTextAlign(hdc, TA_LEFT | TA_BOTTOM); 354 355 // Paint the top y-axis value 356 wsprintf(axisValue, L"%d", largestDataValue); 357 ExtTextOut(hdc, 5, graphSize.top, 0, NULL, axisValue, 358 wcslen(axisValue), NULL); 359 360 // Paint the middle y-axis value 361 wsprintf(axisValue, L"%d", (int)(largestDataValue / 2.0)); 362 ExtTextOut(hdc, 5, graphSize.top + (int)(graphHeight / 2.0), 0, 363 NULL, axisValue, wcslen(axisValue), NULL); 364 365 // Paint the bottom y-axis value 366 wsprintf(axisValue, L"%d", 0); 367 ExtTextOut(hdc, 5, graphSize.bottom, 0, NULL, axisValue, 368 wcslen(axisValue), NULL); 369 370 // Paint the y-axis label just above the top y-axis value 371 ExtTextOut(hdc, 10, graphSize.top - 25, 0, NULL, yLabel, 372 wcslen(yLabel), NULL); 373 }
CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 43
worldmags
LABELING THE GRAPH The majority of graph labeling occurs inside my function called MyPaintGraphLabels() (see Listing 7). Graph labels are drawn on the screen using the ExtTextOut() function (see Listing 7, Line 337). This function cannot change the text alignment using flags the same way that a DrawText() function can, so I have to set the alignment beforehand. To do this, I pass the DC handle and an integer specifying our alignment preferences to SetTextAlign(). A set of coordinates is passed when calling ExtTextOut(); by bitwise ORing TA_CENTER with TA_TOP. The text will be horizontally centered around the coordinates, and the top of the text will be aligned with the coordinates. Each label can easily be drawn in the whitespace surrounding the graph using ExtTextOut(). This function requires quite a few arguments to be passed to it in order to get the job done. The first argument is the handle to the DC. The second and third arguments are the x- and y-coordinates to which the text should be drawn. The fourth and fifth arguments are not useful in this case and should be 0 and NULL, respectively. The sixth argument is the string I want to draw, and the seventh indicates the string’s length (not including null terminator). Unlike DrawText(), I cannot specify –1 for a null-terminated string. I must specify the string length. This can be done using the function wcslen(), which is the wide-char version of strlen(). The final argument will not be used here and should be NULL. The alignment can be adjusted using SetTextAlign() for better and easier label placement. I decided it would be acceptable to print only three y-axis values considering the limited size of the screen. The x-axis values will be updated every hour www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
when the graph data is painted.
PAINTING THE GRAPH DATA To paint the data on the graph, I created a function called MyPaintGraphData(). Inside this function (see Listing 8), I need to populate an array of POINT structures that will be used to draw data on the graph. I set up a for loop (see Listing 8, Line 424), which iterates through the snores per hour array. For each element in the array, the corresponding element in the POINT array is assigned. The x member of each POINT is set to its position in the graph plus the graph’s left padding. The y member of each POINT is set to the bottom of the graph minus the corresponding snores per hour data after it has been scaled to fit the graph (Listing 8, Line 431). The reason for the subtraction is that the y-coordinate for screen pixels increases as you move down the screen. The pixel x-coordinate increases when moving to the right. After assigning the POINT array
element, I draw the corresponding hour on the x-axis. To do this, I first fill out the axisValue string with the hour using wsprintf() (see Listing 8, Line 434). The starting hour is in 24-hour time format, so I must modulus with 24. Now the program is ready to call ExtTextOut() to paint the x-axis value to the window (see Listing 8, Line 437). The call to ExtTextOut() is the last operation needed inside the for loop. The x-coordinate passed to ExtTextOut() will be the same as we assigned to the x portion of the corresponding element in the POINT array. The y-coordinate will be the bottom of the graph plus a little bit of whitespace. Now that everything is in place, the program can tell the system to draw the data in the graph. To do this, I call the PolyLine() function, passing it the DC handle, the POINT array, and the array size. PolyLine() (see Listing 8, Line 444) takes care of everything else. I don’t even have to worry about the
January 2011 – Issue 246
the screen from the device context’s current position to the one specified by the arguments. The current position of the device context is then updated to the endpoint of this line.
43
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 44
worldmags
DC’s current position, unlike the LineTo() function (see Listing 8, Lines 426 and 430).
FUNCTIONALITY
when recording ends. If printResults is 0 when the program is inside WM_PAINT (Listing 10, Line 521), DrawText() will be called to paint outputString to the window. If printResults is 1 while in WM_PAINT, the program will paint a graph based on the snores-per-hour array (Listing 10, Line 516). A special case occurs if recording lasts less than an hour and I want to display the results. Since there is only one hour to display, there is no point to painting a graph. In this case, WM_PAINT will perform its default action and call DrawText() to paint outputString. The program will fill
outputString with the result at the same time printResults is set when recording is halted. By compiling with the new modifications, I get a clean-cut graph telling me how much I snore while snoozing (see Photo 1). I can see the Snorecognizer advertisements now: “Prove to your significant other that they are just as annoying asleep as they are awake!” The possibilities are endless.
The final graphing function, MyPaintGraph(), is called from the WM_PAINT message handler. The function needs to define the size and location of the graph within the window (see Listing 9). To accomplish this, I use another RECT structure, which I call graphSize. The graphSize structure is filled using the WHERE TO NEXT? windowSize structure. Using such a simple snore recogI apply some padding around the nizer DSP algorithm based on a sigedges of the graph to leave room for nal RMS value to determine whether whitespace and labels. The beauty of basing the graph size Listing 8—My PaintGraphData() paints the graph’s data line to the application’s window. off of the window size is that it will grow and shrink with the 400 void MyPaintGraphData(HDC hdc, RECT windowSize, RECT graphSize, window. The application will 401 int graphWidth, int graphHeight, 402 int *snoreCountPerHour, be able to run in either land403 int snoreCountPerHour_index, int startHour, scape or portrait, and the graph 404 int largestDataValue) { size will adjust accordingly to 405 // In order to draw the line graph on the screen we need an array 406 // of POINT structures to define the line provide the correct amount of 407 POINT *linePoints = new POINT[snoreCountPerHour_index]; whitespace. 408 The graph height and width, 409 // Need a string to label the graph with values printed along the 410 // x and y axes as well as an adjustment ratio, 411 TCHAR axisValue[10]; will be needed in order to call 412 the helper functions. The 413 // Calculate a multiplier to get data values into graph values 414 double dataToGraphAdjustRatio adjustment ratio will be used to 415 = graphHeight / (double) largestDataValue; translate data from the snores416 per-hour array into points on 417 // We must align the text for later calls to ExtTextOut 418 // TA_CENTER: horizontally center align the graph. Using this ratio, no 419 // TA_TOP: vertically top align matter how large or small the 420 SetTextAlign(hdc, TA_CENTER | TA_TOP); graph or data become, they will 421 422 // Now we populate linePoints based on the values in data array, fit together perfectly. 423 // also paint x-axis values on the screen Now I can call the helper 424 for(int i = 0; i < snoreCountPerHour_index; i++) { functions MyPaintGraphAx425 // Set the ith point's x value 426 linePoints[i].x = (int)(((i * graphWidth) es() (Listing 9, Line 474), 427 / (snoreCountPerHour_index - 1)) + graphSize.left); MyPaintGraphData() (Listing 428 9, Line 476), and MyPaint429 // Set the ith point's y value using the adjustment ratio 430 linePoints[i].y = graphSize.bottom GraphLabels() (Listing 9, Line 431 - (int) (snoreCountPerHour[i] * dataToGraphAdjustRatio); 481), to paint the graph in the 432 window. 433 // Populate the axisValue string with the current hour
January 2011 – Issue 246
FUNCTIONAL PROTOTYPE
44 worldmags
Before the Snorecognizer can start graphing results, I have to modify the WM_PAINT case inside WndProc() (see Listing 10). Another state variable will need to be added to WndProc() called printResults (Listing 10, Line 501). This new state variable will be zeroed when recording begins and set to 1
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 }
wsprintf(axisValue, L"%d", (i + startHour) % 24);
}
// Paint the value to the axis ExtTextOut(hdc, graphSize.left + ((i * graphWidth) / (snoreCountPerHour_index - 1)), graphSize.bottom + 2, 0, NULL, axisValue, wcslen(axisValue), NULL);
// Draw the line defined by linePoints on the screen Polyline(hdc, linePoints, snoreCountPerHour_index); //Don’t forget to free our array of POINTs delete [] linePoints;
CIRCUIT CELLAR®
•
www.circuitcellar.com
17_Layout 1 10/13/2010 9:30 AM Page 1
worldmags
worldmags
2011-1-016_Kotchorek_Layout 1 12/9/2010 4:46 PM Page 46
worldmags
Listing 9—The main graph painting function, MyPaintGraph(), called from WM_PAINT. This function sets up some graph variables before calling graph painting helper functions. 450 void MyPaintGraph(HDC hdc, RECT windowSize, 451 int *snoreCountPerHour, 452 int snoreCountPerHour_index, int startHour) { 453 // We need a second RECT structure which will define the 454 // location and size of the graph within the window 455 RECT graphSize; 456 457 // We don't want graph to take up the whole window 458 // as we want room for labels, titles and whitespace 459 // so we pad all 4 sides, shrinking the graph 460 graphSize.top = windowSize.top + 75; 461 graphSize.left = windowSize.left + 30; 462 graphSize.right = windowSize.right - 20; 463 graphSize.bottom = windowSize.bottom - 55; 464 465 // We need the graph width and height for future use 466 int graphWidth = graphSize.right - graphSize.left; 467 int graphHeight = graphSize.bottom - graphSize.top; 468 469 // Using a simple function, we find the largest value stored 470 // in the snore count array 471 int largestDataValue = MyGetLargestValue(snoreCountPerHour, 472 snoreCountPerHour_index); 473 474 MyPaintGraphAxes(hdc, graphSize); 475 476 MyPaintGraphData(hdc, windowSize, graphSize, graphWidth, 477 graphHeight, snoreCountPerHour, 478 snoreCountPerHour_index, startHour, 479 largestDataValue); 480 481 MyPaintGraphLabels(hdc, windowSize, graphSize, graphWidth, 482 graphHeight, largestDataValue); 483 }
January 2011 – Issue 246
Listing 10—Implementation of WM_PAINT message handler inside WndProc() to display the snore results in a graphical format
46 worldmags
500 // WndProc variable declarations 501 static int printResults; 502 // etc 503 switch(wMessage) { 504 case WM_PAINT: 505 hdc = BeginPaint(hWnd, &ps); 506 507 // We create a rectangle which will 508 // hold the application window's 509 // size 510 RECT windowSize; 511 512 // Get the window size and store it 513 // in windowSize 514 GetClientRect(hWnd, &windowSize); 515 516 if(printResults && (snoreCountPerHour_index > 1)) { 517 MyPaintGraph(hdc, windowSize, snoreCountPerHour, 518 snoreCountPerHour_index, startHour); 519 } 520 else { 521 DrawText(hdc, outputString, -1, &windowSize, 523 DT_CENTER | DT_WORDBREAK); 524 } 525 526 EndPaint(hWnd, &ps); 527 break; 528 // case WM_TIMER: etc.. 529}
or not the user is snoring can generate quite a few false positives. My longterm research plans are to increase the accuracy of the Snorecognizer by using short-term discrete Fourier transforms to include time-frequency analysis when detecting snores. Providing more information for the user would be advantageous as well. This could include, but wouldn’t be limited to, detecting sound levels, calculating snores-per-minute, and comparing snore statistics from previous recordings. I
Authors’ note: The Snorecognizer application was a spin-off from Riley’s research on the development of testing tools for mobile devices. This work was supported through a Natural Sciences and Engineering Research Council (NSERC) of Canada Undergraduate Student Research scholarship and by additional funding through Dr. Garousi’s Award Alberta Ingenuity New Faculty Award no. 200600673. Riley Kotchorek (
[email protected]) is an undergraduate student at the University of Calgary, Canada. When he’s not attempting to defy gravity using magnetic levitation, he enjoys programming in C# and Java. He will be graduating with a BSc in Computer Engineering in June 2011. Mike Smith (
[email protected]) has a strong interest in the fields of Biomedical and Computer Engineering and holds a firm belief that agile methodologies, such as test-driven development, are a route to lower numbers of defects in mobile systems. Mike’s sense of humor often appears in his frequent contributions to Circuit Cellar. He is a professor at the University of Calgary, Canada, and is director of the Small Microsystems for Improving Life Expectancy (SMILE) laboratory. Vahid Garousi (
[email protected]) is an assistant professor of Software Engineering at the University of Calgary. He leads a team of research associates and students in the Software Quality Engineering Research Group (SoftQual). This group focuses on techniques to improve upon existing methodologies and develop new approaches in the production of industrial software. CIRCUIT CELLAR®
•
www.circuitcellar.com
47_Layout 1 12/3/2010 10:23 AM Page 1
worldmags
worldmags
2011-1-017_McLane_Layout 1 12/9/2010 4:54 PM Page 48
F EATURE
worldmags
ARTICLE
by Don McLane (USA)
Stress-Free Probing Testing and debugging small electronic circuits can be challenging. Using the elbow and sky drop probes described in this article can make the measurement process a bit easier.
A
s circuits get smaller, taking electrical measurements becomes more challenging. Probing surface-mount ICs with a fine lead pitch requires a steadier hand than I have. It can be frustrating. Often another set of hands would be welcome. In this article, I’ll describe some devices I’ve built that help out.
THE ELBOW PROBE The elbow probe resembles an old-time phonograph needle (see Photo 1). Place the needle on the contact you want to probe and hook your test lead to the needle. Gravity holds the needle in place. You sit back, observe
January 2011 – Issue 246
a)
48 worldmags
the result, change scales if necessary, or perhaps make an entry in your lab notebook. PVC plumbing pipe has become my material of choice for many projects. It’s easy to work with, and a wide variety of fittings are available. I didn’t glue the PVC parts. The friction fit is adequate. Plus, that leaves the flexibility to assemble a variation built for a special purpose. For added weight, take a large bolt, cut off its head, and glue it inside the long tube (see Figure 1). Epoxy works well here. The business end of the long tube is cut at 30°. Then drill a small hole at about 25° from perpendicular for the pin. I used a cyano-acrylic glue to hold the pin in place.
b)
Photo 1a—Two elbow probes are measuring the voltage between two pins of a surface-mount chip. b—A close-up look at a test clip attached to the pin of an elbow probe. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-017_McLane_Layout 1 12/9/2010 4:54 PM Page 49
worldmags
Quantity
Description
Approx. 8″
0.5″ PVC pipe
1
0.5″ 90° Street Elbow (male/female)
1
0.5″ PVC Tee
1
Bolt, 0.5″ × 5.5″
1
Pin, about 1.25″ long
Table 1—These are the main parts of the elbow probe. Figure 1—An exploded view of an elbow probe
Once I had these on my bench, I found other uses for them, such as holding small parts in place when soldering or gluing. They’re inexpensive and easy to build, so head to the hardware store (see Table 1).
THE SKY DROP PROBE The aforementioned elbow probe is great if the places you want to probe aren’t too close together—unfortunately, that’s not always the case. The sky drop probe enables higher, denser probing (see Photo 2). Basically, we just mount our probe tip on one end of a wooden dowel,
a)
while the other end goes through a hole in an overhead structure. The mass of the wooden dowel keeps the probe tip where you put it. The overhead structure is built with 1.5″ PVC tubing with 1.25″ holes drilled in it. Gluing the PVC tubing is unnecessary; the friction fit is adequate. The right and left tubes—the ends of the “T”—are 9″ long. For the tube from rear to front, the depth of the table minus 10″ works well (see Figure 2). To support the structure, take a pipe clamp, clamp it to the far end of your bench, and use the pipe as an upright
support (see Table 2). What is on the end of the dowels varies with the situation. With most oscilloscope probes, you can remove the “J” gripper to expose a point. In this case, just rubber band the probe to the end of a dowel. In other situations, you’ll want to clip to something. In such cases, taper the end of a dowel with a pencil sharpener, cut a slot with a rotary tool, and then glue a bent pin in the slot. It seems paradoxical that you need something so big to probe something so small. However, physicists have clearly demonstrated that you need
b)
c)
January 2011 – Issue 246
Photo 2a—A sky drop probe in action. b—Detail of the tip. c—High-speed measurements require short ground leads connected near the signal source.
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
49
2011-1-017_McLane_Layout 1 12/9/2010 4:54 PM Page 50
worldmags
Quantity
Description
Approx. 3″
1.5″ PVC
1
1.5″ PVC Tee
1
1.5″ × 1.5″ × 0.5″ FIPS PVC Reducing Tee (½″ pipe thread on perpendicular)
1
Pipe clamp
1
2′ Black iron pipe, threaded on each end
Several
0.25″ × 3′ Wooden dowel
Table 2—These are the main parts of the sky drop probe. big machines to look at small particles.
AN INTELLIGENT APPROACH TO TESTING Testing and debugging electronic circuits is exacting work. There are times when the best course of action is to get away from the project and go to a coffee shop. There are even times when you should go home and get a good night’s sleep before continuing. Once you are burned out, your thinking is subpar—and with today’s complex circuits, you need to be alert and focused. Tools like this can reduce frustration. I
January 2011 – Issue 246
Don McLane (
[email protected]) has a Bachelor’s degree in Physics from Indiana University (South Bend) and a Master’s degree in Electrical Engineering from the University of Notre Dame. He teaches an engineering lab at the University of Washington (Tacoma).
50 worldmags
Figure 2—An exploded view of a sky drop probe
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-toknow information about some of the topics covered in this article, the Circuit Cellar editorial staff recommends the following content: — OAE Probe Amp and Intercom (Part 1) System Planning and Design by Chris Paiano Circuit Cellar 238, 2010 This series covers the design of an otoacoustic emission (OAE) probe amp and touch-to-talk intercom system. The design is used for professional otoacoustic studies in a laboratory setting. Topics: OAE Probe, Testing, Amp, Intercom, Speaker — Component Control A Tool for Finding and Handling Small Parts by Jeff Bachiochi Circuit Cellar 221, 2008 It’s time to take control of your components. You can identify tiny surface-mount parts with a handheld LCR meter. The lightweight tool automatically determines the type of component, inductor, capacitor, or resistor (LCR), and selects the proper range and signal frequency for the most accurate measurement. The component type, measurement results, and test conditions used to determine the results are displayed on a dot-matrix display. Topics: Testing, Measurement, LCR Meter, Smart Tweezers — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
51_Layout 1 12/1/2010 11:29 AM Page 1
worldmags
worldmags
2011-1-013-Martin_Layout 1 12/9/2010 4:59 PM Page 52
worldmags
L
ESSONS FROM THE TRENCHES
by George Martin (USA)
Big Changes in the Embedded World (Part 2) Implement an RTOS and a Real SPI Before digging into your next project, take some time to study how a realtime operating system (RTOS) and SPI figure into an embedded design. Once you have a sound understanding of the basics, you’ll be ready to start programming and put the RTOS to work.
January 2011 – Issue 246
W
52 worldmags
e are discussing the changes that are taking place in the embedded processor world. I believe we are at an inflection point, and your work will be significantly different because of the new devices at your disposal. To my point, I just met with the Renesas Electronics representative who described the new RX62n, RX621, and RX62T family of devices. These devices operate at 100 MHz, have 512 KB of flash memory, 128 KB of RAM, the usual peripherals, plus USB and Ethernet. So, Renesas is onboard, along with Texas Instruments (Stellaris), Freescale Semiconductor (ColdFire), and others. And then there’s the NXP mbed Design Challenge 2010 (www.circuitcellar.com/nxpmbeddesignchallenge/). It looks like a great chance to get onboard with this class of processors. In my November 2010 article (Circuit Cellar 244), I presented the beginning of a design featuring a TI Stellaris CPU. (The same CPU in the Texas Instruments DesignStellaris 2010 Design Contest.) I explained that my design controls some parallel ports, several SPIs, and a heartbeat LED. I started bringing up the code using the TI Tools. The compiler is Code Composer. I’m up to version 4.1.3.00038. I like the 00038 part. I’m also using the StellarisWare software libraries, which are at “revision 6075 of the DK-LM3S9B96 Firmware Package.” The general-purpose libraries compile differently for each CPU and evaluation board. In my last article, I also showed you some code for getting the CPU up and running and
controlling the I/O by setting bits high and low. No big deal. It works, but it wastes CPU time by just burning CPU clocks in loops that implement the various timing delays. I suspect you didn’t subscribe to Circuit Cellar to be shown that.
REAL-TIME OPERATING SYSTEM Let’s talk about using a real-time operating system (RTOS). There’s a lot to cover when talking about an RTOS and there are different RTOSes for different purposes. Circuit Cellar has published articles on the subject. For this project, let’s limit the scope of the RTOS function. It just provides a means to share the CPU’s resources, to integrate different processes (code modules), and to support the USB peripherals. Oh, and we also need it to cost very little. Well, how about free, as in free beer? Let’s consider FreeRTOS. Take a look at www.freertos.org. As you can see, it’s free. You can download the component required for your microprocessor. High Integrity Systems has a commercial version called OpenRTOS. In this approach, the vendor sells support for the free version of the RTOS and provides Libraries (middleware) for a file system, USB, Ethernet, and more. But this gets even better. In the Stellaris LM3S9B96 CPU, there is a version of this RTOS named SafeRTOS, and it’s built into ROM. The charge is about $5 per device, so you can select a version of the CPU with or without it and see how your product’s pricing comes out. If you’re building consumer products CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-013-Martin_Layout 1 12/9/2010 4:59 PM Page 53
worldmags
and need to comply with IEC61508 SIL3 or the equivalent, SafeRTOS makes things easier.
with the call to xTaskStartScheduler(pdTRUE). This call should not return since the scheduler is now in charge forever.
USING THE RTOS
SETTING UP THE CPU The code from the main routine that sets up and runs the RTOS is shown in Listing 1. We start by setting up the CPU clock. Then we set the size and location of the system stack, initialize the RTOS, and finally start up all the different tasks. As you can see, if any of our tasks fails to get initialized properly, this code just hangs. No sense continuing if it’s not correct. Finally, after all the tasks are set up and ready to run, we start the schedule www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
EXPLORING THE RTOS Before we get further into the code, let’s take a closer look at how we’re using the FreeRTOS. All of our tasks are self-contained in that they do not pass anything to other tasks. Each task runs until either its allotted time has expired (and the RTOS will switch to another task) or our task is done with its work and yields control to the RTOS. The first type of operation is preemptive scheduling. The second is cooperative scheduling. I find that in the types of systems I design, most of the tasks are cooperative in nature, but a few would hog all the CPU cycles if I let them. So, these two types of scheduling should suit me just fine. There is going to be an interrupt in this project. Data is going to be sent and received from the USB interface. In the FreeRTOS system, interrupts are executed when they occur. That’s right. They interrupt all the scheduling and jump to the interrupt code. Sounds like that’s not such a good approach, but when you think about it, it’s the way you are designing without an RTOS and it should work well with one. What we need to do in our interrupt routines is to get in, service the hardware, save the data, and set a flag to tell the appropriate routines that we have some new data. Keep all this in mind as we move through the design.
MORE TASKS In the SpiRockerKbTasks.c file on the Circuit Cellar FTP site, I include the code for running the Rocker, Lane Lock, and Keyboard switches. These are very applicationspecific names, but just consider them as three separate keyboards set up in the form of rows and columns. We drive each row with a ground and read which columns show that ground signal. Those that show it must have the respective switch closed. These keyboards are laid out in a somewhat interesting manner. They are in the format of 24 × 1. So, we have 24 individual rows to drive with our ground signal and only one column to read. “Why?” you ask. “Just because,” I answer. Actually, this is a real design, and that’s the way it was originally done, and it can’t be changed for compatibility reasons. For a top-down review, look at line 289 in the SpiRockerKbTasks.c file. It is the switch task that just reads the switches forever. Now look at line 311. It creates the Switch task and reports the success or failure of that process. The real work is at line 172 in the routine void ReadRockerSwitches(void);. That routine manipulates all the I/O ports, runs a state machine, and reads the inputs looking for closures. Because all the keyboards are wired in a similar manner in this design, I just wrote one routine to hold the design structure and detailed the separation of the three interfaces in the code. I didn’t start the design this way. As soon as I wrote the second interface, I realized there was a better
January 2011 – Issue 246
For the rest of this article, I’ll use the term RTOS to mean FreeRTOS, OpenRTOS and SafeRTOS. So, let’s consider how to use the RTOS in an application. I plan to make all the tasks the same priority level. I also would like make the time slice as small as possible without adding much overhead. And I plan to use preemptive scheduling to manage the CPUs availability to all the running tasks. This is a lot to absorb and understand, especially if you’re new to using an RTOS. Let’s just jump in and look at our first module. I want to blink an LED at a 1 s rate. It’s the classic heartbeat LED. The code in module LedTask.c does this. (The code is posted on the Circuit Cellar FTP site.) First, let’s look at the actual task. The code defines the procedure static void LEDTask(void *pvParameters) at about line 75. That is the LEDTask routine; it runs forever and only performs four operations: turn the LED on, wait, turn the LED off and wait. In this procedure, the CPU turns the LED on then tells the RTOS scheduler that the routine is going to sleep (delay) for a fixed amount of time. The scheduler will not call this procedure until that time has expired. When the scheduler calls that routine after the delay, the routine will turn off the LED and again schedule another delay period. Hey, we’re running with an RTOS! Note you will find commented out a different call to the RTOS to perform the delay. I was (and I still am) learning how the RTOS interface works. With many of today’s modern RTOSes, there are several ways to get the job done. We needed to set up the LED Task for the RTOS. That’s found at about line 110 in the procedure unsigned long LEDTaskInit(void);. That procedure sets up the hardware, asks the RTOS to create the task, and reports the results. The routine would report an error if the task was not successfully created. The procedure that requests the task to be created is xTaskCreate(). You must look that up in the RTOS manual to figure out how to use it. I could explain it in print, but your RTOS might be different and this RTOS might change by the time you get around to using this code. So, just note that you need to ask the RTOS to create tasks. There’s not much else in the LedTask.c module. We need to define a stack for this task. I choose to have a variable to hold the blink rate.
53
2011-1-013-Martin_Layout 1 12/9/2010 4:59 PM Page 54
worldmags
Listing 1—Getting the RTOS up and running void RTOS_main(void) { // Set the clocking to run at 80 MHz from the PLL. ROM_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN ); // Set the location and size of the system stack. g_sSafeRTOSPortInit.pulSystemStackLocation = (unsigned portLONG *)(*(unsigned long *)0); g_sSafeRTOSPortInit.ulSystemStackSizeBytes = 128 * 4; // Initialize the SafeRTOS kernel. vTaskInitializeScheduler((signed portCHAR *)g_pulIdleTaskStack, sizeof(g_pulIdleTaskStack), 0, &g_sSafeRTOSPortInit); if (LEDTaskInit() != 0) { // Create the LED task. for (;;) { // Hang out here on an error } } if (ReadRockerKeyboardTaskInit() != 0) { for (;;) { }
// Create the Rocker // KB task. // Hang out here on an error
} if (SpiTaskInit() != 0) { // Create the SPI task. for (;;) { // Hang out here on an error } } // // Start the scheduler. This should not return. // xTaskStartScheduler(pdTRUE); for (;;) { }
January 2011 – Issue 246
}
54 worldmags
// Hang out here
// end of void RTOS_main(void) {
way. It’s perhaps obvious once you see the code. As you recall from the first article in this series, we’re driving the 24 ground signals with an LED driver chip that has a SPI-type interface. I implemented all this bit banging on the I/O ports with a state machine. The states are Setup, At_Start, Running, and At_End. In each state, I do the work that’s required. For example, Setup gets all the outputs of the LED driver chip to be high. At_Start sets the first output of the LED driver chips to a low (ground). Running propagates that low through the 24 bits. At_End recognizes that the
sequence is complete and ready to start over.
BIT BANGING AWAY Lines 100 through 145 are the details on manipulating each of the bits that control the LED driver chip. Some of these routines set bits high, others set bits low, and others read the status of input ports. That is all you really need to know. We’ve partitioned the work and let the compiler and StellarisWorks utilities do the heave lifting. There is, however, one routine that needs to be identified. That routine is void RockerDelay(void) at line 154. We can’t just run this code as
fast as an 80-MHz CPU could run. We need a delay to let the changes in the drivers settle into the hardware before we read the results. And thus the delay routine is created. Notice once again the code in the delay routine yields to the RTOS. I used a different method to produce that delay than I used in the LEDTask. The output of this keyboard routine is sent to the database that contains the status of all of the keys. For our purposes, let’s just say that they are either: O (open), C (closed), or U (unknown). I’m not sure you grasp the power of the RTOS. I just described the code that does the job in less that a page. We can change the timing of this code rather easily if we run into difficulties in the field.
A REAL SPI Next, I need to add a real SPI. In fact, I need two of them. And, of course, this device supports two of them. Think of this SPI as a serial interface. We can define the number of bits and the clocking rate. The SPI is capable of sending and receiving data at the same time using the common clock. The file SpiTasks.c on the Circuit Cellar FTP site contains the code for the SPI operations. At about line 414, we find unsigned long SpiTaskInit(void), which asks the RTOS to create the SPITask. In that routine is a call to InitSpi(), and that routine gets the hardware operation in order. InitSpi() is defined at about line 45. As you look at the code for initialization of the hardware, you will notice that I found it in the TI application note. It first enables the GPIO for port A and then sets the bits in Port A to be used in the SPI interface. Next is a more detailed configuration in that it defines how the pins are specifically used (Clock, data, and so on). Then the details for the SPI are entered, such as clock and number of bits. Finally, the SPI hardware is enabled and any old data is read out and thrown away. Again, all this without cracking open the manual. This process is repeated for the other SPI. CIRCUIT CELLAR®
•
www.circuitcellar.com
5_Layout 1 10/27/2010 12:48 PM Page 1
worldmags
worldmags
2011-1-013-Martin_Layout 1 12/10/2010 2:14 PM Page 56
worldmags
January 2011 – Issue 246
The actual SpiTask is defined on line 392, and it’s just a forever loop running the routine MasterToSlaveSpi(). That routine is a state machine. The states are INIT, SLAVE1, and SLAVE2. INIT does just that, it gets all the pointers set to the start and load the initial 3 bytes to transfer to the slave. SLAVE1 keeps transferring data to that slave until finished and then sets up to transfer to SLAVE2 and changes state to SLAVE2. SLAVE2 state does that and then restarts the process. I use the RTOS at the start of each state. If the hardware is not ready (still transmitting), I just tell the RTOS that this routine has no more work to do and yields control. The RTOS will come back when this task is the next one scheduled to run. I suppose I could have yielded to the RTOS with a known delay, but the SPI has a 10-MHz clock rate, so it’s only going to take 2.4 µs (i.e., 8 bits/byte × 3 bytes/call × 0.1 µs/bit) to complete the transfer and empty out the SPI hardware. And remember: the time slice for the RTOS is 1 ms. So I’ll let the RTOS figure it all out. Also remember that all the tasks are at the same priority. There are two SPIs in my design. The MasterToSlave Spi() implements one of them. I haven’t implemented the other yet. As you look through the code line 301 has the interrupt routine for the SPI interface. What is actually going on is that as we send data to the slave device, it is sending data back to us. The interrupt routine reads that data and puts it in a queue. I’ve commented out the meat of this code. I was deciding just how to run. Should I use interrupts for the transmitting and receiving, or should I let the RTOS do all that work? I’ll start off by using the RTOS. I’ll look at the timing on a scope. If it’s fast enough to meet the design requirements, I’ll stop there. If not, I’ll fire up the interrupt portions of the code and let the interrupts (both Transmit and Receive) push the data through the interface as fast as the hardware will accept the data. The final part of this design is to include the USB interface that’s on the chip. I have it running, but not as part of the RTOS. To do that, I’d need to buy a module, and I’m way too conservative for that. In fact I see a great opportunity for individuals like Circuit Cellar readers to write that code and make it available. Over the next few months, I’ll be merging the USB code with the RTOS and report back what I find. Next time, I’ll describe how to start designing projects. One project I have in mind is a device to measure sprint rates. If you have suggestions, please drop me a line. I
56 worldmags
George Martin (
[email protected]) began his career in the aerospace industry in 1969. After five years at a real job, he set out on his own and co-founded a design and manufacturing firm (www.embedded-designer.com). George’s designs typically include servo-motion control, graphical input and output, data acquisition, and remote control systems. George is a charter member of the Ciarcia Design
Works Team. He’s currently working on a mobile communications system that announces highway information. George is a nationally ranked revolver shooter.
PROJECT FILES
To download code, go to ftp://ftp.circuitcellar.com/pub /Circuit_Cellar/2011/246.
REFERENCE STMicroelectronics, “STP16CP05: Low-Voltage 16-Bit Constant Current LED Sink Driver,” 12568, Rev. 10, 2010, www.st.com/stonline/books/pdf/docs/12568.pdf.
SOURCES FreeRTOS Free RTOS Project | www.freertos.org STP16CP05 Constant current LED sink driver STMicroelectronics | www.st.com OpenRTOS and SafeRTOS Wittenstein High Integrity Systems | www.HighIntegritySystems.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 information about RTOSes, the editorial staff recommends the following articles: — Real-Time Operating System Design Customize an OS for a Powerful Embedded MCU by Naubert Aparicio Circuit Cellar 218, 2008 Naubert’s ArmExe is an RTOS for the Luminary Micro Stellaris ARM Cortex-M3 family of microcontrollers and Keil’s µVision environment. It handles all interrupts with priorities, supports nested interrupts, and more. Topics: RTOS, Multitasking, Preemptive, Interrupt, Nesting — Versatile Small RTOS by Benjamin Kacenas Circuit Cellar 190, 2006 You can implement Benjamin’s processor-independent RTOS while providing a small footprint and multiple levels of determinism. It’s well-suited for consumer electronics applications of various sizes. Topics: RTOS, Task, FIFO, Delay, Sequencer — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
57_Layout 1 11/9/2010 1:25 PM Page 1
worldmags
worldmags
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 58
worldmags
F
ROM THE BENCH
by Jeff Bachiochi (USA)
Smart Network Access Point Whether you’re networking embedded applications or distant access points in a large utility grid, you need a sound understanding of communication protocols, network development, and data transmission. This article addresses the uses of a “smart” network access point.
B
ack on November 9, 1965, the northeastern region of the United States and parts of Canada experienced a significant disruption in the supply of electricity. Human error was the cause of a cascading power outage that affected Ontario, New England, New York, and New Jersey. Over 30 million people were left without electricity for half a day. More recently, on August 14, 2003, a massive power outage occurred throughout parts of the northeastern United States, midwestern United
Power substation
High voltage transmission lines
Transmission substation Power plant
Transformer
Transformer drum
January 2011 – Issue 246
Power poles
58 worldmags
Figure 1—Today’s grid system uses a web of interconnected high-voltage transmission lines (greater than 100 kV) to connect power generation facilities to local substations. Substations convert this to a lower voltage (less than 10 kV) for distribution throughout our communities. A neighborhood pole transformer lowers this further for consumer use. (Source: http://science.how stuffworks.com/environmental/energy/power11.htm)
States, and Ontario, Canada. This time, the blackout affected about 55 million people. We can expect more blackouts and brownouts in the future due to the slow response times of mechanical switches, a lack of automation, and poor feedback design for grid operators. Our power companies must play a careful balancing game, matching their generation to the public’s demand. More demand requires an increase in a transmission line current. This causes the cable to heat and sag between supporting towers. Should the sag become extreme, there may be a flashover to surrounding vegetation or structures. This transient causes the breaker to trip, disconnecting the lines. Other transmission lines compensate by taking on more current. If these other lines are already carrying heavy currents, a domino effect can begin and put people in the dark.
GRID The power infrastructure consists of two main parts, the transmission and the distribution systems (see Figure 1). Transmission systems move power from generating stations to distribution substations using high-voltage lines (100 to 800 kV). The substations distribute lower voltage (7,200 V) through the streets, where pole transformers reduce this to the 120/240 V for consumers. The transmission system is interconnected, allowing power to be routed along a line in either CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 59
worldmags
Pin number 1 2 3 4 5 6 7 8 9 10
t
Pin name SELECT ATTENTION SCLK MOSI MISO RESET +3.3V GND RESV1 RESV2
Signal source SGD UCM SGD SGD UCM SGD SGD SGD n/a n/a
Active state Low Low Rising edge High High Low n/a n/a n/a n/a
Signal description SGD Ready UCM Ready SPI Synchronous clock SPI Data from SGD SPI Data from UCM RESET (minimum of 100 ms) System power System ground Reserved for testing Reserved for testing
wind generation system you have installed is now not only running your electric meter backwards, but also helping to supply your neighborhood with the extra energy needed to run everyone’s air conditioners during the high demand period of a scorching hot afternoon.
SMART METERING
Many states have begun the switch to smart metering. I can remember meter readTable 1—These are the defined signals available on the 10-pin USNAP interface. ers coming to my house when I was young. My mother let them in and they went into the basement to physically read the electric and water direction. This gives the system a dynamic nature that meters. Later, a wired connector was placed on the outallows energy to be shuffled from where it is currently side of the house so the meter could be read from outbeing generated to the demand. side. Today, utility trucks need only drive past the resiSince the power grid has no facility for energy storage, dence to obtain meter data wirelessly. The ultimate power is used as soon as its generated—or, in truth, it is smart meters will regurgitate their data in real time. generated “just in time” in anticipation of the demand. They’ll give the utilities real-time demand information. When demand peaks, or exceeds the present generating They’ll provide consumers outage updates and informacapacity, additional generation facilities may need to be tion about real-time energy costs based on grid demand. brought online. These peak load facilities may be older The thought is that a conservation-minded customer and inefficient, creating a higher average generation cost may wish to delay any high-demand energy use during for the customer. peak demand (higher cost periods). This might also influIn case you didn’t know, the new buzz term is smart ence a customer’s rational for feeding energy back into grid. Sounds good, eh? Scrap all this outdated infrastructhe grid. Perhaps an idle hybrid automobile could supply ture and build a new and better system. Well, not quite. the grid during peak periods and recharge during lowIn reality, the industry’s new vision is simply a movedemand times. ment away from centralized generation and toward Of course the utility wants its pound of flesh, but increased consumer interactivity. The vision is to when the consumer becomes part of the process, he’ll improve the grid’s “intelligence” by paying closer attenalso reap some of the benefits. Initially, the utilities are tion to what’s going on. It will make use of alternative restricting their short-term plans, but many are keeping fuel and generation sources, enabling customers to tailor the ultimate goal in view and putting a high priority on their energy consumption based on real-time data, such being upgradable and secure. as price. Herein lies the power, so to speak. Imagine an The ZigBee Alliance has directed significant effort into appliance (e.g., your dishwasher) saving you money by making sure that ZigBee wireless is one of the top conrunning itself only during off-peak hours. The solar or tenders for smart meter data interfacing. Although it’s too soon to determine the big winner and what the selected medium will be, it’s a pretty sure bet that being involved is the best way to ensure success. Which brings us to the point of this column—namely, the Utility Smart Network Access Port (USNAP) alliance.
USNAP
Primary NAK Code 0x00 0x00 0x00 0x00
Photo 1—The USNAP vision enables appliance manufacturers to interconnect with smart metering through a home area network (HAN). This enables every connected appliance to become an effective player in the smart energy solution. www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Secondary NAK code 0x01 0x02 0x03 0x04
NAK Description Checksum error Invalid length Extra bytes Intra-message timeout
Table 2—All messages are acknowledged as good (ACK) or bad (NAK) with a 3-byte message frame. An error in a received message is NAKed using a primary and secondary code byte. These codes indicate the type of error that has been detected by the receiver.
January 2011 – Issue 246
As you can imagine, one of the main sticking points on many decisions has to do with communication. How will
59
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 60
worldmags
testing purposes). The PCB area defined for the standard USNAP module is 41 mm × 47 mm, with an extended version adding an additional 51 mm (see Photo 1). The extended version is meant for those mediums that require large components or connectors such as Table 3—Error detection and recovery is slightly different between the SGD and UCM. NAK codes an antenna or RJ-45. UCMs will (see Table 2) can reveal certain errors. use the 10-pin male connector, while SGDs will use the female mating connector. The 10 pins (signals) are defined in what I develop talk to the rest of the world? Clearly, there Table 1. The present configuration uses a system supply is no universally correct answer to that question. Your of 3.3 V at 50 mA. answer might be determined by design criteria like payload size, overhead, peripheral availability, environment, bandwidth, competition, and more. SGD IS THE BOSS According to the USNAP Alliance, “As utilities impleSome of you will recognize the SCLK, MOSI, and MISO ment Automated Metering Infrastructure (AMI) and seek to signals as those of a SPI (first introduced by Motorola back extend the Smart Grid beyond the meter into the home, around 1979.) SELECT and ATTN are handshaking signals the diverse number of communication protocols creates between the SGD and the UCM. Either may initiate a serious compatibility problems for utilities, suppliers and transfer. The SGD initiates a transfer by lowering SELECT consumers alike.”[1] The Alliance offers the utility meter and waits for the UCM to acknowledge by lowering ATTN. If the UCN wants to initiate a transfer, it lowers ATTN manufacturers a universal solution to the problem of and waits for SGD to acknowledge. Remember that the choosing an interface medium. The USNAP protocol’s SGD is always the master so it must constantly watch for independent serial interface creates a gateway, using any requests from the UCM through the ATTN signal. medium, present or future, to interconnect, in this case, a The synchronous clock associated with a SPI is always utility meter, the AMI, and an HAN. The AMI allows the controlled by the master, and in this case the SGD. It utilities to measure, collect, and analyze energy usage from may clock the interface at any speed between 10 kHz and afar. But it goes one step further, it is a two-way communi2 MHz. Even though the SPI is capable of providing bidication path. This allows the utilities to provide the conrectional data, the USNAP spec uses only unidirectional sumer with real-time information that might include transmissions (with the receiving side always transmitting dynamic rate data. This is the present vision of how the smart grid interfaces with consumers. The Home Area Net- a 0xAA character). SPI data is transferred in a MSBit first format with data being legal on the rising edge of the clock work (HAN) provides the consumer interface located in the (mode 0). home. Circuit Cellar readers are familiar with home automation because numerous articles on the subject have been published for longer than two decades. So, while some PAYLOAD of us already have a HAN of some kind, the smart grid The structure of the payload or message frame passed vision will force every home to become connected. While between the SGD and the UCM is identical, independent the immediate plans can only be considered a minimal of who initiates the transfer. Each frame has a minimum of HAN, its effect will be far reaching. 4 bytes and a maximum of 128 bytes. A frame must have a While the first two appliances to use USNAP could be primary command byte, a secondary command byte, a byte the smart meter and the in-home display, you can begin to count, and a checksum that is always the last byte in the imagine other appliance manufacturers that might want to frame. A minimum frame of 4 bytes would therefore logiget in on the action, whether to make use of the current cally have a byte count of zero. When the byte count is not energy rate information from the utility or just provide zero, but, say, 124 (maximum data size), then 124 data manual command and control. USNAP defines an applibytes follow the byte count (byte 3) with the checksum ance as a Smart Grid Device (SGD) and the various interfacing mediums Byte number Request byte description Reply byte description as a USNAP Communication Module 1 Primary command Primary command (UCM). The USNAP interface creates 2 Secondary command Secondary command (with bit 7=1) a simple way of letting an SDG com3 Data count (0-124) Data count (1-124) municate with a UCM.
January 2011 – Issue 246
Error Checksum Invalid length Inter-message timeout Message initiation failure Intra-message timeout Extra bytes
60 worldmags
SGD x x x x
UCM x x x x x x
Detection Bad checksum value Byte count greater than 124 100-ms Timeout when waiting for ACK/NAK 100-ms Timeout when waiting for handshake 10-ms Timeout when waiting for next byte Bytes continue after checksum byte
PHYSICALLY FIT The physical interface consists of a 10-pin, 2-mm strip header with eight predefined signals (two reserved for
4 5
Checksum
Recovery NAK + goto idle NAK + goto idle goto idle goto idle NAK + goto idle NAK + goto idle
Error code Checksum
Table 4—This table shows the minimum frame sizes for command requests and replies. Note that the reply uses the same format, except the subcommand has its MSB set and the data count has a minimum of one since there is an extra byte (error code). CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 61
worldmags
being the last byte in the frame as its error code. Unsuccessful Reply error code Description of error (byte 128). replies can report the reason 0x00 Success As I mentioned earlier, transfers with a number of other values 0x10 More data to come (didn’t all fit here) that indicate the reason for failare unidirectional. When the SGD 0x4z Busy. Retry in z × 100 ms ure (see Table 5). lowers SELECT (and then the UCM 0xC0 Command not implemented When a request is of the minilowers ATTN), a message frame is 0xC1 Found illegal parameter mum size (4 bytes)—that is, the transmitted from the SGD to the 0xC2 Bad message length 0xC3 Bad checksum data count is zero—this request UCM. When the UCM lowers 0xC4 Generic (error message follows in data) is being used to GET data (read). ATTN (and then the SGD lowers 0xC5 Not available (at this time) An instance when the data count SELECT), a message frame is trans0xC6 Too many sends pending (can’t accept it) is anything other than zero is a mitted from the UCM to the SGD. 0xE0-0xEF Manufacturer-specific error request to SET data (write). The Numeric data can consist of 0xFF Unknown failure nature of many requests is that multi-byte values. These are the data can be retrieved or used transferred MSByte first. The Table 5—These error codes returned in a reply deterimmediately, and so the request predefined data can be of signed mine if the request was successful or why it wasn’t. is replied to quickly, in a synor unsigned integers from This can help determine a course of action for the chronous way. Sometimes there INT8/UINT8 through sender. will be an expected delay, in this INT64/UINT64. The checksum Before getting into the actual comcase an asynchronous request is used. byte is a simple (unsigned) sum of all mands of USNAP Rev 2.0, I need to This is called a SEND. Although a previous bytes. mention how a reply differs from a SEND message will receive the normal Upon receipt of a completed mesrequest. As I described above, comreply, a new message is initiated at a sage, the receiver will initiate an mands (requests) are sent in a frame later time that will confirm the action ACK or NAK message. Each of these with a minimum of 4 bytes. The has completed. In this way, the origiis 3 bytes in length. A good message nal requester does not have to spend gets an ACK, the value 0x06 followed reply to each command has an additional byte added to it (see Table 4). time continually polling for confirmaby the primary command byte, and There is a reply to every request. A tion. The confirmation is sent when the secondary command byte of the successful reply responds with 0x00 the requested task is completed. previous message. A bad message gets a NAK, the value 0x15 followed by the primary NAK code, and the secondary NAK code. The NAK present NAK codes are listed in Table 2. Once a message begins, it shouldn’t be interrupted. A new message can be attempted only after a complete transfer (or a timeout). A complete transfer consists of both a message frame and an ACK/NAK frame. To ensure a transfer always completes, a timeout period of 100 ms is used. This is used as a initiation failure timeout (the handshaking line has not been lowered by the receiver) or an inter-message timeout (an ACK/NAK has not come). Should an error occur during a ZZZDUPFRPWRROV ZZZNHLOFRP message attempt, each party must be able to recover. This usually consists For ARM Application Processors: For Microcontroller: ® of sending a NAK after receiving the (FOLSVHEDVHGGHYHORSPHQWWRROVIRU/LQX[ 6RIWZDUHGHYHORSPHQWWRROVIRU$50 70 DQG$QGURLG &RUWH[DQG&0&8V message and returning to the idle 6XSSRUWIRUDOO$50DSSOLFDWLRQSURFHVVRUV 5726DQGPLGGOHZDUHOLEUDULHV state (handshaking line high). Error +LJKSHUIRUPDQFHGHEXJDQGWUDFHDGDSWHU 'HEXJDGDSWHUVDQGHYDOXDWLRQERDUGV reporting isn’t required in some instances. In this case, the only necessary action is to return to the idle state (handshaking line high). Table 3 1-800-348-8051 shows the kind of error detection and recovery necessary for both the SGD and the UCM. www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
January 2011 – Issue 246
Leading Embedded Development Tools...
61
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 62
worldmags
Primary command value 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x02 0x02 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x70 0x81 0x81 0x81 0x81 0x81 0x81
Secondary command value 0x01 0x10-0x1E 0x20-0x2F 0x50 0x51 0x60-0x6F 0x70-0x7F 0x01 0x02 0x00 0x10 0x11 0x20 0x21 0x22 0x23 0x23 0x25 0x30 0x31 0x32 0x33 0x34 0x40 0x01 0x10-0x1F 0x020-0x2F 0x40 0x41 0x70-0x7F
Command GET SGD Information GET SGD Description String GET SGD Help URI GET SGD Slot Number GET Available Slot Numbers SEND Command to Slot GET/SET MFG Specific to SGD GET/SET UTC Time GET/SET Local Timezone GET SEP Information GET/SET Publish Price SEND Scheduled Prices Request GET/SET Load Control Event SET Cancel Load Control Event SET Cancel All Load Control Events GET/SET DRLC Attribute GET Load Control Events SEND Scheduled Events Request SEND Meter Profile GET/SET Meter Mirror SET Remove Meter Mirror GET/SET Meter Attribute SEND Meter Profile Response GET/SET Display Message GET UCM Information GET UCM Description String GET UCM Help URI GET UCM Connection Status GET UCM Status String GET/SET MFG Specific Data to UCM
SGD SET
x x x x x x x x x x x x x x x x x x x x x x x
SGD GET
x x x x x x
x x x x x x x x x
UCM SET
x x x x x x x x x x x x x x x x x x x
UCM GET x x x x x x x x x x x x
x x x x x x x x
x
Table 6—These are the present primary (and secondary) commands set forth by Version 2.0 of the USNAP Serial Interface Specifications. Primary commands 0x01 and 0x81 are informational to the device or module. Time and date commands 0x02 and Smart Energy Profile SEP commands 0x70 are only the first additional commands included in this Public Review Document. Additional commands are presently being discussed, which, if I had to guess, will have to do with more command-and-control issues. Table 6 shows four primary commands: SGD information, Time of Day, Smart Energy Profile (SEP) information, and UCM information. Note that reading the informational data about a device is like reading its datasheet. This will be sufficient for the requester to determine its level of compatibility.
January 2011 – Issue 246
TIME AND DATE
62 worldmags
Let’s take a quick look at how time and date are handled. First, all time is given in Coordinated Universal Time (UTC), also known as Greenwich Mean Time (GMT). The Prime Meridian, 0 degrees longitude, passes through the Royal Observatory in Greenwich, England, and this is the point where everyone has agreed to reference time (and position). Since we don’t know exactly when time started, UTC uses January 1, 1970 as the beginning, or 0 time. For every second that passes after that first second of 1970, the UTC is incremented by one. So, the present UTC value is the number of seconds that has passed since the arbitrary beginning of time (1/1/1970). In my case, as of this very second, that is 1284371520 UTC. This piece of information allows us to determine the present time and day.
While this is great for all those living in the Greenwich time zone, I’m here on the east coast of the United States. Connecticut is located in the Eastern Standard Time zone and is 4 hours behind UTC (minus 4 hours). Remember to take into account Daylight Savings Time if appropriate. This adds an additional hour to your time zone. So, the second piece of information becomes an offset to UTC. This is the time zone offset. When added to UTC, it gives us local time. The time zone offset is in the same format as UTC—that is, the difference in seconds between UTC and the local time. You’d think that this would always be the number of seconds in an hour times the number of hours in the offset (3600 × 4 = 14400 in my case), and it is for most. However, there are places in the world that use something other than an even hour offset. If that’s got you scratching your head, check out www.worldtimezone.com/faq.html. For the calculation of the local time and date, you need these two pieces of data. The UTC is a constantly increasing value, while the time zone offset is a relatively static value. (In my case, it will change with daylight savings seasons.) It’s really up to the device to determine how it will keep time. It may request this information CIRCUIT CELLAR®
•
www.circuitcellar.com
63_Layout 1 12/2/2010 9:28 AM Page 1
worldmags
ition d E A S U r o Elekt /usa m o c . r o t k e l www.e “Elektor? Prescribed reading for our R&D staff because that’s where we need professional guidance for microcontroller technology.” – Frank Hawkes, 39, development engineer – [Analog Digital Microcontrollers & Embedded Audio Test & Measurement ] US $ 7.95 - Canada $ 7.95
January 2010
[Analog Digital Micro
controllers & Embedded
December 2009
Audio Test & Measurement
]
US $ 7.95 - Canada $ 7.95
[Analog Digital Micro
controllers & Embedded
www.elektor.com Januar y 2010
Audio Test & Measurement
]
US $ 7.95 - Canada $ 7.95
www.elektorusa.com
Measurement ] Audio Test & $ 7.95
There’s More Preselector forthan just USB! Life Elektoto r SD R
ded ollers & Embed l Microcontr [Analog Digita February 2010
US $ 7.95 - Canada
Her
e’s the USB Magic Eye automat ic tuning upgrade
!
www.elektor. com
Put a Stop to Throwawayism!
Buses USB and I2C Energybeyond Sav
com www.elektor.
Subscribe to Elektor now!
ings from Home Autom ation Fourier Analysis using Standards com pared LTspice & Excel Tech ATM18
There’s Mor nolo gy to Life than just USB!e Proj N KDOW AC Dimmer with a Micro a Sto PFCPutCR p to Throwawa led Christm r reveayism
ects Logic Analyzer USB Magic Eye
as ! Hol fac Buses mp rida ysto we Circuits po 13 pag yo esnd La be of beg US Br’sAVR-USB inne an andd I2box junk C projollers & Embedded Test & Measurement ] My First Microcontr ects
ER olsPOW ing [ Fou TAwTH S rieerToE An ign aly des VE GO ,NEW DIY U’18 lingsis usi Thetrol YO ngPROJECT ATM rc , coo ard uling follo , con0 w7 the LTs pic So e story ds on testing l Analogue Digita
Audio
February 2010
2pen Logic AnalOyz ECTS NEW PROJer Han
6
ty paci ery Ca Batt ker Chec
elektor.com stem PA Sy
& Excel
oth ueto TTL Blgle Don ain ke Ch orbi Mot
LET THE
Join the fascinating world of electronics worldwide!
SCEPTER RULE! 7
A 32-bit ARM g fast prototypin system
applications design for AVR Low power e DMX Interfac ED Mixer with LED Linux on a Chip Linu ar Parking Rad pacctt ... mpa -com a-co ltra Ultr
ULO D MOD amplifier fledged stereo A full-
H ELECTRONICS WIN $100 WIT
Creative & fresh articles since 1961
$ 7.95 US $ 7.95 - Canada
PUZZLE
ues 11 Iss the ing includ le r doub e m m t su for jus e u s s i 5* $39.9
Electronics projects to delight and educate in diverse areas of electronics Each project is built, tested, and approved by Elektor’s laboratory staff Access to a wide range of products to support magazine projects in our online shop Cheaper than 11 issues from the newsstand: Save 57% of the cover price of $92.45 * Offer available in US and Canada only. Canada add $11 per year.
Take out your subscription now:
XXXFMFLUPSDPNVTBt1IPOF
electronics worldwide
electronics worldwide
worldmags ELEK US1001 Aboadvo indd 1
09-12-2009 09:37:05
2011-1-002-Bachiochi_Layout 1 12/10/2010 8:45 AM Page 64
worldmags
Request Byte Number 1 2 3 4 Reply Byte Number 1 2 3 4 5 6 7 8 9
of the specification at www.usnap.org. Value 0x02 0x01 0x00 0x03
Description Primary command Secondary command Data count Checksum
Value 0x02 0x81 0x05 0x?? 0x?? 0x?? 0x?? 0x?? 0x??
Description Primary command Secondary Command MSBit = 1 Data Count Error Code MSByte of UTC time ... ... MSByte of UTC time Checksum
Table 7—A typical time request begins with a 4-byte request containing the command and no data. The reply contains the original command (with the high bit of the secondary command set) followed by a data count, error code, and the data.
SMART SOLUTIONS The smart grid will help bring about a truely smart home. You will have the ability to be a producer as well as a consumer. The efficiencies you create will help everyone in the short and long term. I’m not sure how I feel about the present trend to replace all incandescent lamps with compact florescent lamps (CFLs). It seems like the reintroduction of mercury into every household might be a big mistake! I’d be happy to hear your thoughts on any of this. 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.
REFERENCE [1] USNAP Alliance, www.usnap.org.
RESOURCES
January 2011 – Issue 246
once and set its own internal clock-keeping mechanism, request it at some predetermined interval, or only when necessary. Should an RTC not be implemented, the appropriate response to these commands would be 0xC0 (not implemented, Table 4) as the Error Code. A request for information (GET) for the UTC, command 0x02:0x01, would take the form you see in Table 7. A request to give information (SET) for the UTC, command 0x02:0x01, would take the form you see in Table 8. The description “Error Code” is a misnomer because a “good” reply will use an Error Code of 0x00 (Success, see Table 4). The 32UINT UTC value, like all data, is in hexadecimal format. I’ve described this command to give you a feel for how the USNAP interface is used between the SGD and UCM. For more information, I suggest you get a copy
64 worldmags
Request Byte number 1 2 3 4 5 6 7 8 Reply Byte number 1 2 3 4 5
Value 0x02 0x01 0x04 0x?? 0x?? 0x?? 0x?? 0x??
Description Primary command Secondary command Data count MSByte of UTC time ... ... MSByte of UTC time Checksum
Value 0x02 0x81 0x01 0x?? 0x??
Description Primary command Secondary command MSBit = 1 Data count Error code Checksum
Table 8—Data can also accompany a command request. In this case the data count is nonzero, indicating data is included. The reply always contains a data count of at least one, the error code.
USNAP Alliance www.usnap.org ZigBee Alliance www.zigbee.org
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-toknow information about some of the topics covered in this article, the Circuit Cellar editorial staff recommends the following content: — Portable Network Service Monitor by Alexander Popov & Peter Popov Circuit Cellar 238, 2010 This portable network service monitor helps network administrators supervise data centers. The LCD displays important messages from any configured server in a local network. Topics: Network, Server, Monitor, Access, Ethernet — Home Automation for an Energy-Efficient House (Pt. 1) System Design and Server Software by Stefan Siegel Circuit Cellar 238, 2010 A modern energy-efficient house requires a home control system based on some serious embedded hardware. You can build a home automation system based on a CAN bus running a CANOpen software stack. Here you learn about the overall design and server software. Topics: Automation, Network, CAN, Server — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
64_Layout 1 12/2/2010 9:31 AM Page 1
worldmags
January 31 – February 3, 2011 Santa Clara Convention Center Santa Clara, California
DESIGN ISN’T ALWAYS SIMPLE... ...BUT IT CAN BE SIMPLIFIED! Don’t miss the definitive event for chip, board and systems designers. Save up to $200 WITH ONLINE REGISTRATION Go to www.designcon.com/register today! Enter promo code DCONPA to save an additional 15% off your registration.
2011 Conference Highlights 95+ tutorials and technical paper sessions covering design issues for power, RF, analog and other applications Agilent Educational Forum Industry Keynotes Product Spotlights Chiphead Theater Presentations DesignVision Awards IP and PCB Summit Events And much more….
Official Host Sponsor
Diamond Sponsor
Diamond Sponsor
Gold Sponsor
Corporate Sponsor
worldmags
5:00 PM
2011-1-003-Cantrell_Layout 1 12/10/2010 8:52 AM Page 66
worldmags
S
ILICON UPDATE
by Tom Cantrell (USA)
Power Tripping Energy Conservation on the Embedded Level Much of the IC-era has been about performance at any price. But lately, attention has turned to “green” and “alternative energy” products, or at least ones that don’t chew through so many batteries. This month you take a power trip and learn about some easy ways to reduce, or better yet eliminate, your design’s energy bill.
January 2011 – Issue 246
I
66 worldmags
n times past, the IC revolution was mainly now we have chips that can squeeze more than about smaller, faster, and cheaper. Sure, a few MIPS from just a single milliamp. Don’t there was a low-power CMOS niche for simple you just love this business? applications like calculators and watch chips, As marks the history of silicon, the new but most designers were screaming for more capability (i.e., ultra-low power ICs) is enabling MIPS, megabits, and megahertz rather than a new class of applications, ones that extend lower power consumption. That all changed battery life, perhaps even to the lifetime of the with the emergence of “high-performance” gadget. At the bleeding edge of low-power CMOS in the 1980s. The premise it could do design, there’s the option of harvesting ambient everything NMOS could (i.e., speed, density, energy and eliminating batteries altogether. price), but consume much less power, was The Silicon Wizards have given us chips quickly proven in the SRAM market. It wasn’t long before mainstream MCUs also made the switch to CMOS, further fueling demand for new high-capability, yet low-power, applications. Since then, CMOS has carried on the crusade against power conFigure 1—The LTC3109 is the “powerware” at the heart of this TEG-powered wireless sensumption with a sor. The chip takes millivolts and microamps from the TEG and delivers volts and milliamps vengeance, and to your application. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-003-Cantrell_Layout 1 12/10/2010 8:52 AM Page 67
worldmags
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Photo 1—Harvesting the tiny voltage generated by a tiny temperature differential from a TEG isn’t trivial (note the twin step-up transformers), but the LTC3109 makes it easier than ever. be powered by the other supplies, starting with VOUT, which is pinselectable (VS1 and VS2 pins) as either 2.35 V, 3.3 V, 4.1 V, or 5 V. The current limit is 6 mA, but once again, a storage capacitor can be added to handle higher pulsed current demands. Once VOUT reaches the selected voltage, it’s held there by toggling charge current from VAUX and the open-collector PGOOD output (internal weak pullup to VLDO) signals VOUT is good to go. Your next power option is VOUT2, which connects to VOUT internally
Photo 2—If the chip fits, wear it. Piezo harvesters make ped-power possible in this smart shoe from Nike.
January 2011 – Issue 246
DC power outlets on the other. Here’s how it works. The TEG-side of the chip, fronted with two small transformers (see Photo 1), comprises a step-up switching power supply that can harvest energy from very low voltages (e.g., 30 mV with a 1:100 turns ratio transformer) of either polarity. The latter feature means there’s no longer a “hot” or “cold” side of the TEG per se, but rather energy is available for harvesting as long as there’s a temperature difference (e.g., as little as 1°C) between the sides, Figure 2—The ’3109 is uniquely well-suited with polarity switching handled autofor applications that exploit the dual-polarity matically by the ’3109 (see Figure 2). If capabilities of the TEG. you don’t need the goes-both-ways feature, Linear offers a similar that use less power than ever. But LTC3108 for single-polarity (i.e., ironically, that ups the ante for “hot” side always hotter than the designers in terms of delivering it “cold” side) apps. efficiently (i.e., power generation, On the output side of the ’3109, conversion and management). Never let’s review (in order of appearance, fear, Linear Technology has a catalog Figure 3) the veritable power-strip of chocked full of answers to that chalfive DC supplies: VAUX, VLDO, lenge too. Let’s take a power trip. VOUT, VOUT2, and VSTORE. As the harvested voltage rises above the start-up threshold, the HEAT WAVE VAUX supply is where the action I just covered the topic of thermal begins by powering the chip’s interelectric generation in Circuit Cellar nals starting at about 2 V. The volt244 (November 2010), so the age at VAUX will eventually reach LTC3109 immediately caught my 5.25 V, the highest voltage inside the eye. As shown in Figure 1, inside a chip, where it’s clamped by shunting tiny 4 × 4 mm 20-pin package, the excess current to ground. ’3109 integrates a lot of thermal Once VAUX reaches about 2.3 V, energy-harvesting functionality into VLDO, the output from the on-board a single easy-to-use chip. Indeed, it’s 2.2-V low-dropout (LDO) voltage regvirtually a complete black-box power ulator, is switched on. As first up at subsystem with the thermo-electric bat, VLDO would typically be congenerator (TEG) on one side and five, nected to the application’s MCU. count ’em, ones-and-zeros-friendly Even though the output current limit is just 5 mA, as mentioned earlier, that’s enough to do something useful these days (i.e., tens of megahertz/MIPS for a lowpower MCU). Remember that energy-harvesting apps typically feature low duty cycles, so you can always add a storage capacitor to support higher pulse currents. Remember that VLDO only Figure 3—Harvested electrons face a gauntlet of five has to power enough intellisupplies to run starting at VAUX (to power the chip), gence to get the ball rolling next to VLDO, then VOUT and VOUT2, and finally leftwhile additional circuits can overs stashed at VSTORE
67
2011-1-003-Cantrell_Layout 1 12/10/2010 8:52 AM Page 68
January 2011 – Issue 246
worldmags
68 worldmags
option works better piezo output is AC (no motion = no energy) and as intermittent as the or worse depending vibration source, while a TEG is DC on the voltage outand typically has a rather constant put chosen for output around thermal equilibrium. VOUT (i.e., 2.35, Also, a piezo generator output current 3.3, 4.1, or 5 V). may be just a few microamps, but the Lower VOUT voltvoltage can be rather high—for examages are better ple, up to 20 V in normal use. And it since the additioncan spike much higher, which is a al headroom (i.e., real issue considering the possibility 5.25 V – VOUT) of “g-shock” (e.g., a pothole or fummeans a given storFigure 4—Get some excitations from those good vibrations with bling fingers). age element will the piezo-friendly LTC3588. So, the challenge for the ’3588 is to take longer to drain harvest even the tiniest amount of below the critical energy to be had across a wide volt(i.e., PGOOD) threshold. via a switch controlled by the age range, yet at the same time be One ’3109 spec that leaps off the VOUT2_EN pin. Driving robust enough to withstand Murphy’s datasheet is efficiency, which, even VOUT2_EN high turns on VOUT2; Law, all while generating a clean and under the best circumstances, peaks otherwise, it’s kept off by an interuseful (i.e., selectable 1.8, 2.5, 3.3., at just 35%. You’re no doubt used to nal weak pull-down resistor. 3.6, up to 100 mA) DC output. seeing much higher efficiency (e.g., VOUT2_EN would typically be drivThe easiest way to explain the 80% to 90%) specs for conventional en by intelligence previously ’3588 is to follow it along through power supplies, so this must be a brought to life by VLDO or VOUT. the startup phase (see Figure 4). Once real problem, right? Wrong. Put aside The ON/OFF capability makes the fact that the TEG itself is far less vibration begins, the piezo generates VOUT2 especially useful for powerpower, perhaps just a few microamps efficient (e.g., 0.1%) at converting ing a sensor or other logic that doesat a few volts. At this point, the thermal to electrical power. The real n’t have a good sleep or standby ’3588 is in “Under Voltage Lock Out” issue is that we’re talking about harmode, especially in very low duty (UVLO) mode in which it simply recvesting “free” energy, and 35% of cycle applications where those specs tifies the input, clamps any spikes free is still free! So it’s not the drive average power consumption. beyond 20 V, and stores the DC on a absolute efficiency number that matAlternatively, you can connect the capacitor connected to VIN. Since the ters, but simply whether it’s “effiVOUT2_EN and PGOOD pins, and ’3588 consumes only 460 nA in cient enough” to do what you want then VOUT2 will be enabled as long UVLO, every extra microamp is to do. as there’s surplus power, but autoavailable to start charging the VIN matically shut off if there isn’t. capacitor. Another noteworthy feature is that PIEZ-O-CAKE Once the VIN cap charges to a suffithe VOUT2 current limit is whopAnother ample source of “free” ciently high voltage (i.e., 300 mV highping 200 mA since it can draw curenergy is piezo power (see Photo 2), er than the selected output voltage), rent from the storage capacitor on and the LTC3588 is an easy-to-use VOUT directly to bypass current limsolution. In many its imposed by the harvester circuits. ways, designing-in The parade of harvested electrons the ’3588 is like finally comes to an end at the designing-in the VSTORE pin. As the name implies, ’3109—that is, just this is a handy place to hang a superchoose a few discapacitor or battery back-up power crete components circuit. As long as there’s enough to match the piezoenergy being harvested to run the generator specs and other supplies (i.e. VLDO, VOUT, meet your average VOUT2), any surplus flows from and pulse current VAUX to VSTORE. If VAUX starts demands. falling (i.e., the harvest is inadeBut under the quate), the ’3109 automatically fills hood, the parts are the gap by switching direction and quite distinct, Photo 3—The LTC4070 is virtually a complete Li-Ion battery drawing current from VSTORE to reflecting the funda- charger in a chip. Not just for energy harvesting, it can deliver run the other supplies. Remember mental differences high charge current too. With the large 1-W current limit resistor that VSTORE tops out at 5.25 V between TEG and shown here, this circuit can deliver up to 50 mA for fast recharge. (same as VAUX), so this back-up piezo generators. A CIRCUIT CELLAR®
•
www.circuitcellar.com
69_Layout 1 8/31/2010 2:24 PM Page 1 ! "
%%#
! !
*
*%('
worldmags
www.DevtoolsXpress.com
Pick a Tool. Any Tool. Find the Right Development Tool, Compare it to Other Tools, Evaluate It, and Buy It from Digi-Key Tools Xpress -- Without Leaving Our Site. The Digi-Key Tools Xpress intuitive research engines are used by engineers worldwide to locate, compare and evaluate hardware or software development tools.
Compare before you buy: tools are listed side-by-side, with features and performance specs, availability, and prices, so you can make an educated decision!
FIND. COMPARE. BUY.
worldmags
Digi-Key Tools Xpress, engineered by Embedded Developer, is the only site in the industry where engineers can quickly find, compare and buy the leading development tools.
2011-1-003-Cantrell_Layout 1 12/10/2010 8:52 AM Page 70
January 2011 – Issue 246
worldmags
70 worldmags
to one side of the bridge and the ’3588 turns on its output leaving the other open. and begins transferring charge to another storage capacitor on VOUT. Presuming the generaBATTERY BUDDY tor output is still minimal, It often seems like energy this charge transfer will cause harvesting is positioned as a VIN to drop, putting the ’3588 “battery replacement” technolback into UVLO where it ogy, but that’s not necessarily waits while new charge accuthe case. Sometimes the harmulates on the VIN capacitor. vest doesn’t come in, an evenThere’s some hysteresis built tuality every design needs to into this charge/discharge consider. Or maybe a gadget cycle to ensure proper and effihas a real-time clock that cient operation of the power needs to be set at the factory. conversion circuits. There may be situations where The process continues with a period of sustained full throtthe ’3588 charging up the tle is called for. For example, VOUT capacitor in little even if the normal operation of Figure 5—You can see how a ’3588-based vibration harbursts until eventually the a wireless sensor is very low vester handles with the twin reality (i.e., high voltage, low voltage rises to the chosen DC duty cycle, it’s helpful to have current) of piezo generators. The chip harvests efficiently output level. At this point, “takeoff power” available for across a broad voltage range (e.g., 4 to 18 V) and guards PGOOD turns on and the chip the initial network discovery against voltage spikes at 20 V and beyond. At the same enters regulation mode to and set-up phase. time, it uses a storage capacitor on VIN to accumulate maintain the proper output It’s the need to manually microamps until there are enough to ratchet the DC output voltage level. Even if a deficit replace or recharge batteries up a notch. arises (i.e., load demands more that gives them a bad rap. Use than the generator is providenergy harvesting to eliminate ing), the ’3588 continues delivering power by drawing that chore and you can have the best of both worlds. For from the storage capacitor on VIN. If the deficit persists, instance, it’s easy to add a conventional (i.e., nonthe capacitor will eventually discharge to the point VIN rechargeable) battery to the front-end of the ’3588 piezofalls below the UVLO threshold, at which point PGOOD harvester in Figure 5. The harvester can significantly turns off and the ’3588 goes back into charge accumulaextend the life of the battery, ideally to the life of the tion mode. product. At the same time, you can ship the unit “live” The fact charge can be stored on both the VIN and (i.e., powered by the battery), make it through the leanest VOUT capacitors raises a question: Where is the best of harvest times or even famine (e.g., piezo generator place to put it? The answer is generally on VIN, especially breaks or is disconnected) and have a deep store for conto the degree it has higher voltage to work with (e.g., VIN tinuous full power when you need it. up to 20 V versus VOUT 1.8 V–3.6 V). One caveat is the A rechargeable battery is another option, but one that’s chip’s 100-mA current limit, which is plenty for most a little trickier. No surprise Linear has an easy-to-use applications; but if you need more, it would have to come answer for you in the LTC4070 Li-Ion battery charger in a from a capacitor on VOUT. In any case, some capacitance chip (see Photo 3). (e.g., 10 to 100 µF) is required on Keeping a Li-Ion battery happy VOUT to smooth output ripple. isn’t trivial. The charging cycle Though positioned as a piezo-cenneeds to be intelligent enough to tric solution, the ’3855 is well suitcharge the battery quickly without ed for harvesting energy from other overheating lest your gadget end up sources. You could even gorge at a in headlines along with “Exploding wall socket (noting safety and reguLaptops.” Fully draining a Li-Ion latory issues) by adding a few resisbattery isn’t a good idea either, so tors, turning the ’3855 into a ACthe voltage needs to be monitored to-DC wall-wart-in-a-chip. Another and the load disconnected before novel application would be an eit’s too late. field harvester using electrodes to As you can see in Figure 6, all capture energy from, for example, you need in addition to the ’4070 is fluorescent light ballast switching. a resistor that limits the charge Figure 6—Typical add-ons for an LTC4070 design The ’3855 can also work with DC current (the chip can handle up to include a current-limiting resistor for the input, a generators, such as a typical (e.g., 5 50 mA itself, more with an extertransistor for low-voltage disconnect and connecto 16 V) solar panel, by connecting nal driver) and a transistor for the tions to a battery’s internal temperature sensor. CIRCUIT CELLAR®
•
www.circuitcellar.com
2011-1-003-Cantrell_Layout 1 12/10/2010 8:52 AM Page 71
worldmags
automatic disconnect. You can select the charge voltage as 4.0, 4.1, or 4.2 V using the ADJ pin (ADJ = GND, open, VCC respectively). An optional thermistor input lets you take advantage of automatic temperature compensation that steps the charge voltage down incrementally (four steps) as battery temperature rises. The temperature is only sampled every second or so to minimize power consumption. High-battery output (HBO) and lowbattery output (LBO) pins can keep an MCU apprised of the situation or drive LEDs that provide visual indication of charging status. You can run the ’1070 from any reasonable power source (i.e., above the battery voltage), just keeping in mind the chip current limit and the power rating of the current limiting resistor. Of course, in an energy harvesting application, you wouldn’t want to waste energy heating a resistor, so lower voltages and charge currents would be the call. In this regard, the ’4070 is a great match with the ’3109 since you can just hang the battery circuit (i.e., ’4070, battery and disconnect transistor) on the ’3109 VSTORE pin, which tops out at 5.25 V. Energyharvesting apps probably wouldn’t need the current limiting resistor or thermal protection feature (i.e., thermistor) since the charge currents are so low.
GREEN IS GOOD
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].
SOURCE LTC3109 Thermal energy harvester, LTC3588 piezo energy harvester, and LTC4070 Li-Ion battery charger Linear Technology | www.linear.com
January 2011 – Issue 246
Sure, saving the environment is a worthy cause. And there’s no doubt super-low power “Batteries Not Included
Or Needed” apps are exciting to contemplate. But the emphasis on intelligent and efficient power delivery goes further than that. I’ve never forgotten the lesson learned from the CMOS revolution in the 1980s. If performance and cost are the same, power issues become ever more compelling and, ultimately, the deciding factor. As with hybrid and electric cars, advanced power solutions are for now kind of pricey (e.g., ’3109 = $3.95, ’3588 = $2.95, and ’4070 = $2.06 in 1,000-piece quantities). But never forget the biggest lesson of them all. When it comes to the march of silicon, lower prices and widespread adoption are always a matter of when, not if. Every embedded designer gets it when it comes to “hardware” and “software.” Now, whether you’re designing smart dust or a server farm, if you want to stay ahead of the curve, it’s time to brush up your “powerware” skills. I
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
71
57_Layout 1 9/30/2010 11:55 AM Page 1
worldmags
worldmags
41.qxp
1/7/2009
3:07 PM
Page 1
worldmags
worldmags
crossword2_Layout 1 12/10/2010 9:13 AM Page 78
worldmags
1
2 3
4
5 6 7
8
10
9
11
12
13 14 15 16 17
18
19
January 2011 – Issue 246
20
74 worldmags
Down
Across
1. 4. 5. 6. 8. 9. 11. 12. 13. 14. 15. 17.
2. 3. 7. 8. 10. 16. 18. 19. 20.
F/A x, y Binary + digit Natural logarithms; “Marvelous Merchiston” Irregular intervals Measures a circuit’s Q 0.01 bar Line that transmits an RF signal to an antenna Kilby; Ge One-time Short for superheterodyne …
MO varistor [two words] Unchanging IP address A circuit’s “Q” [two words] Constant signal processing Tesla Tower Satellite-to-earth connection Memory that doesn’t require power eV [two words] RL [two words]
The answers will be available in the next issue and at www.circuitcellar.com/crossword. CIRCUIT CELLAR®
•
www.circuitcellar.com
ib-246_Layout 1 12/10/2010 9:51 AM Page 75
worldmags
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.
Add Speed and Color to Your Instrument 0$13CREEN4(IGH0ERFORMANCE)NSTRUMENT#ONTROLLER
L L L L L L L
1/4 VGA Color STN Display 16-bit HCS12 processor clocked at 40 MHz Touchscreen-operated GUI Dual RS232/485 ports, SPI and I2C ports 16 10-bit A/D inputs 512K on-chip Flash, 512K RAM with Flash backup Plug-in I/O expansion, including Ethernet, Wi-Fi, GPS, 24-bit data acquisition, UART, USB, Compact Flash, relays, and more ...
-OSAIC)NDUSTRIES)NC
tel: 510-790-1255 fax: 510-790-0925
WWWMOSAIC INDUSTRIESCOM Evaluate * Educate * Embed Adapt9S12 Modular Prototyping System For education & development
DUSTRIES )NC
Topologies Supported: Planar, Stack, Backplane, Tower MCU Families Supported: S12A, C, D, E, NE, XD, XE, XS
Toll-free (USA & Canada): 1-877-963-8996 www.TechnologicalArts.com
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
January 2011 – Issue 246
WWMOSAIC INDUSTRIESCOM
75
ib-246_Layout 1 12/10/2010 9:51 AM Page 76
worldmags
&
! "#
*" # * %
$ % &% # +
% ' ( !)%"
#!)
%&"
microEngineering Labs, Inc. www.melabs.com w w w. m e l a b s . c o m P PICBASIC ICBASIC P PRO RO™ Compiler Compiler
January 2011 – Issue 246
Bridges the gap between ease
76 worldmags
of use and professional level The implicity o off tthe he rresults. esults. T he ssimplicity language allows both hobbyist a and nd e engineer ngineer tto o m master aster iitt quickly, but engineer q uickly, b ngineer ut tthe he e what’ss happening appreciates what’ under the hood. This is a true compiler that produces optimized ptimized m machine achine ccode p roduces ffast, ast, o ode that's stable and dependable. Supports: More than 300 PIC® Microcontrollers Direct Access to Internal Registers In-Line Assembly Lan guage Language Inte rrupts in PICBASIC and Assembly Interrupts Built-In USB, I2C, RS-232 and More Source Level Debugging Debugging in MPLAB
PICBASIC PRO™ Compiler $249.95
888-316-1753 888-316-1753
USB Programmer Programmer ffor USB or PIC® M MCUs CU PIC
$89.95 ((as as shown) shown) R oHS RoHS C ompliant Compliant Programs P rograms P PIC IC M MCUs CUs including including llow-voltage ow-voltage ((3.3V) 3.3V) d devices. evices. Includes 98, Me, NT, Includes Software Software for for Windows Windows 9 8, M e, N T, XP, XP, and and Vista. Vista.
With W ith Accessories Accessories ffor or $$119.95: 119.95: Software, USB nd IIncludes ncludes Programmer, Programmer, Software, USB Cable, Cable, aand Programming Adapter P rogramming A dapter ffor or 8 tto o 40-pin 40-pin DIP. DIP.
See See our our full full rrange ange ooff pproducts, roducts, iincluding ncluding bbooks, ooks, accessories, accessories, aand nd ccomponents omponents aat:t:
www.melabs.com w ww.melabs.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
ib-246_Layout 1 12/10/2010 9:51 AM Page 77
worldmags
MaxSonar Perfect for OEMs & Engineers XL-MaxSonar-EZ High acoustic power Real-time calibration Tiny size $39.95 USD qty. 1
MaxSonar-WR (IP67)
Industrial packaging Weather resistant Standard ô´ILWWLQJ $99.95 USD qty. 1
LV-MaxSonar-EZ Power-up calibration Smallest MaxSonar Low power, 2.5V-5.5V $29.95 USD qty. 1
MaxSonar-WRC (IP67)) Compact packaging Weather resistant Quality narrow beam $99.95 USD qty. 1
January 2011 – Issue 246
www.maxbotix.com
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
77
ib-246_Layout 1 12/10/2010 9:51 AM Page 78
worldmags
FS M QJ N $P$6 $ r %FD S FBT F D PEF E . F ¥ [ J $ * T J [ F CZ N 1 J U S Q P G 0 r 6T F M FT T FY QFOT J W F .$6 XJ U I
T NBM M FS QS PHS BN NFNPS Z r 4 B W F IVOES F ET PG EPM M B S T J O D PNQPOF OU D PT U T J O Z PVS QS PK F D U T
$$4 $PNQJ M FS T 4BWF :PV .POFZ $PNQJ M FS T 4U BS U J OH BU
TCPmaker TCPmaker ffor or ccontrol ontrol o over ver the W Web eb Easy Easy as 1-2-3: our Da tha ta, with v ariable names that 1. Define Y Your Data, variable YOU create. create. YOU Lay O ut Your Your Content Content (with gorgeous 2. Lay Out gorgeous web-ready screen screen controls web-ready controls that that you you can grab grab to) using TCPmaker’s TCPmaker ’s drag drag & drop drop Visual Visual on to) Page Designer. Designer. Page ode, ffor or all M icrochip C our C Generate Y 3. Generate Your Code, Microchip o ““wire wire it all ttogether.” ogether.” compilers, tto compilers, T ALL – just poin NO PC PROGRAMMING AT pointt y your PROGRAMMING A PROGR our web browser browser a our devic e! web att y your device!
Simple Up Upgrade grade M Management anagement S System ystem rades L ow ccost ost in tegrated sy stem manages upg Low integrated system upgrades ypes: acr oss diff erent pr ocessors & cconnectivity onnectivity ttypes: across different processors our PIC >L ets y our end users upg rade y Lets your upgrade your fir mware saf ely,, simply, ely simply, and secur ely. firmware safely, securely. > Automatically email.. Automatically delivers delivers upgrade upgrade by by email > Simple for for non-technical non-technical end users. users. Encrypted system system protects protects your your firmware firmware > Encrypted from theft theft or from from being programmed programmed into into the from wrong device. device. wrong Grows with your your product product line: for for a new > Grows product w/ different different processor processor or connectivity connectivity product type, just add another SUMS bootloader. bootloader. type,
From the makers of HIDmaker FS:
XXX D D T J OG P D PN 4"7& T BM FT !D D T J OG P D PN Y
www.tracesystemsinc.com 888-474-1041
##
$ #
2! " $ # +
%& &
& (
! ' ) &* &
(&
)(
,() (()(
-
)( )(
& ( , '& - %& $ 1 "!
.) / & )0 & / .& ( (()( %& &
www.linksprite.com
Tools for Embedded Development
! "
CROSSWARE
UART-WiFi, UHF EPC Gen2 RFID Reader, Powerline Communication
®
1* $¥ .$6 B OE ET 1* $¥ %4 $ B S F S FHJ T U FS FE U S B EFNB S L T PG .J D S PD IJ Q 5 FD IOPM PHZ
* OD
USB KEY & CASE Fully programmable USB key with snap-together case
G48 MIPS microcontroller GSecure on-chip flash GOff-chip SPI flash
www.crossware.com
[email protected] January 2011 – Issue 246
CROSSWORD ANSWERS from Issue 245
78 worldmags
Down 2. BUILTINTEST—BIT [three words] 3. EXPONENT—Superscript number 4. VARISTOR—Variable resistor 5. BACKSHELL—Behind a connector; shield [two words] 6. BREAKOUTBOARD—BOB [two words] 9. SUBSONIC—< 15 Hz 11. MIL—0.001″ 15. LAG—Behind time
Across 1. SNUB—To suppress 4. VIENNA—Rectifier; Johann W. Kolar 7. INERTIA—Newton’s First Law 8. RECOVERYTIME—Period to straighten out [two words] 10. PRIMENUMBERS—19, 23, 29, 31, 37, 41, 43, 47 [two words] 12. ZULU—Coordinated Universal Time 13. KILO—103 14. ENAMEL—Insulator for a wire 16. MEGA—106
CIRCUIT CELLAR®
•
www.circuitcellar.com
79-advertiser's index_Layout 1 12/10/2010 2:59 PM Page 79
worldmags
I
NDEX OF ADVERTISERS Page
Page
51
2011 Int’l CES
78
AAG Electronica, LLC
75
Page
DesignNotes
15
Ironwood Electronics
14
Mouser Electronics, Inc.
22, 23
Elektor
C3
Jameco
C2
NetBurner
All Electronics Corp.
63
Elektor
41
Jeffrey Kerr, LLC
45
NXP Design Challenge
50
AP Circuits
27
Elprotronic Inc.
13, 32
JK microsystems, Inc.
5
71
APEC 2011 Conference
35
Elsevier, Inc.
75, 76
JK microsystems, Inc.
C4
Parallax, Inc.
77
Artila Electronics Co. Ltd.
27
EMAC, Inc.
61
Keil Software
39
Pololu Corp.
76
Bitwise Systems
77
Embedded Adventures Ltd.
41
Lakeview Research
77
Reach Technology Inc.
76
BusBoard Prototype Systems Ltd.
69
Embedded Developer
77
Lawicel AB
47
Saelig Co. Inc.
57
CC Archive
29
ExpressPCB
13
Lemos International Co.
77
Scidyne
28
Cleverscope
32
ezPCB/V-Module
78
LinkSprite
31
Sparkfun Electronics
55
Comfile Technology, Inc.
75
FlexiPanel Ltd.
15
Linx Technologies inc.
2, 3
Technologic Systems
78
Crossware Products, Inc.
26
Front Panel Express
77
Maxbotix, Inc.
75
Technological Arts
78
Custom Computer Services, Inc.
43
General Circuits, Inc.
77
MCC
77
Tern, Inc.
33
CWAV
26
Grid Connect, Inc.
76
microEngineering Labs, Inc.
78
Trace Systems, Inc.
75
Decade Engineering
IC Bank
11
ModularLogix LLC
76
Triangle Research Int’l
65
DesignCon 2011
Imagineering, Inc.
75
Mosaic Industries, Inc.
P
41
72, 73 1
REVIEW
of February Issue 247
Wireless Access and Control: A “MiWi” Network Card Reader Remote Humidity Control System Parallel Processing Computer: A Design for Solving Computation-Intensive Problems THE CONSUMMATE ENGINEER RF Design Review ABOVE THE GROUND PLANE Parallel NiMH Cell Measurement THE DARKER SIDE Don’t Fade Away: A Multipath Fading Experiment FROM THE BENCH Serving Up BASIC SILICON UPDATE Tune In, Turn On: Power Via Radio Waves
worldmags
•
WIZnet Co., Inc.
A TTENTION A DVERTISERS
Theme: Wireless Communications
www.circuitcellar.com
7
NXP Semiconductors
CIRCUIT CELLAR®
March Issue 248 Deadlines Space Close: Jan. 14 Material Close: Jan. 21
Theme Robotics Bonus Distribution Trinity College Robotics Contest, IPC APEX Expo Call Peter Wostrel now to reserve your space! 800.454.3741 or 978.281.7708 e-mail:
[email protected] January 2011 – Issue 246
Page
79
steve_edit_246_Layout 1 12/10/2010 9:57 AM Page 96
worldmags
RIORITY
PINTERRUPT by Steve Ciarcia, Founder and Editorial Director
Second-Life Computing
January 2011 – Issue 246
I
80 worldmags
realize it might be tongue-in-cheek in our recycle-obsessive culture, but I do find that some applications for older computers are a bit over the top. Certainly, we’ve all used an older computer for secondary tasks to extend its value, but I was taken aback a bit when I came across an old Windows desktop that had been converted into a charcoal barbecue. As if that wasn’t enough, there were also a few Macs turned into toilet paper dispensers (out the floppy disk slot), fish aquariums, and a hamster habitat. Flush DOS perhaps? If you are like me, you have a few old computers on the shelf. Between Moore’s Law and Microsoft’s moving-target marketplace strategy, it seems that computer users are perpetually stuck in a never-ending four-year replacement cycle. The depth of all this old iron becomes even more significant when it includes multiple users and replacing both desktops and laptops. By my count, I’ve probably bought and replaced 20 computers in the last 35 years. Some of them, like the ancient 8bitters, are still around as collectables. There are also a few new ones just starting the cycle. The storage dilemma is created by the big gray area in the middle where you and I are constantly deciding whether to repurpose, recycle, or junk the pile. Fortunately, there are a lot of suggestions out in cyberspace on ways to give an old computer a second life with more utility than turning it into a fish tank. The most popular and seemingly easiest second-life applications seem to be: donate it to a school or charitable organization; use it for a public distributed computing project like Folding@Home at Stanford University, make a network-connected File/Print server; make a dedicated gaming box for either current or classic video games; install and experiment with Linux; make a better moving picture frame; make a simple music jukebox; make it into a multimedia AV server; or use it as a sophisticated embedded controller (perhaps for a robot). If you really get inspired, consider the following more involved applications. Extend your wireless coverage. Turn an old laptop into a hotspot as a remote area Wi-Fi booster or gaming wireless adapter. Build a video recorder. Simply use a TV tuner card and free TiVo-like software to make your own less-involved media center. Can we add Slingbox-like functions using Skype? Create a “live” weather station. Combine downloaded webcasts and graphical maps with physical readings from temperature and environmental sensors attached to the computer as a single wall-mounted display. Develop “windows on the world.” Rather than display just the traditional picture frame with canned photos, create a design to view a series of live webcams from around the world. Add a PC to your car. Cars have more processors and computing power than any other device we typically own. However, very little of that performance is available for “alternative” uses. Someone with more software talent than me and a laptop with preloaded MP3 files, a couple webcams, GPS, a broadband card, and various sensors could have any or all of the following: an audio jukebox, instant vehicle stats, collision and lane change warnings, traffic notifications, driving directions, weather maps, fuel and speed info, red light camera and radar trap warnings, and a “blackbox” video/data recorder. Build an exercise cycle display. Videotape (Do they still call it that?) a road trip and then play it back on a monitor mounted in front of the cycle. A wheel speed sensor changes the playback speed. Alternatively, if you are stuck on soap opera TV, just attach a USB-connected TV tuner and peddle on. And my favorite: Customize a home security system. PC-based security and home control systems have been around for many years, but their price/performance over dedicated systems has always been suspect. Now, an old PC or netbook with Ethernet or Wi-Fi webcams, a relay output board, and a few inputs can function like systems costing thousands more. (I know, because I have the others.) With a free surveillance application like Yawcam, the system can detect motion, send e-mail notifications, and record events. With an Internet connection and off-the-shelf scheduling software for powerline controllers like X10 or Insteon, the system becomes a complete home control and security system. Certainly, the list could go on for pages. The great thing about computers is their infinite applicability. As a reader of this magazine, the concept of a car computer or web-connected security system isn’t new, and you could have implemented it years ago using many of the sophisticated offerings from our advertisers. The positive aspect of that pile of old computers is that now it provides a zero-cost platform to create more single-purpose devices. In reality, engineering is all about thinking about what can be invented, even if the technology isn’t quite there yet. That pile of old computers still has some useful life it, and perhaps your list is more achievable than mine. If you have created something classy, consider writing up your success as an article for us. If you’ve simply fashioned the latest-andgreatest barbecue from your old dual-core gaming PC, just send me the cooking recipes instead.
[email protected] CIRCUIT CELLAR®
•
www.circuitcellar.com
C3_Layout 1 9/13/2010 4:04 PM Page 1
worldmags
What is the missing component? A Physics professor planned to illustrate a lecture with demonstrations of how light can be intercepted by certain phosphors or various optoelectronic sensors and transformed into entirely new light. He wanted an ultra-simple demonstration of how an LED would glow when biased by a forward current provided by a suitable sensor. He rummaged through his optoelectronic drawer and found two silicon solar cells, several cadmium sulfide photo resistors, a couple of AlGaAs red LEDs, some silicon phototransistors and half a dozen silicon photodiodes. In his parts cabinet he found some transistors, miniature chokes and assorted resistors and capacitors. How did he combine the smallest number of components to do what the phosphor card did? Go to www.Jameco.com/teaser8 to see if you are correct.
Sign up for our e-newsletter and get a bonus puzzle. www.Jameco.com/enews
worldmags
1-800-831-4242 | www.Jameco.com
C4_Layout 1 12/8/2010 11:12 AM Page 1
worldmags
worldmags