CoverOut - 245_Layout 1 11/8/2010 12:15 PM Page 1
worldmags
Build an Interactive USB Module, p. 34 | Encoders and System Control, p. 58 | A Look at a Multi-Purpose Chip, p. 66
THE
MAGAZINE
FOR
COMPUTER
A P P L I C AT I O N S December 2010 Issue 245
Develop a Sound-Monitoring Mobile Application Embedded Control with Programmable Array Logic VHF Data Transmission Aircraft Telemetry System Development
$7.50 U.S. ($8.50 Canada)
www.circuitcellar.com
PLUS CAPACITOR ANALYSIS What Happens When Capacitors Behave Like Inductors?
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_245_masthead.qxd 11/3/2010 2:52 PM Page 4
worldmags
T
ASK MANAGER Looking to the Future
December 2010 – Issue 245 worldmags
FOUNDER/EDITORIAL DIRECTOR Steve Ciarcia
PUBLISHER Hugo Van haecke
EDITOR-IN-CHIEF C. J. Abate
I
4
THE MAGAZINE FOR COMPUTER APPLICATIONS
t’s been an exciting and productive year for Circuit Cellar. Here I’ll highlight our accomplishments because they set the foundation for what we plan to do in 2011 and beyond. As you know, we strengthened our partnership with Elektor during 2010, and while doing so, we clearly presented our mission to the international embedded design community. In 2011, we will continue to collect, select, and disseminate need-to-know information around the world in the fields of embedded hardware, embedded software, and computer applications. We’ll use both print and electronic content-delivery platforms to reach a diverse international readership of professionals, academics, and electronics specialists who work with MCU-related technologies on a regular basis. We delivered three major design challenges in 2010, two of which wrapped up in mid-2010 (Texas Instruments DesignStellaris 2010 and WIZnet iMCU 2010). In September, we kicked off the NXP mbed Design Challenge 2010. It was a major event because it was the first design challenge that we launched with our Elektor colleagues. (The submission deadline is February 28, 2011. We encourage you to participate.) As for the magazine, we made some noticeable improvements during the last 12 months. First and foremost, we brought a variety of new content to our readers. We presented not only informative project articles, but also insightful interviews with engineers and a new monthly column by George Novacek. And last, but certainly not least, we started running every issue in full color, which has been enjoyed by readers and advertisers alike. On the digital/electronic front, we launched CCAccess.com, an exclusive website where subscribers can download the digital version of Circuit Cellar, locate individual articles, read important news items, manage subscriptions, find deals on products (from books to tools), and more. For all the Circuit Cellar archivists out there, we developed “CC Gold,” a highly popular portable archive of every issue since 1988. Sure, you can still buy back issues in print and on CDs, but we’ve found that many readers prefer having everything loaded in a small thumbdrive with gigs to spare. Moving forward, we plan to further develop these products and services, as well as bring more to the table. You can expect the following: more in-depth articles on an even wider variety of topics, enhanced “search” functionality on our websites, fresh online content (e.g., tutorials and project videos), and quality design contests and sample programs. Lastly, 2011 will be the first year in which Circuit Cellar begins publishing books. Feel free to email us your book proposals and outlines. I’m confident that you’ll enjoy this issue, as well as those in the pipeline. I look forward to writing you in 2011.
[email protected] ASSOCIATE PUBLISHER Shannon Barraclough
WEST COAST EDITOR Tom Cantrell
CUSTOMER SERVICE Debbie Lavoie Kim Hopkins
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
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 10/27/2010 12:48 PM Page 1
worldmags
worldmags
TOC_245_toc.qxd 11/9/2010 10:49 AM Page 6
245
INSIDE ISSUE December 2010
16
Mobile Application Development (Part 1) Program a Sound-Monitoring Prototype Riley Kotchorek, Mike Smith, & Vahid Garousi
28
MCU-Based Aircraft Data Logging and Telemetry (Part 2) Telemetry System Development and Results Eric Ohmit
34
Interactive USB Module Richard Dzioba
Interactive USB, p. 34
THE CONSUMMATE ENGINEER Good Old PALs George Novacek
42
ABOVE THE GROUND PLANE Real-Life VHF Data Transmission Understanding and Using the APRS Ed Nisley
December 2010 – Issue 245 worldmags
58
66
Programmable Logic
App Development, p. 16
VHF Data Transmission, p. 42
12
50
6
•
THE DARKER SIDE Parasitic Components When Capacitors Behave Like Inductors Robert Lacoste FROM THE BENCH Encoder Essentials How to Close the Loop with Hardware Jeff Bachiochi SILICON UPDATE What’s My Line? Moving Toward a General-Purpose Chip Tom Cantrell
On-Board Data Logger, p. 28
Capacitor Experiments, p. 50
Multipurpose Chip, p. 66 TASK MANAGER Looking to the Future C. J. Abate
4
NEW PRODUCT NEWS
8
TEST YOUR EQ SOLUTIONS
9
CROSSWORD
74
INDEX OF ADVERTISERS January Preview
79
PRIORITY INTERRUPT Winging It Steve Ciarcia
80
CIRCUIT CELLAR®
•
www.circuitcellar.com
worldmags
17_Layout 1 10/13/2010 9:30 AM Page 1
worldmags
worldmags
npn245_Layout 1 11/3/2010 2:56 PM Page 8
worldmags
TRUE-RMS CLAMP METER MEASURES DOWN TO 1 mA The CP41 is a hand-held AC/DC true RMS clamp meter that combines simplicity of operation and convenience with the noninvasive measurement of current to an accuracy of ±1% and a resolution of 1 mA. The meter meets the needs of a wide range of users in the industrial and automotive markets. Its range and sensitivity enable the measurement of operating currents, and leakage currents, with a single product, and without breaking connections in the circuits under test. Measurement capability in the milliamp range permits verification of 4- to 20-mA current loops in process control systems, while the meter is equally applicable to testing light industrial and residential electrical installations. The CP41 maintains accuracy even in electrically noisy environments, featuring excellent rejection of external magnetic fields together with a very high level of immunity to interference from voltage transients. The battery-powered meter has a fourdigit LCD. Full-scale readings are up to 4 A or 40 A, with autoranging and auto-zero functions. A variant of the CP41, the CP410, measures higher currents: its auto-range full-scale limits are up to 40 or 400 A. The CP41 and CP410 meet the safety requirements of EN61010-2-032:2002 and the EMC specifications of EN 613262-2:2006, and they provide safe operation on uninsulated conductors carrying voltage of up to 300 V with respect to ground. They measure 194 mm × 74 mm × 25 mm, weigh 235 g, and operate for 15 hours from a standard 9-V alkaline battery. Contact GMC-I PROSys for pricing and availability.
GMC-I PROSyS www.i-prosys.com
S W E N CT DU R O P NEW John Gorsky
December 2010 – Issue 245
Edited by
8 worldmags
CIRCUIT CELLAR®
•
www.circuitcellar.com
eq-245_Layout 1 11/3/2010 2:57 PM Page 9
Edited by David Tweed
Answer 1—A common way to estimate system MTBF is to first take the reciprocal of the component MTBFs, using a unit known as “FIT,” or “failures in time.” One FIT represents one failure in 109 component-hours. Therefore, we can represent the reliability of the three components as 10,000 FITs, 8,333 FITs, and 66,667 FITs, respectively. If any one component of the system fails, the system overall has failed, so for single failures, we can simply add up the FITs of the individual components to get an idea of the FITs for the system: 10,000 + 8,333 + 66,667 = 85,000 FITs You can convert this back into an MTBF estimate by dividing it into 109 hours, giving a value of 11,764 hours.
Answer 2—There are two key mathematical assumptions that validate the analysis of system failure rate as the sum of the component failure rates. First, we assume that only single failures are significant. In other words, once the first component has failed, the system has failed. Second, we assume that the failure rates of the individual components are constant over time. This means that the cumulative distribution function representing failures of a particular type of component is a straight line.
What’s your EQ?—The answers are posted at
www.circuitcellar.com/eq/ You may contact the quizmasters at
[email protected] ü
RoHS
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Test Your ANSWERS for Issue 244
EQ
Answer 3—Copper makes a poor current-measuring shunt because it has a relatively large temperature coefficient of resistance, on the order of 0.004/K. In other words, if the temperature of a length of copper wire changes by 10°C, its resistance changes by 4%. One of the best materials for this type of application is an alloy known as Manganin (86% copper, 12% manganese and 2% nickel), invented in 1892 by Edward Weston (inventor of the eponymous voltage reference cell) for use in scientific instruments. Answer 4—This question is almost becoming irrelevant with the advent of the LED-based decorative lights, but here goes: In addition to the filament that produces the light, each bulb has a second fine wire wound around the two internal legs that hold the filament. This wire is coated with a resistive substance that has no effect at low voltages (each bulb normally has only about 2 to 3 V across it), but burns off permanently when exposed to full line voltage. So, when a bulb burns out, current stops flowing in the string, and the full line voltage appears across that bulb. This causes the secondary wire to begin conducting current, relighting the string. Note that when this occurs, each of the other bulbs in the string is now seeing a slightly higher voltage, since the original voltage drop of the failed bulb is now gone. This accelerates the aging rate of the other bulbs. If the failed bulb is not replaced and more bulbs fail, eventually the entire string will fail catastrophically, burning out not only all of the remaining filaments, but the secondary wires in one or more bulbs as well. Contributed by David Tweed
December 2010 – Issue 245
CIRCUIT CELLAR
worldmags
9
2112017_Ford_Layout 1 11/8/2010 11:22 AM Page 10
worldmags
by Simon Ford
ADVERTISEMENT
The mbed Challenge Is On! DESIGN CHALLENGE
December 2010 – Issue 245
W
10 worldmags
The mbed team is setting out to make rapid prototyping with microcontrollers a reality. Now it is 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
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
2112006-Novacek_Layout 1 11/3/2010 3:02 PM Page 12
worldmags
T
HE CONSUMMATE ENGINEER
by George Novacek (Canada)
Good Old PALs Microcontroller monitoring is essential to ensuring the reliability of a design. But watchdog timers don’t always fit the bill. An alternative is a programmable array logic (PAL) arbitrator, which if used properly can significantly improve a system’s fault-detection capability.
T
he challenge associated with designing an embedded controller is to make sure it can recover from faults gracefully in a predictable manner. It is embarrassing to see that many products don’t live up to this fundamental engineering obligation. Worse, the engineering nightmares of potential product recalls always loom in the background. Even if the customer’s specification does not expressly require a graceful shutdown, it is good engineering. Our engineering pride should compel us to always keep this goal in mind. The micro (a microprocessor or a microcontroller)—which is the brain of the embedded controller—can and should, at little or no additional hardware cost, test all the peripherals for integrity and their data plausibility. One could then argue that if the software is successfully verified and validated, and if we know through some other mechanism that the micro is operating properly, the peripherals must also be OK. Then,
December 2010 – Issue 245
Inputs
12 worldmags
Signal conditioning and ADC
monitoring the micro only should be sufficient for failsafe operation. Putting the first condition (i.e., the software quality assurance) aside for a moment, how can you reliably detect when the micro has derailed (for whatever reason)? Once detected, the following corrective action may be just a simple reset. With more severe faults, you might have to shut down the system or remove the power from its output drivers. An embedded controller’s ability to respond to a fault by resetting or shutting down is called “fail-passive operation.” As an absolute minimum, every designer should use the watchdog timer (WDT) built into just about every micro today. Unfortunately, its usefulness is very much limited to perhaps a reset when the program has gone off the rail due to a software bug, a bit corruption caused by alpha particles, or electromagnetic interference (EMI). That’s all. It’s better than nothing, but
PAL Arbitrator
Disable
Microprocessor or microcontroller
ADCs and output drivers
Outputs
Traditional monitor Disable
Figure 1—A typical embedded controller CIRCUIT CELLAR®
•
www.circuitcellar.com
2112006-Novacek_Layout 1 11/3/2010 3:02 PM Page 13
there are no guarantees. We can only hope for the best. Somewhat more useful is an independent, commercially available WDT, often combined with the power supply monitor, available from chip makers such as MAX. Generally, it is a timer continually re-initiated by the micro. If the micro stops executing the program for any reason, it is expected to fail to re-initiate the timer, which then times out and initiates the system reset. Additional circuitry can make sure that several consecutive resets result in the system shutdown. That’s the theory. In reality, it is not impossible for the micro to continue to toggle the WDT even though it no longer executes its software correctly. Let’s bring the good old programmable array logic (PAL) to the rescue. Some time ago we developed a monitor, residing in one PLD chip and called it “Arbitrator.” In one case, it was accepted by aircraft certificating
RC Clock
authorities as a sufficiently reliable monitor for an aircraft safety-critical embedded system. We were able to show that the probability of the Arbitrator failing to detect a micro failure was less than 10–9—significantly better than any WDT. This needs some explanation. Figure 1 shows a block diagram of a typical embedded controller. The traditional way to monitor its operation is to simultaneously perform all of the controller’s activities in the monitor and compare the results. If the results differ, take a corrective action by first attempting a reset and then by disabling the output drivers to revert to manual control. One will immediately realize that the “traditional” monitor is essentially a second controller, just as complicated and costly. Worse, to prevent common mode failures, “dissimilar hardware, dissimilar software” is the rule. That means at least double the manufacturing cost and double the
Arbitrator
Processor
4-bit counter
Microprocessor reads
Restart
Stop and read
Microprocessor read in time? Y
Arbitrator OK? Y
Generate 2’s complement
Generate 2’s complement
Read microprocessor output
Send to PAL
Stop declare fault
Microprocessor read in time? Y
Data correct?
Y
Figure 2—Arbitrator function www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
engineering development cost. Very few customers have pockets deep enough to afford it. With the PAL Arbitrator accepted by the authorities, the traditional monitor, as seen in Figure 1, was replaced by it. Once developed, the Arbitrator, at a cost of only one PAL, can be used without modification in many applications instead of commercial WDTs and thus provide significant improvement in fault detection. At this point, I hasten to state that in only one case has the Arbitrator been accepted as the sole monitor of a safety-critical system. In that system, both the inputs and the outputs were communication channels, MIL-STD1553B in this case, with their own error detection, leaving no doubt about the data integrity. Proving the correctness of the code for testing the peripherals (the first condition mentioned above) is the Achilles’ Heel of the Arbitrator for fault detection. It’s the old dilemma: While it takes one test to show something is bad, how many tests do we have to perform to prove something is good? How do we prove the probability of the software failure is less than 10–9? One has to rely on statistics, but the verdict will inevitably be a matter of engineering opinion, with the tendency to err on the safe side. Thus we’re back to the traditional monitors relying on dual redundancy, but with a twist. The monitors are now often constructed using programmable logic instead of a second micro. This means that the dissimilar hardware, dissimilar software requirement is automatically satisfied. But the required adherence to the DO-254 standard provides no reduction in the engineering effort. Whenever you build a noncritical controller, a PAL Arbitrator will give you more security than a commercial WDT. The arbitrator can be implemented in many different ways; one is limited by imagination only. Ours was built around a 4-bit timer. Its general approach is
December 2010 – Issue 245
worldmags
13
2112006-Novacek_Layout 1 11/3/2010 3:02 PM Page 14
worldmags
shown in Figure 2. At specific intervals, the micro reads the timer that is not synchronized with the micro’s clock to achieve some randomness. In case the same number as the last time is read, a new read is performed immediately. If it remains the same three times, a fault is declared. Otherwise, the micro generates a 2’s complement. The Arbitrator also generates the 2’s complement. The two results are read and compared. Different results mean a fault occurred, just as when the activities do not occur within a certain time frame. Either the Arbitrator, the micro, or both can declare a fault, which is followed up by a reset or a shutdown. The Arbitrator can simplify the design of safety-critical systems, provided the embedded software is not the sole mechanism for the peripherals’ fault detection. Error detection in communications protocols or some simple additional hardware can ensure that. Some sensors and ICs can be purchased as BITable—they have a pin to signal internal faults. In noncritical applications, the Arbitrator will be more reliable than a WDT. New programmable logic and tools offer many advantages over the 15-year-old PALASM design I described. 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.
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 topics covered in Alexander and George Novacek’s Issue 245 article, the Circuit Cellar editorial staff highly recommends the following content: — Designer’s Best Friend by Tom Cantrell Circuit Cellar 208, 2008 The roots of Altera’s MAX II go back about 30 years to the programmable array logic (PAL) device. Tom covers the history of programmable logic chips and introduces you to MAX II technology. Topics: PAL, CPLD, FPGA — FPGA Embedded Microcontroller Environment by John Clayton Circuit Cellar 235, 2010 Want a simple custom microcontroller development environment? All you need for an FPGA-based embedded design is a PC, some HDL coding/synthesis tools, and an FPGA board. Topics: FPGA, HDL, IP Core — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
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
December 2010 – Issue 245
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.
14 worldmags
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 CIRCUIT CELLAR®
•
www.circuitcellar.com
11_Layout 1 8/4/2010 5:00 PM Page 1
worldmags
worldmags
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 16
F EATURE
worldmags
ARTICLE
by Riley Kotchorek, Mike Smith, & Vahid Garousi (Canada)
Mobile Application Development (Part 1) Program a Sound-Monitoring Prototype Mobile medical devices are poised to change how healthcare professionals service their patients’ needs. This series details how to develop a prototype Windows Mobile application for such a purpose. In this article, you learn about programming a sound-monitoring prototype used to identify medical issues related to sleep apnea.
Editor’s note: Riley Kotchorek wrote this article, with contributions by Professors Mike Smith and Vahid Garousi.
December 2010 – Issue 245
“S
16 worldmags
HappyWakeUp might just be the surprise killer applicapark” describes itself as a blog, radio show, tion of 2009–2010. If people could automatically ‘get up podcast, and an ongoing conversation about on the right side of the bed’ in the technology and culture (cbc.ca/spark). morning, then it might change the The host, Nora Young, certainly mood of the world. Perhaps there does not come across as a “techno would be no more road rage!” geek,” but she has interviewed “However,” Dr. Garousi sighed some pretty tech-savvy people wistfully, “The application only since 2007! It was Nora’s interview runs on Nokia and iPhones. That with Tapani Salmi (Podcast 49) means I can’t use it as a case study about the HappyWakeUp cell for my course ‘Testing for New phone application that got us excitTechnologies.’ We only have Wined. The podcast explained how dows Mobile phones in the teachHappyWakeUp (happywakeup.com) ing laboratories. You’ll just have to used a cell phone to monitor the write the code for an application sounds of a sleeper’s movement for we can use!” the last 30 minutes before a Perhaps the conversation did not planned wake-up alarm call. This exactly happen that way. But you time consists of alternating deep get the gist. It’s why I ended up sleep and arousal periods. If you writing a prototype medical mobile wake up during an arousal time, application—which I call The you are refreshed. If you wake up Snorecognizer—to help determine during a deep sleep period, you how often people snore when takswitch between happy and grumpy! ing a nap after eating supper (see When I joined Drs. Mike Smith Photo 1). and Vahid Garousi’s research group This application may sound a bit at the University of Calgary (CanaPhoto 1—The first prototype requires a simple crazy; however, it addresses a problem da) in the summer of 2009, I was message to be displayed in the application’s that is real and capable of causing informed that, “We reckon that window. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 17
worldmags
Listing 1—The implementation of a basic “Hello World!” operation inside the WM_PAINT case of the switch(wMessage) statement in the WndProc() callback function in our mobile application 1 LRESULT CALLBACK WndProc(HWND hWnd, UINT wMessage, 2 WPARAM wParam, LPARAM lParam) { 3 // WndProc variable declarations 4 PAINTSTRUCT ps; 5 HDC hdc; 6 TCHAR outputString[ ] = L"Oy you – you’re snoring!"; 7 8 // switch statement to interpret the message from Windows OS 9 switch(wMessage) { 10 11 // Code for handling wMessages sent the when application 12 // starts and finished 13 case WM_CREATE: etc; break; 14 15 case WM_DESTROY: etc; break; 16 17 // A WM_PAINT message occurs when the operating 18 // system wants to refresh or "paint" a window 19 case WM_PAINT: 20 // Prepare window for painting and get a handle to the DC 21 hdc = BeginPaint(hWnd, &ps); 22 23 // Get info on application window's size 24 RECT windowSize; 25 GetClientRect(hWnd, &windowSize); 26 27 // Immediately draw the text to the known screen area 28 DrawText(hdc, outputString, 29 -1, windowSize, DT_CENTER | DT_WORDBREAK); 30 31 // End the painting session for the window 32 EndPaint(hWnd, &ps); 33 34 break; 35 } // End switch(wMessage) 36 return 0; 37 } // End WndProc( )
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
CELL PHONE OS Before saying “Hello” to this new world, I had to choose a target platform and an environment in which to develop. There are many different smart phone and PDA platforms available, each with its own pros and cons. Most of the existing mobile operating system (OS) options have free or inexpensive development environments. Some platforms run Java-based applications, while others run C, C#, or C++. With all of the different choices available, I chose Windows Mobile because the University of Calgary had licenses for Microsoft’s Visual Studio 2008 in place. The code could be first tested using the emulators that come packaged with the Windows Mobile
December 2010 – Issue 245
Photo 2—These are New Project Wizard settings to create a C++ project for a Windows Mobile device.
considerable financial losses at both business and societal levels. Snoring is related to sleep apnea, which is a major health issue across the world. I developed a series of mobile applications to form the first practical part of a software engineering course about the “reliable development of mobile medical devices.” These applications are intended be further developed by future graduate students when investigating smart phone aids for addressing sleep-deprivation issues. (If you are interested in learning more about the impact of sleep deprivation, I recommend books such as Sleep Thieves by Stanley Coren, Free Press.) In this article, I will cover the first part of my work, which involved building the initial Snorecognizer prototype at the “Hello World” level. I had to demonstrate how to write software to use the many basic features available on a PDA or smart phone. This meant the prototype would have to be able to accept input commands from the available keys and display text, as well as handle basic audio operations. By doing some basic DSP analysis on the monitored input sounds, the final cell phone Snorecognizer outputs graphs on the maximum number of snores per snooze and other useful pieces of information.
17
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 18
December 2010 – Issue 245
worldmags
18 worldmags
(see Listing 1) based on which event message (wMessage, line 9) has been sent by the mobile operating system to the application. Standard cases are called when the application starts and finishes (WM_CREATE, line 13, and WM_DESTROY, line 14). For our code, I wanted to make the WndProc() function responsible for posting the greeting message in the application’s main window (see Photo 1). When Photo 3—This screenshot shows the options available in the drop-down target device list. The only difference the OS receives a between the two emulator options is that one has a square display and the other has a standard rectangular display. The third option runs the code on a physical device connected via ActiveSync or Windows Mobile request to recreate this Device Center. window, it sends a WM_PAINT message to the application. Deciphering of this mobile windowed application that software development kits (SDKs). displays a message—“Oy you—you’re incoming wMessage message is done Then the code could be moved to in the WndProc() function by the snoring!”—on the mobile device’s UTStarcom devices for use in the WM_PAINT case in switch(wMessage) screen (see Photo 1). classroom. Another advantage was shown in Listing 1. To begin, you create a new project that Windows Mobile applications in Visual Studio by selecting File > could be developed using the same The case statement starts by callNew > Project in the menu bar. Next, C/C++ language that the undergraduing the BeginPaint() function (line choose Visual C++ Smart Device as ates’ other embedded system courses 21). This function takes a handle to the project type (see Photo 2), and used. the window (hWnd) and a pointer to a then select Win32 Smart Device A full version of Microsoft Visual PAINTSTRUCT structure. It returns a Project as the template. After clickStudio can be expensive for somebody handle to information about the who just wants to start playing around ing OK, select the software developdevice context (DC). This DC defines ment kit that corresponds to the with mobile devices. However, a fully the screen area that will be affected device’s Windows Mobile version. functional, 90-day trial version of by the paint operation, which in this My device uses Windows Mobile 5.0 Visual Studio 2008 Professional is case is the “client area” of the for Pocket PC, so I used Windows available on Microsoft’s website mobile device’s window. Mobile 5.0 Pocket PC SDK. The (www.microsoft.com/downloads). Next, you need details of the area on application type should be set to A useful source of code ideas are the screen into which you want to Windows Application. available in the Microsoft Developer place text. For this particular case, call Clicking the Finish button causes Network function descriptions/usage GetClienterct() (line 25) and pass in Visual Studio to generate a large porguides (msdn.microsoft.com). The a handle to the window. The result is a tion of the code. The WinMain() Windows Mobile SDKs are also availrectangle variable, windowSize, function, the entry point into the able on the same download site at no filled with details about the client charge. Remember to get the SDK that application, continuously listens to window. DrawText() is then called matches your target device’s version of the messages sent to it by the mobile to display “Oy you—you’re snoring!” Windows Mobile. For example, if you in the area defined by the rectangle operating system when events (interhave an HP iPAQ RX5910 GPS device rupts) occur. These messages are then and the device context (lines 28 and running Windows Mobile 5.0 for Pock- dispatched to the WndProc() call29). The “L” leading the string et PC, you you’ll need the Windows passed to the DrawText() function back function. This main user code Mobile 5.0 SDK for Pocket PC. is an indication that this string entry point is where the messages are should be created with wide characdeciphered so that appropriate ters (TCHAR—Unicode symbol) that actions can be taken. WORKING PROTOTYPE take 2 bytes of storage instead of just The default WndProc() procedure Getting started can be the most one. Using TCHAR means that the generated by Visual Studio is nothing difficult part of a new project. Here application can be adapted to a wide more than a large switch statement I’ll detail how to make a basic CIRCUIT CELLAR®
•
www.circuitcellar.com
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 19
worldmags
Listing 2—A new WM_KEYDOWN case in the switch(wMessage) statement inside the WndProc() function changes the message displayed based on user input via buttons. 1 LRESULT CALLBACK WndProc(HWND hWnd, UINT wMessage, 2 WPARAM wParam, LPARAM lParam) { 3 // WndProc variable declarations 4 static TCHAR outputString[100] = L"Welcome to the Snorecognizer"; 5 // etc 6 7 switch (wMessage) { 8 9 // VK_RIGHT and VK_LEFT are virtual-key codes for the 10 // right and left keys (set by the operating system) 11 case WM_KEYDOWN: 12 switch(wParam) { 13 14 case VK_RIGHT: // Change global output string 15 wsprintf(outputString, L"Recording the audio”); 16 break; 17 18 case VK_LEFT: 19 wsprintf(outputString, L"Playing back recorded audio"); 20 break; 21 22 // Let all other keys retain their standard functionality 23 default: 24 return DefWindowProc(hWnd, message, wParam, lParam); 25 } // switch(wParam) 26 27 // Tell the operating system that hWnd window needs updating 28 InvalidateRect(hWnd, NULL, TRUE); 29 break; 30 31 // New WM_PAINT message displays text from a local static object. 32 case WM_PAINT: 33 hdc = BeginPaint(hWnd, &ps); .. .. …. .. .. break; .. .. // Code for interpreting other wMessages .. case WM_CREATE: etc; break; .. .. } // End switch(wMessage) .. } // End WndProc( )
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
only inside the WM_PAINT case.
DEBUGGING Once the basic Snorecognizer prototype was coded, I needed to test it. There are two approaches to debugging the code: running the application on an emulator or checking it later when a real device is available to work with. Choosing whether to run an emulator or debug an application directly on a physical device can be done in the target device drop-down menu (see Photo 3). If you can’t find the target device menu amongst your
December 2010 – Issue 245
range of languages. The third parameter, –1, indicates the use of a null-terminated string and avoids the need to specify the precise length of the string. The DT_CENTER and DT_WORDBREAK flags passed in the fifth argument to DrawText() tell the system to center the text horizontally and wrap the text to the next line if it goes outside of the rectangle specified in argument four. Each call to BeginPaint() must be followed by an EndPaint() call (line 32) to complete the painting processes. These functions can be called
19
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 20
December 2010 – Issue 245
worldmags
20 worldmags
toolbars, it can be enabled by selecting View > Toolbars > Device from the menu bar. You can begin running the application in one of the Windows Mobile device emulators supplied as part of the Microsoft SDKs. You can do this by first selecting Build > Build Solution from the menu bar and fixing any errors that pop up. The second step is to choose Debug > Start Debugging from the same menus. The appropriate Windows Mobile emulator will activate and, after the program has been transferred to the emulator, it will display the message (see Photo 1). Click the OK button (see Photo 1) to stop the application. Since this is a mobile device, clicking the X at the top of the screen just minimizes the application rather than stop it as would happen on a desktop. Remember that minimized mobile applications still consume power. An emulator is all fine and dandy, but on-device debugging is the proverbial meat and potatoes when testing mobile applications. To do this, you need three more things: one, the free program Microsoft ActiveSync if running under XP or the Windows Mobile Device Center if you’re programming on Windows Vista; two, a cable to connect the device to the computer; and three, a mobile device itself. In our case, we first used the GPScapable HP iPAQ RX5910 loaded with Windows Mobile 5.0 for Pocket PC donated by a local company. To get started with ondevice testing, first connect your device to the computer and wait until ActiveSync/Windows Mobile
Listing 3—Changes to the WM_KEYDOWN case of the switch(wMessage) statement inside WndProc() start and stop the audio devices if the user presses certain buttons. 1 // Mask used to check if a key is being held down 2 #define PREVIOUSLY_DOWN_MASK 0x40000000 3 // WndProc variable declarations 4 static int recording = 0, playing = 0; 5 static HWAVEIN hWaveIn; 6 static HWAVEOUT hWaveOut; 7 static WAVEHDR waveOutBufferHeader; 8 static WAVEHDR waveInBufferHeader; 9 // etc 10 11 switch (wMessage) { 12 case WM_KEYDOWN: 13 // Check the PREVIOUSLY_DOWN bit of lParam to ensure we do 14 // not repeat actions if the button is held down 15 if ((lParam & PREVIOUSLY_DOWN_MASK) == 0) { 16 switch(wParam) { 17 case VK_RIGHT: //The user has selected record 18 // Record if not already recording or playing 19 if (!playing && !recording){ 20 recording = 1; 21 waveInAddBuffer(hWaveIn, &waveInBufferHeader, 22 sizeof(WAVEHDR)); 23 24 waveInStart(hWaveIn); 25 26 wsprintf(outputString, L"Recording Audio"); 27 InvalidateRect(hWnd, NULL, TRUE); 28 } 29 // else if we are currently recording and want to stop 30 else if (!playing && recording) { 31 recording = 0; 32 waveInReset(hWaveIn); 33 } 34 break; 35 36 case VK_LEFT: //The user has selected play 37 // If we aren't already recording or playing 38 if (!recording && !playing){ 39 playing = 1; 40 waveOutWrite(hWaveOut, &waveOutBufferHeader, 41 sizeof(WAVEHDR)); 42 43 wsprintf(outputString, 44 L"Playing back recorded audio"); 45 InvalidateRect(hWnd, NULL, TRUE); 46 } 47 //else if we are currently playing and want to stop 48 else if (!recording && playing) { 49 playing = 0; 50 waveOutReset(hWaveOut); 51 } 52 break; 53 54 default: 55 return DefWindowProc(hWnd, message, wParam, lParam); 56 } // End switch(wParam); 57 } // if ((lParam & PREVIOUSLY_DOWN_MASK) == 0) 58 else 59 return DefWindowProc(hWnd, message, wParam, lParam); 60 61 break; // End case WM_KEYDOWN: .. .. case WM_PAINT: etc; break; .. } // End switch(wMessage)
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 21
worldmags
Listing 4—New code inserted into the WM_CREATE case in the WndProc() function’s switch(wMessage) statement to initialize the buffer and audio devices
Device Center recognizes and syncs to it. Next, back in the Visual Studio development environment, select your project again. However, this time, choose the device option from the drop-down target-device selection menu (see Photo 3). Now simply follow the same build/debug procedure we used when running on an emulator.
KEY STROKE RECOGNITION The final Snorecognizer project will need more than just the ability to www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
print out a simple warning message such as “Oy you—you’re snoring.” The user will need to use the mobile device’s keys to control its operation. We can demonstrate this additional functionality by having the application output different messages to the screen according to which button has been pressed. Unlike a desktop or laptop with its keyboard, mobile devices have relatively few buttons. Pressing any of these keys causes a WM_KEYDOWN message to be sent to the WndProc()
December 2010 – Issue 245
100 case WM_CREATE: 101 // Setup the initial message and state variables 102 wsprintf(outputString, 103 L"Welcome to the Snorecognizer"); 104 recording = 0; 105 playing = 0; 106 107 // Zero the buffer header structures (will cause errors 108 // if not done) 109 memset(&waveInBufferHeader, 0, sizeof(WAVEHDR)); 110 memset(&waveOutBufferHeader, 0, sizeof(WAVEHDR)); 111 112 // Allocate and zero the audio buffer 113 waveInBufferHeader.lpData = new char[AUDIOBUFFERSIZE]; 114 waveOutBufferHeader.lpData = waveInBufferHeader.lpData; 115 waveInBufferHeader.dwBufferLength = AUDIOBUFFERSIZE; 116 waveOutBufferHeader.dwBufferLength = AUDIOBUFFERSIZE; 117 118 memset(waveInBufferHeader.lpData, 0, AUDIOBUFFERSIZE); 119 120 // Setup the audio format based on pre-defined values 121 WAVEFORMATEX waveFormat; 122 waveFormat.wFormatTag = CHOSEN_WAVE_FORMAT; 123 waveFormat.nChannels = CHANNELS; 124 waveFormat.nSamplesPerSec = SAMPLES_PER_SEC; 125 waveFormat.nAvgBytesPerSec = AVG_BYTES_PER_SEC; 126 waveFormat.nBlockAlign = BLOCK_ALIGN; 127 waveFormat.wBitsPerSample = BITS_PER_SAMPLE; 128 waveFormat.cbSize = CBSIZE; 129 130 // Open connections to the audio devices 131 waveInOpen(&hWaveIn, 0, &waveFormat, (DWORD) hWnd, 0, 132 CALLBACK_WINDOW); 133 waveOutOpen(&hWaveOut, 0, &waveFormat, (DWORD) hWnd, 0, 134 CALLBACK_WINDOW); 135 136 // Prepare the headers 137 waveInPrepareHeader(hWaveIn, &waveInBufferHeader, 138 sizeof(WAVEHDR)); 139 waveOutPrepareHeader(hWaveOut, &waveOutBufferHeader, 140 sizeof(WAVEHDR)); 141 142 // Code already in WM_CREATE (generated by Visual Studio) 143 // to handle the application menus 144 145 break;
21
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 22
worldmags
function. Refer to Listing 2 (lines 11 to 29) for details on how the WM_KEYDOWN message is handled. Detailed information about each WM_KEYDOWN message is contained in the wParam and lParam arguments passed to WndProc() (line 1). The wParam variable contains a code corresponding to which key has been pressed. The lParam variable contains additional information about the key press, such as whether or not the key has been pressed and released or is being held down. (We will need this information later on.)
December 2010 – Issue 245
KEY USE
22 worldmags
To demonstrate using the keys, we modified certain aspects of the WndProc() function (see Listing 2). Let’s review. To enable the WM_PAINT event to display different messages, we are able to change the TCHAR string array used by the DrawText() function inside the WM_PAINT case statement. As a result, we can modify what is displayed on the screen when a button is pressed. Now we can create a new case inside the switch(wMessage) statement of WndProc() to handle WM_KEYDOWN messages. This gives the application the ability to recognize a key press. Inside this new case statement, wParam was compared to the Windows constants VK_RIGHT (right arrow, line 14) and VK_LEFT (left arrow, line 18) in order to decipher which key had been pressed. Our outputString (line 4) can be modified to display a different message using wsprintf(). The wsprintf() function differs from the standard sprintf() write-to-astring-buffer function in that it handles the “wide” Unicode-enabled characters rather than standard 8-bit characters. The default case of the WM_KEYDOWN message (line 23) activates the DefWindowProc() function. This informs the OS that it is to perform the default action corresponding to the current key press. This is a better programming style than just
Listing 5—These are definitions used to set the audio format and audio buffer size placed inside the Snorecognizer.h file, which is included in the main Snorecognizer.cpp file. // Pulse Code Modulation format #define CHOSEN_WAVE_FORMAT WAVE_FORMAT_PCM // Mono #define #define #define
audio with 44.1-kHz sampling rate, 2 bytes per sample CHANNELS 1 SAMPLES_PER_SEC 44100 BITS_PER_SAMPLE 16
// 2 bytes per block #define BLOCK_ALIGN (((CHANNELS) * (BITS_PER_SAMPLE)) / 8) // 88,200 bytes per second #define AVG_BYTES_PER_SEC ((SAMPLES_PER_SEC) * (BLOCK_ALIGN)) // 5-second audio buffer size #define AUDIOBUFFERSIZE (5 * AVG_BYTES_PER_SEC) // Size in bytes of any extra space at the end of the // WAVEFORMATEX structure for additional user info #define CBSIZE 0
setting the default case code to the following: default: /* DO NOTHING */ break; This would not allow any other device keys to function properly. We can force the mobile OS to issue a WM_PAINT message to update the device’s display window. This is done in line 28 by passing the InvalidateRect() function a handle, hWnd, to the window we want to invalidate (redraw). Setting the second parameter to NULL causes the window’s entire client area to be updated, rather than just part of it. The last argument of InvalidateRect() is set to TRUE so as to erase the background before
painting over it. Setting this parameter to FALSE will cause the new text to be written without erasing the previously displayed message first. Running the program with these changes will display the welcome message on the screen initially. Pressing the left or right arrow keys will cause a change between “playback” and “recording” messages, respectively.
AUDIO I/O DEVICES The final stage in developing the prototype has to do with using the mobile OS waveform audio input and output devices. In the case of Windows Mobile, the built-in microphone and speakers are the devices used. Listing 3 shows the modification
Listing 6—New cases added to the WndProc() function’s switch(wMessage) statement to handle messages sent when the audio devices finish reading/writing their buffers //case for when the waveOut device has finished playback 60 case MM_WOM_DONE: 61 wsprintf(outputString, L"Audio recording complete"); 62 InvalidateRect(hWnd, NULL, TRUE); 63 break; 64 65 //case for when the waveIn device has finished recording 66 case MM_WIM_DATA: 67 wsprintf(outputString, L"Playback complete"); 68 InvalidateRect(hWnd, NULL, TRUE); 69 break;
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 23
worldmags
of the WM_KEYDOWN events so that the application will record a sound and then play it back. Four functions need to be controlled: start recording, stop recording, start playback, and stop playback. The user interface would be intuitive if we used one press of the right key to start recording, and a second press to stop the recording. Similarly, we use the left key to start and stop the playback. We’ll also initially limit the audio operation to recording and playing back five seconds of sound into a specified buffer. The application stops recording/playback either when you tell it to (second key press) or when it reaches the end of the buffer, whichever comes first. The first lines in Listing 3 show static variables needed for the new WndProc() function. The state variables playing and recording will keep track of the application’s current play/record state. Device handles to the audio in/out devices hWaveIn and hWaveOut are used to identify each device (lines 5 and 6). The WAVEHDR structures will hold information regarding the audio buffer, as well as a pointer to the buffer itself. We use one buffer to
hold the audio information. This means that in the prototype, you can’t play and record at the same time. Two WAVEHDR structures are required: one header used by the audio-in device and the other is used by the audio-out device (lines 7 and 8). Both headers will use a pointer to the same audio buffer. We can now make use of the lParam variable, which contains additional information about the WM_KEYDOWN message. In Listing 2, we changed the display for each WM_KEYDOWN message. It does not really matter if we have been accidently holding down a key for long enough to activate its “repeat” functionality. Now, in this new prototype, we don’t want to recognize a second WM_KEYDOWN event until you have physically released the key. We can avoid this “repeat” operation gotcha by checking the PREVIOUSLY_DOWN_MASK bit of the lParam (line 15). If this bit is not zero, we don’t want to re-execute the case statement as the application is in the “repeat keystroke” mode. If the right key has been pressed for the first time, we want to start recording (line 17). This involves
70 case WM_DESTROY: 71 // Force the devices to stop what they are doing 72 // and return the queued buffer(s) to the 73 // application 74 waveOutReset(hWaveOut); 75 waveInReset(hWaveIn); 76 77 // Unprepare both headers 78 waveOutUnprepareHeader(hWaveOut, &waveOutBufferHeader, 79 sizeof(WAVEHDR)); 80 waveInUnprepareHeader(hWaveIn, &waveInBufferHeader, 81 sizeof(WAVEHDR)); 82 83 // Close the device connections 84 waveOutClose(hWaveOut); 85 waveInClose(hWaveIn); 86 87 // Remove the audio buffer 88 delete [] waveInBufferHeader.lpData; 89 90 // Code already in WM_DESTROY (generated By Visual Studio) .. // to destroy the basic application menu .. .. break;
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
Listing 7—New code inserted into the WM_DESTROY case in the WndProc() function’s switch(wMessage) statement to clean up allocated memory and close audio device connections.
23
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 24
worldmags
using waveInAddBuffer() to tell the OS to add a new buffer to the audio input (wave) queue (line 21). Then the audio device is activated (waveInStart(), line 24) and the user informed that recording has started. A second press of the right key causes the recording to stop (waveInReset(), line 32). In a similar way, the left key is used to control the wave output device. The waveOutWrite() function handles both queuing the buffer and starting the output audio device (line 40).
December 2010 – Issue 245
AUDIO DEVICE INITIALIZATION
24 worldmags
When the window for the application is first created, a WM_CREATE message is sent to the WndProc() function by the OS. In the default code, WM_CREATE is used to create the OK and HELP menu at the bottom of the application window (see Photo 1). Additional code must be placed in this case statement to set up the audio devices (see Listing 4). The inserted code has a straightforward logical flow. The string and state variables are set to their initial values. Both input and output buffer headers are then zeroed to avoid causing errors down the road. The lpData member of the WAVEHDR structures will point to the audio buffer, which we have to allocate. Although the audio buffer is made up of signed short integer (16-bit) values, the dwBufferLength value must be expressed in bytes— another gotcha to be avoided in lines 115 and 116. The buffer itself needs to be zeroed to avoid producing painful sounds when the output device is first activated. Next, we fill a WAVEFORMATEX structure with audio format information defined in Listing 5. The format structure is then passed to the waveInOpen() and waveOutOpen() functions, which specifies our selected audio format to the audio devices (lines 131 and 133). The waveInOpen() and waveOutOpen() functions open handles to the microphone and speakers, respectively. We pass a pointer to the handle we wish to populate (hWaveIn or hWaveOut) as the first argument to these functions. The second argument specifies which audioin/out device we would like to use, although there’s a good chance your device only has one. The audio format is specified by the third argument—a pointer to our WAVEFORMATEX structure. The audio devices themselves are capable of sending messages (much like WM_KEYDOWN) to a callback mechanism. The fourth and sixth arguments of waveInOpen() and waveOutOpen() tell the system to send any messages from the audio devices to our application’s WndProc() function. The fifth argument is saved for any custom data and is not currently used. Now that we have opened the device handles, we must prepare the buffer headers. This is done using the waveInPrepareHeader() and waveOutPrepareHeader() functions (lines 137 and 138). We pass the device handles, hWaveIn and hWaveOut, to the functions to identify which devices we are referring to. The second argument is a pointer to the header we want to prepare. In addition, we must specify the size of the header, which
is passed in the third argument.
COMPLETED BUFFERS Now that we are in the position to be able to start recording and playback, how can we tell if an audio device has completed filling or emptying its buffer? We need this information to be able to update the screen with a “done” message to the user, but how? The route to solving this problem is the parameter CALLBACK_WINDOW used in the waveInOpen() and waveOutOpen() functions in Listing 4 (lines 132 and 134). This specifies that our program window is to be the callback mechanism for any messages from the audio devices. Because of this, when the wave-out device finishes with a buffer, it will send a MM_WOM_DONE message to the WndProc() function. We can create a new case inside the main WndProc() switch statement (see Listing 6, Line 60) for this message in order to update outputString. Equivalently, the MM_WIM_DATA (line 66) message is sent when the wave-in device has finished with its buffer.
APPLICATION CLOSEDOWN With the current code, the mobile device will be left in an inoperable situation for other applications when the user clicks “Ok” to exit the Snorecognizer prototype. For example, we have allocated a buffer in WM_CREATE. If this is not released, then exiting the code will generate a memory leak. In addition, if we “prepare” a buffer header for a device and forget to “unprepare” it, it will remain with the device even if our program exits! Once the audio device has been filled with “prepared” headers, it will refuse additional buffer headers, requiring a hard reset of the system. In order to avoid these troublesome errors, we should ensure our program properly cleans up after itself. (It reminds me of what my great-great aunt Agatha always used to tell me about tidying my room.) We will have to release the audio buffer, unprepare the buffer headers, and close the audio device handles. All of this can be accomplished inside the WM_DESTROY case of the WndProc() function’s main switch statement (see Listing 7). A WM_DESTROY message is sent to WndProc() whenever the window is destroyed (line 70). This mirrors the initialization code we wrote for the WM_CREATE message. The main gotcha to avoid is to release things in WM_DESTROY in the exact opposite order in which they were created in WM_CREATE. For example, the handles become useless after they have been closed. With clean code, the window can close without worry of a memory leak or other errors.
WHERE TO NEXT? In this article, I described a simple prototype for the Snorecognizer Windows Mobile application. So far, the design handles basic key input/screen output and controls the on-board audio devices on a Windows Mobile device. I hope you enjoyed this article. In the next article, I’ll CIRCUIT CELLAR®
•
www.circuitcellar.com
2112014_Kotchorek_Layout 1 11/8/2010 11:39 AM Page 25
worldmags
delve further into the world of Windows Mobile and “snore recognition.” I will explain how to expand the prototype’s functionality to include simple audio DSP and handling audio operations over a long period of time. I’ll even cover the topic of graphing the results! I Authors’ Note: We would like to thank DirectVoxx and Telus for arranging the donation of the mobile equipment used for this article. The Snorecognizer application was a spin-off from Riley Kotchorek’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. Vahid Garousi’s Alberta Ingenuity New Faculty Award no. 200600673. We also thank Lizie Dunling-Smith for her editorial suggestions in making the article more readable. 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 BS in Computer Engineering in June 2011.
Computing/HMI
Serial
I/O
The right connection creates incredible power. Connectivity and control. Making your interface as reliable as the tides—and just as strong. Sealevel creates hardware and software solutions for both digital and serial interface requirements. We Listen. Think. And Create.
SeaI/O® data acquisition modules provide powerful digital, analog, and serial expansion to any computer. Two new modules now available to add even more flexibility to your distributed I/O network with 16 high-current optically isolated inputs / 16 open collector outputs or 32 open collector outputs.
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. www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
sealevel.com >
[email protected] > 864. 843. 4343
© 1986-2010, Sealevel Systems, Inc. All rights reserved.
26_Layout 1 10/27/2010 12:55 PM 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
Get started quickly and proceed rapidly
Python Programming and GUIs This book is aimed at people who want to interface PCs with hardware projects using graphic user interfaces. The programming language used is Python, an object-oriented scripting language; a higher level language than, say, C. The book guides you through starting with Linux by way of a free downloadable, live bootable distribution that can be ported around different computers without requiring hard drive installation. Practical demonstration circuits and downloadable, full software examples are presented that can be the basis for further projects. 224 pages • ISBN 978-0-905705-87-3 • $47.60
ore This book and m are available at m/books www.elektor.co Visual Studio
Books
C# 2010 Programming and PC interfacing This book is aimed at anyone who wants to learn about C# programming and interfacing
Use only free or open source software
to a PC. It covers programming concepts from the basics to object oriented programming,
ARM Microcontroller Interfacing
displaying graphs, threading and databases. The book is complete with many full program examples, self assessment exercises and links to supporting videos. All code examples used are available –free of charge– from the www.elektor.com support website; you can easily
Learn to interface and program hardware devi-
create your own results to demonstrate the concepts explained and reinforce your learning in
ces in a wide range of useful applications, using
the process. Professional quality software tools are downloadable –also free of charge– from
ARM7 microcontrollers and the C program-
Microsoft. The Microsoft Visual Studio 2010 environment is extensively covered with user
ming language. Examples covered in full de-
controls and their properties, methods and events. Detailed guidance is provided for those
tail include a simple LED to a multi-megabyte
wishing to control hardware from a PC with PC interfacing chapters which explain the legacy
SD card running the FAT file system. A chapter
serial and parallel ports, analogue interfacing using the sound card and use of Microsoft DirectX
on more advanced ARM microcontrollers is in-
drivers. Interfacing to the ubiquitous USB port is explained in-depth with a detailed hardware
cluded with an overview of some of the newest
and software design for a USB connected PIC-based hardware target included.
ARM microcontrollers and their features.
305 pages • ISBN 978-0-905705-95-8 • $47.60
250 pages • ISBN 978-0-905705-91-0 • $47.60
Prices and item descriptions subject to change. E. & O.E
worldmags
Bestseller!
27_Layout 1 10/27/2010 1:15 PM Page 1
CD/DVD-ROMs
worldmags
Bestseller!
Reign with the Sceptre
InterSceptre
This open-source & open-hardware project
Recently, Elektor introduced Sceptre, a fast
aims to be more than just a little board with a
prototyping system fitted with a 32-bit
big microcontroller and a few useful peripherals
microcontroller. Even on its own, this board will
— it seeks to be a 32-bit ARM7 fast prototyping
let you produce some great results, but if we
system. To justify this title, in addition to a very
add an extension board to make it easier to
useful little board, we also need user-friendly
access all its peripherals, the Sceptre platform
development tools and libraries that allow fast
becomes downright powerful. What’s more, if
implementation of the board’s peripherals. Am-
you fit this extension board into a suitable case,
bitious? Maybe, but nothing should deter you
you’ll be able right from the start to develop
from becoming Master of Embedded Systems
a prototype that you can use ‘properly’ in a
Universe with the help of the Elektor Sceptre.
installation, with no trailing wires or bits of
75 Audio designs for home construction
DVD The Audio
collection 3 A unique DVD for the true audio lover, containing more than 75 different audio circuits from the volumes 2002-2008 of Elektor. The articles on the DVD-ROM cover Amplifiers, Digital Audio, Loudspeakers, PC Audio, Test & Measurement and Valves. Using the included Adobe Reader you are able to browse the articles on your computer, as well as print texts, circuit diagrams and
0#" POPULATEDANDTESTED
PCB layouts.
TESTSOFTWARELOADED
ISBN 978-90-5381-263-1 • $28.90
Art.# 090559-91• $143.60
sticky tape holding everything together. Now that’s what you call fast, convenient prototyping!
+ITOFPARTS CONTAINS0#"ANDCOMPONENTS Art.# 100174-71 • $ 187.10
New! More than 75 power supply designs
CD The Power Supply
www.elektor.com/shop
The Elektor DSP radio Many radio amateurs in practice use two receivers, one portable and the other a fixed receiver with a PC control facility. The Elektor DSP radio
This CD-ROM contains more than 75 different can operate in either capacity, with a USB interpower supply circuits from the volumes 2001face giving the option of PC control. An addi2005 of Elektor. Highlights include the Cuk Contional feature of the USB interface is that it can verter, Automatic Battery Switchover, Battery be used as the source of power for the receiver, Voltage LED, Digital Benchtop Power Supply, the audio output being connected to the PC’s Lithium-Ion Charger, Lithium-Ion Charger and much more. Using the included Adobe Reader you are able to browse the articles on your computer, as well as print texts, circuit diagrams and PCB layouts. ISBN 978-90-5381-265-5 • $28.90
worldmags
Elektor US PO Box 180 Vernon, CT 06066 USA Phone: 860-875-2199 Fax: 860-871-0411 E-mail:
[email protected] powered speakers. To allow portable 6 V battery operation the circuit also provides for an audio amplifier with one or two loudspeakers.
0#" ASSEMBLEDANDTESTED Art.# 100126-91 • $240.40
Kits & Modules
Collection 1
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!
2112016_ohmit_Layout 1 11/3/2010 3:23 PM Page 28
F EATURE
worldmags
ARTICLE
by Eric Ohmit (USA)
MCU-Based Aircraft Data Logging and Telemetry (Part 2)
of
Art
Telemetry System Development and Results
na The first article in this series detailed how to design an aircraft data logger. This article covers the development of the telemetry system. Useful test results are presented.
I
n the first part of this series, I presented a practical aircraft data logger design developed around a Microchip Technology PIC24F64GA002 processor. Here I cover the telemetry portion of the system.
DOWNLINK MODULE The downlink module is a simple circuit used to enable transmission by a Radiometrix TXM-433 module. Photo 1a shows the module during the development with the Microchip 28-pin, 16-bit development board. Photo 1b shows the transmitter mounted to the upper surface of
December 2010 – Issue 245
a)
28 worldmags
the wing with the foil ground plane. Figure 1 shows the schematic of the final configuration. The antenna was a quarter wavelength (6″) with a ground plane mounted on the upper part of the wing. The nominal output of the UART on the data logger is 0 to 3.3 V. The TXM-433 transmitter is powered by a 9-V battery to maximize the power of the transmitted signal, and it requires a minimum high-level voltage level of 4 V for data input. A Radiometrix SILRX433 receiver is not capable of receiving a DC signal. Frequency errors and drift between the transmitter and
b)
Photo 1a—This is the downlink module during development with the Microchip 28-pin, 16-bit development board. b—The downlink module is mounted to a Sig Manufacturing LT-40 on a foil ground plane. You can see the connection to the data logger. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112016_ohmit_Layout 1 11/3/2010 3:23 PM Page 29
Figure 1—The downlink module
disables (powers off) the transmitter. Data bytes are transmitted at 2,400 bps. Later developments have included other parameters (altitude, acceleration, airspeed, etc.) for additional information as well as an increased data rate of 4,800 bps.
receiver will cause errors for signals that exceed the maximum pulse width BASE STATION MODULE (20 ms). The PIC24 UART idle time I developed the base station module between transmissions sent by the to receive the data sent from the airtransmitter will easily exceed this borne telemetry, interpret this data, time. The resulting erroneous signals convert it to temperature in degrees would fill the four-element UART Celsius, and then announce that tembuffer in the PIC24 with garbage. perature through the earpiece to the The first alternative was to continupilot. Speech synthesis was accomously transmit the values from the plished using the programs developed logger; this worked, but defeated the for the “Demo2—Talking Thermomeoriginal plan to use the RC radio to ter” provided by Elektor and described command the transmission of the curin “Explorer-16 Value Pack and audio rent temperature. The next alternative signal processing” (an article from was to use a TC4427 MOSFET driver Elektor magazine February 2007). The to enable (key) the transmitter. Since code—which is available at www.elekthere is no separate TRANSMIT pin tor.com/Uploads/Files/Demo2_1.zip— on the TXM-433, the only method uses the methods described in available was to turn the unit on and Rodger Richey’s 2007 application note off. A separate line (RB9) from the “Adaptive Differential Pulse Code PIC24 was used to power the transModulation using the PIC16/17” mitter via the TC4427. The other line (Microchip AN643) to create an audio (RB8) was then fed to the other availstring of words, replaying combinaable channel of the chip switching the tions of words to form a phrase which 9 V to transmit the data. This elimiprovides the temperature. I modified nated the addition of a buffer between the original Demo2 code to accept the the PIC24 and the transmitter. When downlinked bytes of the temperature the transmission is done, the RB9 line measured onboard the model when is brought to zero to disable (turn off) the RC pilot selects the appropriate the transmitter until the next request position on his transmitter. for data. When transmitting the data, the software in the data logger module first enables the transmitter by setting the RB9 pin to high. A short delay is then provided to allow the unit to power up prior to sending the data. The 2 bytes associated with the upper and lower bytes of the temperature are then sent through the RB8 pin, which was assigned the UART Tx function using the PPS function of the PIC24. After the last bit of the byte is sent, the unit waits for a Photo 2—The initial development of a voice filter with short period of time and then Microchip 28-pin development board www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Initial testing of the generation of voice was implemented using the Microchip 28-pin, 16-bit development board (see Photo 2). I developed the software on the development board and implemented the fourthorder low-pass filter on a protoboard using a potentiometer to adjust the volume. The original Demo2 software was modified to run on the 28-pin PIC24. These changes include reassigning the input and output pins (since the original code was developed for the PIC24FJ128GA010, 100-pin processor). A protoboard using the PIC24F was assembled because the base station had to be portable (see Photo 3). On the right of the board is the PIC24FJ64GA002 processor in a DIP format. An MCP4011 digipot was used in the original circuit to control volume. Two push buttons were used to provide the *CS and UP/DN inputs to control volume. This was found later to be cumbersome and eventually replaced with a potentiometer. Power for the processor and the fourth-order speech filter came from a Panasonic AN77 3.5-V voltage regulator (found in my parts stash) and within the allowable voltage range of the PIC24F. The Radiometrix SILRX-433 receiver is located on the left side of the board. The antenna is mounted directly to the board. A 5-V National Semiconductor LM2931 voltage regulator is used for its power. The receiver’s Detect output detects the presence of the TXM433 carrier prior to the data transfer. This output is wired to a PNP transistor (BC858). The transistor’s output is then sent to a comparator using an MCP6022 opamp. I found that a level of 1 V on the negative input of the comparator is sufficient to detect the transmission at the ranges used. The output of this comparator is sent to the CD4051 analog multiplexer, which controls whether the output of the data line from the SILRX-433 will be fed to the UART Rx input of the PIC24F. the The comparator’s output is also
December 2010 – Issue 245
worldmags
29
2112016_ohmit_Layout 1 11/3/2010 3:24 PM Page 30
worldmags
December 2010 – Issue 245
code modulation (ADPCM) method of wave file compression described in AN643. Sound bites are created for numbers and words, which are later combined to create phrases. The sound bites are stored as arrays in the program. Sufficient program memory is available for the voice files used in this application. The internal 8-MHz oscillator and the Photo 3—The base station protoboard used for this project PLL are used (resulting in a 32-MHz processor clock rate). Data is received from the SILRXsent to the PIC24 RB5 input. This pin is 433 in the form of the upper and lower monitored by the software. When it bytes of the 12-bit temperature meastransitions low, the software enables the ured by the data logger. UART and waits for the 2 bytes to be received. After they are received, the Figure 3 illustrates a software block UART is disabled again. Figure 2 is diagram of the base station code. This the schematic, which reflects the prosoftware is organized in two tasks. toboard shown in Photo 3. The first task is initialization, where The speech-generation program the inputs and outputs are assigned. uses the adaptive differential pulse The PPS feature is used to assign the
30 worldmags
output compare (OC) module, which generates a PWM signal at 16 kHz with a 50% duty cycle. The second task performs an infinite loop, waiting for the carrier-detect input on RB5. When RB5 is low, the UART is enabled after receipt of the bytes; the software converts this to temperature in degrees Celsius. The decimal representation of the temperature is parsed into the hundreds, tens, and ones. These values are then used to look up the file locations that contain the compressed encoded bytes, which represent its associated sound bite. These sound bites are then decoded and used to modulate the duty cycle of the PWM signal sent on the OC pin. The output of the OC pin (RB6) is passed through the fourth-order low-pass filter. This filter removes the high-frequency PWM component of the signal so all that remains is the low-frequency audio created by the modulation. Once each part of the number is announced, it is followed up by the
Figure 2—The base station module CIRCUIT CELLAR®
•
www.circuitcellar.com
2112016_ohmit_Layout 1 11/9/2010 12:29 PM Page 31
worldmags
sound bytes representing the words “degrees” and “Celsius.”
RESULTS I used the Sig Manufacturing LT-40 model for the airborne testing of the downlink module. Flight tests with the downlink module on the LT-40 were very successful. With the whip antennas on the transmitter and receiver and ground planes on both (conformal foil ground plane on the model and a 10″ × 10″ aluminum ground plane on the base station), it was found the in-air range was excellent. Plots were obtained from the onboard data logger. Photo 4 illustrates three plots of data from a flight with the LT-40 model. The first plot illustrates the altitude of the model. The initial altitude is with the model on the runway and reflects the model’s
Power up
Initialization - PPS - Ports I/O
N
Carrier detected? RB5 == 0
Photo 4—This is data from the Sig Manufacturing LT-40. You see altitude, temperature, and PWM data from the test flight.
altitude above sea level. The next plot illustrates the temperature-time histories during the same flight of the sensor mounted on the motor battery (a four-cell Li-ion pack). The last plot illustrates the RC radio PWM commands. Note the value transitions between just above 1.5 to 1.8 ms. This reflects the pilot selecting the third position of the switch on his RC radio. Each time this was selected, the temperature was
announced in the base station’s earpiece. The values heard prior to flight were “14 degrees Celsius.” As the model climbed, the battery temperature increased slowly as it supplied current to the motor, and the spoken temperatures increased with the temperature. For the majority of the flight, I heard “22 degrees Celsius.” A peak temperature of “23 degrees Celsius” was announced in the earpiece after the model landed. These all correspond
Y Enable UART
Receive TM Data via UART Rx
Convert to degC
Send decoded ADPCM string to OC module
Disable UART
Figure 3—The base station software www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Photo 5—This is motor current, battery voltage, propeller RPM/10, airspeed, and acceleration data obtained during the downlink test flight.
December 2010 – Issue 245
Formulate phrase based on temperature “xx” “degrees” “Celsius”
31
2112016_ohmit_Layout 1 11/3/2010 3:24 PM Page 32
worldmags
Photo 7—The latest version of the data logger with the Microchip PIC24HJ128GP502 MLF
very well to the recorded temperatures shown in Photo 4. Several climbs and turns were performed during the flight in an attempt to test the system at different altitudes and attitudes (with respect to the receiver). Each time the switch was selected the temperature was announced. Note that the maximum altitude was approximately 300′ above the ground. The model was also flown more than 600′ away, as well as directly overhead. No problems occurred with the transmission of temperature during any portion of the flight. Photo 5 illustrates additional data that was obtained during this
flight, including current, voltage, RPM, airspeed (nautical miles per hour), and acceleration. The wind was blowing during this flight and varied between 5 and 10 MPH, which is reflected in the airspeed indication after the model landed and before take off into the wind. The resolution of the pressure prevented accurate speed indications at these speeds, so the majority of the data while not moving was noisy. I think the best indication of this project’s success was how much I learned about using the Microchip PIC24. Also, I now have a useful way to record and know in real-time the most
December 2010 – Issue 245
Photo 6—The latest version of the airborne downlink module and base station with Linx RF modules and enhanced features
32 worldmags
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112016_ohmit_Layout 1 11/3/2010 3:24 PM Page 33
worldmags
RECENT DEVELOPMENTS Since finishing the first version of this project, I’ve made some upgrades. The base station can now evaluate other features of the PIC24F: the RTCC, 40-MHz operation (using an external crystal), the addition of a Nokia cell phone color LCD (which uses a SPI), and a microSD card and EEPROM for data storage. The Radiometrix modules have proven to be limited. Other systems tested include Linx 433-MHz transmitter/receiver pairs (see Photo 6) and Digi International XBee 2.4-GHz systems. As for the on-board data logger, I designed the final PCB for the main board using the MLF chip form factor (see Photo 7). In addition, I incorporated a microSD card in the system to provide data in the form of FAT16 data files and a huge increase in storage space. Lastly, I now use GPS to acquire position, velocity, and real GPS time and integrate it with the on-board data. This GPS time and date is also used to provide the correct time and date attributes for the FAT16 files stored on the microSD card. I Eric Ohmit (
[email protected]) is an Aeronautical Engineer with a BS in Aeronautical and Astronautical Engineering from Purdue University. He has worked in the aerospace industry for almost 30 years and he specializes in flight control systems. Eric has been building model airplanes, rockets, and electronics designs for over 40 years. He is also a semi-active Ham, KC2FKV.
PROJECT FILES To download the code, go to ftp://ftp.circuitcellar.com/pub/ Circuit_Cellar/2010/245.
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
RESOURCES J. Buiting and L. Lemmens, “Explorer-16 Value Pack and Audio Signal processing,” Elektor, 2007. Microchip Technology, “PIC24FJ64GA004 Family Data Sheet,” DS39881B, 2007. Radiometrix, “UHF Radio Telemetry Receiver Module,” SILRX-UHF, 2001. ———, “UHF Radio Telemetry Transmit Module,” TXM-433, 2002. R. Richey, “Adaptive Differential Pulse Code Modulation Using the PIC16/17,” AN643, Microchip Technology, 2007.
SOURCES Motorola MPXAZ6115 pressure sensors Freescale Semiconductor, Inc. | www.freescale.com LTC-1865 ADC Linear Technology | www.linear.com PIC24FJ64GA002 Microcontroller Microchip Technology, Inc. | www.microchip.com 433-MHz SILRX Receiver and TXM transmitter Radiometrix | www.radiometrix.co.uk PQ1X331M and PQ1X451M regulators Sharp Microelectronics | www.sharpsme.com
December 2010 – Issue 245
critical information needed to safely operate my electric model aircraft. Now that I’ve had a chance to try the PIC24F 16-bit processors with their flexibility, memory size (program and RAM), speed, peripheral pin select, and timers, I will likely continue using the PIC24 chips. I look forward to incorporating the PIC24H series (high speed) and the new 28-pin USB PIC24 chips into this design.
33
2112015_Dzioba_Layout 1 11/8/2010 12:03 PM Page 34
F EATURE
worldmags
ARTICLE
by Richard Dzioba (Canada)
Interactive USB Module Are you ready to unlock the mysteries of USB? It’s possible with this low-cost project. Here you learn how to build an interactive module of your own.
T
his project began as a low-cost way for me to understand how a USB device communicates with a host PC. I have always been curious about USB and its complicated terminology, and since my preferred learning style is hands-on, I wanted to design a simple USB device that I could interact with. My objective was to gain a good understanding of the USB protocol while keeping the hardware and software development simple. In this article, I’ll describe the approach I took to design and build the interactive USB module shown in Photo 1. a)
plugged into a USB port. I decided the simplest, most affordable way to accomplish this task was to monitor the USB transactions using a microcontroller’s serial port while the microcontroller was interacting with the host PC via the USB port. To keep the host software development straightforward, I used the human interface device (HID) drivers built into Windows. This saved time because I didn’t have to learn how to develop and test Windows drivers.
b)
December 2010 – Issue 245
MCU-BASED MONITORING
34 worldmags
The USB protocol is complex. A lot has to go well for a USB device to talk to a PC. You plug your device into a USB port expecting the melodic “dooDIT” sound that Windows makes when it identifies your device. But, if things aren’t just right, Windows responds with stony silence and you have no clue what went wrong. Passiveaggressive, anyone? Without some sort of interactive device, you are really in the dark as to where to start looking for answers. What I needed was a means to display USB transactions and status information, starting from the time the device was
Photo 1a—The device is simple enough for a single-sided PCB. b—A close-up of the CP2102 USB-to-serial carrier board showing the MLP package chip. Both boards were made using “Press-n-Peel” toner transfer film and all parts were hand soldered. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112015_Dzioba_Layout 1 11/8/2010 12:03 PM Page 35
worldmags
An added benefit of creating an HID device was that free software is available that provides a simple PC
interface for testing the device. For inspiration, I turned to Lane Hauck’s August 2006 article titled
Listing 1—Here is an example of the macros that are used to configure the USB endpoints. The use of macros greatly simplifies the source code. ;------------------------------------------------; Configure Endpoints ;------------------------------------------------Configure_Endpoints: ; Endpoint 0 (Control Endpoint): ResetEndpoint (EP_0) SelectEndpoint (EP_0) EnableEndpoint SetEndpointType (EP_CONTROL | EP_OUT) SetEndpointSize (EP_SIZE64 | EP_ONE_BANK) AllocateEndpointMemory EnableSETUP ;
Endpoint 1 (IN Endpoint): ResetEndpoint (EP_1) SelectEndpoint (EP_1) EnableEndpoint SetEndpointType (EP_INTERRUPT | EP_IN) SetEndpointSize (EP_SIZE32 | EP_ONE_BANK) AllocateEndpointMemory EnableIN
;
Endpoint 2 (OUT Endpoint): ResetEndpoint (EP_2) SelectEndpoint (EP_2) EnableEndpoint SetEndpointType (EP_INTERRUPT | EP_OUT) SetEndpointSize (EP_SIZE32 | EP_ONE_BANK) AllocateEndpointMemory EnableOUT
;
ret
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
“Windows Volume Control” (Circuit Cellar 193). Lane’s code illustrated how to develop a simple Windows HID device using a Maxim MAX3420E USB peripheral controller. However, the MAX3420E requires a 3.3-V regulator and a microcontroller to make it work, so I decided to look for a simpler hardware solution. Since I was already familiar with the Atmel AVR series of 8-bit microcontrollers used in Hauck’s article, I settled on an AT90USB162. The AT90USB162 is a low-cost chip that contains an AVR microcontroller, a serial port, a USB 2.0 full-speed module, and a 3.3-V voltage regulator to power the USB interface. Perfect! This allowed me to reuse some of Hauck’s code, and I didn’t need much in the way of additional hardware: a 16-MHz crystal, a few passive components, and a USB connector. The AT90USB162 also has plenty of flash memory. It has 16 KB compared to the 1 KB in the ATtiny13 that Hauck used, so I didn’t have to worry about writing compact code. The large amount of flash memory provides a handy feature: the AT90USB162 is factory-programmed with a device firmware upgrade (DFU) bootloader that enables you to program the
December 2010 – Issue 245
Figure 1—The schematic is very simple. No additional power supply is needed as each chip takes its power directly from the USB bus. I included an ISP interface even though the chip can be programmed via the USB port. I found the ISP to be the most convenient way to perform quick edit-compile-load-test firmware development.
35
2112015_Dzioba_Layout 1 11/9/2010 12:48 PM Page 36
worldmags
Macro ConfigureUSART_1x ConfigureUSART_2x PutChrI PutChr PutHexI PutHex
Parameter(s) Data rate Data rate Literal, newline Register, newline Literal, newline Register, newline
Description Configure USART for low-speed operation Configure USART for high-speed operation Put Character Immediate Put Character Put Hex Immediate Put Hex
Notes Best for low data rates Best for high data rates Newline = TRUE or FALSE. If TRUE, then append a new line sequence (/)
Table 1—The project uses the serial port and a set of macros to manage the port, making the main software easier to write.
microcontroller using the USB port.
December 2010 – Issue 245
HARDWARE DESIGN
36 worldmags
The AT90USB162 can operate in the range of 4.5 to 5.5 V at 16 MHz and is suitable for a bus-powered design (see Figure 1). In this mode, the microcontroller gets all of its power from the USB bus. A bus-powered design does present some additional responsibilities over a selfpowered design in order to meet USB power restrictions. At the top end of the power scale, a USB port can provide up to 100 mA (or 500 mA for a high-power hub). At the low end is USB Suspend mode, which is activated when Windows is placed in Standby mode. The revised USB specification states that in Suspend mode, a USB device can’t draw more than 2.5 mA from the bus. This low-power requirement can create some design challenges, for example the choice of CPU clock method. I usually like to use integrated (“canned”) oscillators with my microcontroller projects because they eliminate any uncertainty that the oscillator is actually running, a problem I have encountered with some crystal oscillator designs. Unfortunately, canned oscillators typically draw 15 mA or more at 5 V. The Suspend power limitation pretty much dictates using the AT90USB162’s lowpower oscillator mode with an external crystal. The AT90USB162 provides a Clock Out (CLKO) pin that provides a buffered oscillator signal. The first thing you should check is that the oscillator is running at 16 MHz to within ±0.25% to meet the USB specifications. The capacitor values on the schematic work for the crystal shown; but if you use a different crystal, you may need to adjust C3 and C4.
I included an LED indicator on the PCB as a handy debugging aid. I’m able to quickly confirm that a block of code has executed (or not) by turning on the LED. When it is not used for debugging, I use the LED to indicate that Windows has recognized the device. Note that the LED must be switched off in Suspend mode to conserve power. I brought out most of the microcontroller port pins to the PCB edge so that I could use my device to develop USB gadgets. I also included two buttons: Reset and HWB to boot in DFU mode.
as well as a silicon oscillator, eliminating the need for an external crystal. In bus-powered mode, the chip draws all the power it needs from the USB port. Virtual communication port (VCP) drivers are available for download from Silicon Lab’s website. The downside of the CP2102 is that its 5-mm, leadless, 28-pin MLP package is tiny to work with, but I managed to hand-solder it to a carrier board without too much difficulty. No interface hardware is required to connect the bridge chip to the AT90USB162. Nothing could be simpler!
SERIAL PORT
SOFTWARE CONSIDERATIONS
A key aspect of this project was to give myself the ability to send diagnostic data from the microcontroller to my laptop using a serial port. On the laptop, the diagnostic information is displayed using HyperTerminal. However, my laptop didn’t come with a serial port, as this type of port has all but disappeared from laptop computers. Fortunately, “bridge” chips allow any USB port to emulate a serial port. The emulated port looks just like a standard COM port to HyperTerminal. I chose a Silicon Labs CP2102 chip for this purpose. This chip contains a USB and serial port module,
I chose to use AVR Assembler for this project because I wanted to use Hauk’s assembler code as a starting point. The AT90USB162 serial interface engine (SIE) takes care of all of the low-level USB interface requirements such as bit stuffing and error detection. The assembler code only has to manage the USB transactions. Only two interrupt handlers manage the USB function: USB_Device and USB_Endpoint. The Device interrupt handler either configures the USB interface (Reset), places the device in low-power mode (Suspend), or wakes the device from Suspend
Listing 2—Simple polling is used to send a byte over the serial port. The AT90US162 takes care of telling the host to wait if the device is busy. ;************************************************************* ; USART - Transmit usartByte ;************************************************************* Usart_TxChr: push temp ; preserve temp UTxC_Wait: lds temp,UCSR1A sbrs temp,UDRE1 ; wait for empty data register rjmp UTxC_Wait sts UDR1,usartByte ; send byte pop temp ; restore temp ret
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112015_Dzioba_Layout 1 11/8/2010 12:03 PM Page 37
worldmags
DFU VS. ISP
bootloader object code is available on Atmel’s website and can be reinstalled using the ISP.
USB INTERFACE You can download the USB specifications from the www.usb.org website, although you may find the specifications a confusing place to begin. I highly recommend Jan Axelson’s book USB Complete (Lakeview Research). It explains USB in detail, but I will summarize a few of the USB basics as they apply to the AT90USB162. It is useful to keep in mind that the device can only respond to host requests; it can’t initiate a transfer itself. USB communication occurs between a host and a device through endpoints. An endpoint in the AT90USB162 is a block of dual-port RAM (DPRAM) that is accessed on a first-in-first-out (FIFO) basis. Endpoints are numbered starting at zero and the AT90USB162 allows for up to five endpoints to be defined (i.e., 0 through 4). The total amount of DPRAM available in the AT90USB162 is 176 bytes and can be allocated to endpoints in 8-byte blocks from 8 to 64 bytes. Endpoint0 is a special endpoint called the “control” endpoint. It is a bidirectional buffer that is used by the
To get firmware into the AT90USB162, you can use the in-system programming (ISP) or the DFU bootloader. To use the DFU loader, you must install Atmel’s FLIP program and drivers on the host PC before connecting your device. This free software is available on Atmel’s webPhoto 2—The setup packets sent from the host are dissite. To boot in DFU played using HyperTerminal. The “S” next to a packet mode, press and hold means the device responded with a Stall. There is some HWB, press and release repetition in the requests from the host, but this is normal. Reset, and then release HWB. This sequence causes Windows to load the DFU driv(Wakeup). The Endpoint interrupt handler manages the USB transaction er, allowing you to program the microcontroller using the FLIP software. protocol. For serious development work, I decided to create a macro for each Device and Endpoint action to simpli- however, you will want to program the AVR using the ISP interface and fy the overall assembler coding. Each not the DFU facility. I found that the macro handles setting or clearing speDFU feature was excellent for updatcific USB register bits and is named ing firmware in a finished project, according to the function it performs. but it was not as convenAs an example, Listing 1 shows the ient as using Atmel’s macros used to initialize the Endpoints. The macro coding is contained AVRISPII programmer. I was used to the quick in include files so that they don’t edit-compile-load-test clutter the main source code. Overall, cycle because I’d used this approach makes the program easthe ISP on other AVR ier to read and understand. microcontroller projects, so I included an ISP DISPLAY ROUTINES interface in this project. I send diagnostic information to the Also note that DFU host PC via the serial port using a set mode does not allow of serial port macros, summarized in microcontroller fuse setTable 1. I made the serial port hantings to be changed; only dling as simple as possible. Listing 2 the ISP or JTAG proshows how I implemented polling grammer can do that. rather than interrupts to manage the When I used the ISP USART. The serial port macros are interface with the AVR used inside Interrupt Service RouStudio development tines (ISRs) where it is normally not environment, I ended up good practice to put logic that can erasing the flash memory delay a speedy return from an interand along with it the rupt. However, the AT90USB162 SIE Photo 3—When the device wakes up from Suspend mode, preprogrammed DFU takes care of letting the host know the host sends many of the original setup requests to the device. loader! Fortunately, the the device is temporarily unavailable www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
by sending “NAK” USB handshake packets while the device is busy, so this simple approach to managing the serial port works.
37
2112015_Dzioba_Layout 1 11/9/2010 12:59 PM Page 38
worldmags
a)
b)
Photo 4a—GenericHid, a free application from Lakeview Research, is ideal for testing the device. GenericHid shows 2 bytes it has sent to and received from the device using In/Out Reports, Feature Report, and In/Out endpoint transfers. b—The HyperTerminal session shows the device processing the USB requests that GenericHid generates.
December 2010 – Issue 245
host to configure the device. It can also be used to send and receive bytes of user-defined data. When the AT90USB162 is “attached” to the USB bus, it means that an internal 1.5-kΩ resistor is connected between the 3.3-V regulator and the D+ USB interface pin. This signals the USB hub that a full-speed device has connected to the bus and that the host should begin the device configuration sequence called “enumeration.” The first thing the hub does is issue a USB reset that causes the AT90USB162 to execute UD_Reset, which configures the endpoints and enables the endpoint interrupts. The first endpoint interrupt routine to be called is UE_Endpoint0. It reads the 8-byte control packet into general-purpose registers and takes a different setup action
38 worldmags
depending on the value in bRequest. I chose to implement just the subset of commands that are required to enumerate and operate a simple device. All other requests are “stalled,” which is the USB term describing the way in which the host is notified that the request can’t be fulfilled. Photo 2 shows an example of actual setup packets during the enumeration phase. The “S” next to a packet indicates that the device responded to the host request with a stall. An OK response for these particular requests. When the host signals the AT90USB162 to enter Suspend mode, the UD_Suspend interrupt routine is executed to disable the USB clock in order to cut power consumption. This routine also signals the program main loop to turn off the LED and enter CPU power-down mode. When the host comes out of standby, the UD_Wakeup interrupt routine is executed. This brings the CPU out of power-down mode and restarts the USB clock. Photo 3 shows the setup packets that the host sends to the AT90USB162 during wakeup from Suspend mode. One of these packets is a Set Configuration that turns the LED back on. To capture these packets, I had to move the USB-to-serial interface cable to a second laptop because my primary laptop could not receive serial data while resuming from standby. To test Suspend mode, I also found I had to disconnect the ISP from the device because the ISP forces a microcontroller reset when it wakes up from Suspend mode.
HID EXTENSIONS Photo 5—An oscilloscope image of the EP1_POLL pin shows that the host requests data from the IN endpoint every 8 ms with the Descriptor values used and my laptop’s particular USB hub.
Windows recognizes my device as a generic HID and automatically loads the driver for it. The HID specification extends the standard USB requests to include two additional requests: Get Report and Set Report. These enable the host to send and receive user-defined data CIRCUIT CELLAR®
•
www.circuitcellar.com
2112015_Dzioba_Layout 1 11/8/2010 12:03 PM Page 39
worldmags
from the device using Endpoint0. These requests are only intended for very-low-bandwidth data transfers. For high-volume data transfer, you need to use the IN and OUT Interrupt transfers. Interrupt transfers are not the same concept as the interrupt system in the AT90USB162. Interrupt endpoints have a polling interval (bInterval in the Endpoint Descriptor) that determines how often the host asks the IN endpoint for data. To send data to the host, the AT90USB162 writes bytes to the IN endpoint and expects the host to scoop them up. When the host has data ready to send to the device, an OUT Endpoint interrupt is generated and the AT90USB162 firmware can read the bytes sent by the host. The number of bytes to transfer is defined in the Report Descriptor, which is divided into three report types: Input, Output, and Feature Reports. The Input Report defines the data packet size for both the IN Endpoint and the HID Get Report command. The same is true for the OUT Endpoint and the HID Set Report command. The Feature Report is not associated with either an IN or an OUT endpoint. The wValueH byte in the Control packet indicates if the request is an In Report (0x01), Out Report (0x02), or Feature Report (0x03).
from the AT90USB162 over the Control endpoint or the IN endpoint. Sending data over the Control endpoint or the OUT endpoint is controlled by the GenericHid user interface. The microcontroller firmware sends back the 2 bytes it receives from the host to verify that everything is working. To use GenericHid, enter the VID and PID for this project (0x03EB and 0x21FF, respectively) and click the Find My Device button. The VID and PID values were
taken from an Atmel application note and are fine if you just want to experiment. You can hook your oscilloscope to the EP1_POLL pin to confirm that the host polls Endpoint1 periodically (see Photo 5). I noticed that my laptop’s hub actually polls Endpoint1 at 8-ms intervals and not 10 as specified in the descriptor bInterval. On closer investigation, I found that the type of hub in my laptop only looks at the most-significant bit of
The USB control packets and endpoint activity can be observed using HyperTerminal on your PC. The default settings for the serial port are 115,200 bps, 1 stop bit, no parity, no handshaking. Using HyperTerminal, you can watch the device enumeration sequence, HID Control transfers, and In and Out interrupt transfers. To test the device’s data-transfer capability, a free software application called GenericHid is available from Lakeview Research (see Photo 4). The Generic HID descriptor supplied with the project files is designed to match up with GenericHid. GenericHid sends 2 bytes to the AT90USB162 over the Control endpoint or the OUT endpoint. GenericHid then requests 2 bytes www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
TESTING
39
2112015_Dzioba_Layout 1 11/8/2010 12:03 PM Page 40
worldmags
recommend the www.fourwalledcubicle.com website where you will find hints and ideas for the AT90USB162. Meanwhile, you can use the serial port macros to probe further into the firmware to see what is going on; guidelines are provided in the source code. If you are like me and learn by tinkering, this is the ideal project for unlocking the mysteries of USB. I Richard Dzioba (
[email protected]) holds a degree in Computer Science from the University of Victoria, British Columbia. He works as an IT consultant and project manager with Project Strategies, Inc. Richard has been an electronics enthusiast since building his first Heathkit in 1968. When he isn’t dreaming up USB gadgets, he is playing guitar. Photo 6—This is my version of Lane Hauck’s Windows Volume Control. The low parts count makes for a very compact design. bInterval. There are various types of hubs and they don’t all work the same way.
PROJECT FILES To download the code, go to ftp://ftp.circuitcellar.com/ pub/Circuit_Cellar/2010/245.
SOURCES IN & OUT OF TROUBLE Once you get things up and running, you will probably want to try different types of descriptors. I have included a few different ones in the project files. The descriptors include a few hints on how to use them. Be forewarned: Windows does not facilitate trial-and-error descriptor development. The most troublesome for Windows is an incorrect descriptor-length calculation; for example, not accounting for the extra byte needed to pad descriptors that are an odd length. (The AVR Assembler organizes memory in words, not bytes.) This type of error will prevent the enumeration process from completing and may cause your PC to lock up. To fully recover from this type of error, you may need to delete the following keys in the Windows Registry (assuming you used the VID and PID shown):
December 2010 – Issue 245
HK_LM\System\CurrentControlSet\Enum\HID\Vid_03eb&Pid_21ff HK_LM\System\CurrentControlSet\Enum\USB\Vid_03eb&Pid_21ff
40 worldmags
Another potential problem is switching descriptor files but keeping the same VID and PID codes. For example, if you want to experiment with a keyboard descriptor but you use the same VID and PID as a media-control HID device, Windows won’t automatically uninstall the media control device driver for you. I found that I had to first manually uninstall whatever driver I was using with Windows Device Manager before I attempted to reuse the VID and PID with a different descriptor. Recovery from a registry corruption like this can be resolved by deleting the two registry keys above, and it requires the PC to be rebooted as well. Your best bet is to use a different VID and PID combination for each descriptor type.
PROJECT IDEAS For further experimentation, I have included descriptors for a Windows media control device, a simple keyboard, and a serial port device. For example, Photo 6 shows my version of Hauck’s Windows Volume Control design using the AT90USB162 and the Media Controls descriptor. I
AT90USB82/162 Microcontroller and DFU bootloader Atmel Corp | www.atmel.com Generic HID Lakeview Research | www.lvr.com CP2102 USB-to-Serial Bridge Silicon Laboratories | www.silabs.com
NEED-TO-KNOW INFO Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Richard Dzioba’s Issue 245 article, the Circuit Cellar editorial staff highly recommends the following content: — USB in Embedded Design (Part 1) The Undeniable Benefits by Jeff Bachiochi Circuit Cellar 165, 2006 How much do you really know about USB? This column is a great place to start educating yourself about the “embedded-tech-related” basics. Topics: USB, Hub, Interface, Enumeration, HIDmaker — Windows Volume Control by Lane Hauck Circuit Cellar 193, 2006 Lane’s design enables him to control the volume of applications running in Windows without having to use his mouse. The system plugs into his PC’s USB port. Topics: USB, Volume Control, HID, SPI — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
5_Layout 1 10/27/2010 12:50 PM Page 1
worldmags
EMBRACE INNOVATION AND OPPORTUNITY.
Put your business at the center of the future. See 20,000 new products and meet with 26,000 key decision makers—at every point on the supply chain—all in one place. Register with priority code M1 by 5 p.m. EST December 31 to save $100 off the on-site registration fee. Exhibitors: Reach an international audience in one trip. Reserve space at
[email protected]. Register Now at CESweb.org | January 6–9, 201 1 | Las Vegas, Nevada
worldmags
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 42
worldmags
A
BOVE THE GROUND PLANE
by Ed Nisley (USA)
Real-Life VHF Data Transmission Understanding and Using the APRS You can develop hardware applications that automatically report their positions to the Automatic Packet Reporting System (APRS) network, which is a global digital network linking amateur radio stations through RF to the Internet. This article provides useful tips and covers topics ranging from RF propagation to position tracking.
December 2010 – Issue 245
G
42 worldmags
PS-enabled devices have become using amateur radios. ubiquitous over the last few years, to In this column I’ll review my latest bike the extent that essentially every new wireless interface hardware, then describe how RF electronic gadget knows its current location. propagation, packet collisions, and topograAmateur radio operators have had that capaphy affect what begins as a pristine digital bility since the early 1990s, although assempacket. You’ll see that many of the assumpbling the hardware and using the RF network tions applicable to wired networks lead you required considerable technical expertise. The astray in the world of RF networking. Automatic Packet Reporting System (APRS) is now a global digital network linking amateur SOME AUDIO CIRCUITRY radio stations through RF to an Internet backPhoto 1 shows how the interface attached bone, with both commercial and Open Source to the radio. The CNC-machined acrylic case products that simplify the whole process. I described a radio interface in my October 2008 column that combined digital GPS position data with analog voice signals from a microphone, transmitting the result through an amateur radio transceiver on my recumbent bicycle. That hardware gave my bike the ability to automatically report its posiPhoto 1—The acrylic plastic case attaches to the radio in place of a standard tion to the APRS network battery pack and powers the radio through its battery contacts. The output audio while I used the radio for goes to the radio’s mic input for transmission, while the radio’s external speaker normal voice communicajack sends received audio to the interface. The GPS receiver terminates in the DB-9F connector. tion with other riders CIRCUIT CELLAR®
•
www.circuitcellar.com
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 43
worldmags
Photo 2—The Byonics TinyTrack3+ board on the left converts GPS position data into FSK audio signals. My circuit combines that data with voice audio from an electret mic to drive the radio’s external mic input.
duplicates the tabs and slots found on an ICOM BP-170 battery pack and mounts securely on the back of the radio. Because the case doesn’t have
nearly enough surface area for all the connectors, I routed pigtail leads to the external battery, PTT switch, helmet, and radio jacks. Two flat contacts
Figure 1—The most significant changes in the last two years include deriving Vcc/2 directly from the battery, adding an attenuator on the TinyTrak3+ audio output, and reducing the mic gain. I now use USB cables for the mic and earbud audio to the helmet, taking advantage of their low cost and non-latching connectors. www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
n
on the bottom provide power directly to the radio. The GPS receiver plugs into the DB-9M connector on the Byonics TinyTrak3+ GPS encoder board visible through the top of the case. That board converts the serial GPS data into an audio frequency-shift keyed (AFSK) signal that encodes APRS digital packets into voice-band tones. Photo 2 shows the underside of the TT3+ board and the top of my interface PCB. I soldered the cables directly to the circuit board, because there’s no space in there for more connectors. The arched opening visible in the upper left of the top case half clamps firmly over the cables, anchoring them to the bottom case half for strain relief. The schematic in Figure 1 shows the circuitry in the interface board.
43
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 44
December 2010 – Issue 245
worldmags
44 worldmags
My October 2008 column described the original interface’s design and operation in considerable detail, so I’ll quickly cover two years of tweaks required by on-the-bike experience. An electret mic capsule converts acoustic energy into an electrical signal, which is then amplified by the op amp inside the MAX4467 chip. The gain depends on the mic’s acoustic sensitivity; the higher gain I used in the previous design worked well with a different set of mic capsules. A more recent batch produced overwhelming wind noise; reducing the gain to 1, using a larger foam windscreen, and putting the mic very close to my cheek solved that problem. A 10-dB attenuator on the TT3+ audio output provides a better match to the ICOM IC-Z1A mic input’s expected level. The maximum output from the TT3+ was far too high, putting its output trimpot near the low end of its range. The attenuator allows a trimpot setting near midrange, making it far less sensitive to vibration. The VCC/2 supply now comes directly from the battery input, rather than the TT3+ internal 5 V regulator, to reduce digital noise injected into the voice signal. I’m using the TT3+ outside of its usual non-voice environment, so every decibel of noise suppression helps. I tried to use an optoisolated MOSFET power relay to switch the supply voltage, but the IC1A mic supply doesn’t provide quite enough current to drive the relay’s LED. The failure was frustratingly temperature-sensitive: the interface worked fine on the bench and failed after a few hours of riding in the summer sun. Although this doesn’t appear on the schematic, I now use a 9-V 5.4Ah Li-ion battery intended for DVD players, instead of homebrew eightcell NiMH packs. The new battery provides much higher capacity, albeit at a slightly lower voltage. The 0.6 V reduction cuts the maximum radio output from 5 W to about 4 W, about –1 dB, which seems to have no effect on the range. I’ve built three of these boards, each with slight changes, over the
2010-08-16 09:41:34 EDT: KE4ZNU-9>APT311,WIDE1-1,WIDE2-1,qAR,K2MHV-6:>TinyTrak3 v1.1 2010-08-16 09:45:07 EDT: KE4ZNU-9>T1SY5R,K1DF-15*,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 09:48:07 EDT: KE4ZNU-9>T1SY5R,K1DF-15*,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 09:48:08 EDT: KE4ZNU-9>APT311,K1DF-15*,WIDE2-1,qAR,K2MHV-6:>Ed -- Bike Mobile PL100 2010-08-16 09:51:06 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 09:54:06 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 09:57:07 EDT: KE4ZNU-9>T1SY5R,K1DF-15*,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 10:00:06 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 10:03:06 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 10:09:06 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u} 2010-08-16 10:15:07 EDT: KE4ZNU-9>APT311,WIDE1-1,WIDE2-1,qAR,K2MHV-6:>Ed -- Bike Mobile PL100 2010-08-16 10:18:08 EDT: KE4ZNU-9>T1SY5R,WIDE1-1,WIDE2-1,qAR,K2MHV-6:`ePFl!Zb/"4u}
Figure 2—APRS packets include the source callsign, the path from transmitter to Internet, and the compressed GPS coordinates. The TinyTrak3+ is sending packets every 180 seconds, but some packets never reach the receiver. The bike remained stationary in my driveway, as shown by the unchanging position data at the end of each packet.
last two years. The mic and speaker jacks on the radios will probably fail in the next year or two and, having already replaced the jacks once, I plan to rebuild new interface boards for new radios.
PASSING PACKETS The amateur radio packet network is based on the AX.25 protocol that supports both datagram and connectionless modes. APRS depends on connectionless packets, much like UDP, that are not guaranteed to reach their destination. Unlike UDP packets traversing your pristine wired Internet connection, however,
APRS packets frequently vanish into thin air: they are, after all, traversing an RF link. Figure 2 shows the APRS-IS database records from my bike over the course of half an hour, with the TT3+ sending packets (“beaconing”) every 180 seconds. Each record has a fixed format, with specific punctuation separating the fields: timestamp: sender>destination, comma-separated path: packet data The references provide far more
Figure 3—A ride across Philadelphia shows the effect of packet collisions. Despite the nearby NJ2BB-15 digipeater and others only slightly more distant, more than half of my position packets vanished. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 45
Figure 4—Given low RF traffic, a nearby digipeater, and a GPS tracker set to beacon on every turn, the APRS data points clearly mark my route. details about the network and APRSIS than I will cover here and, indeed, the packet network has far more capabilities than APRS requires. The database path field contains every RF station that handled the packet until it reached the Internet. Those stations, known as digipeaters (digital repeaters), generally have better antennas, so they can receive a relatively weak signal from a mobile station, and more power, so they can retransmit packets over a much greater distance to the next digipeater or Internet gateway (IGate). For example, the packet in the first line of Figure 2 started from my bike (KE4ZNU-9) and was directly received by the K2MHV-6 IGate in Poughkeepsie. The K2DF-15 digipeater high atop Mt. Beacon received the second packet, then retransmitted it to K2MHV-6. The TinyTrak3+ board sends an ID string (TinyTrak3 v1.1) during its power-up initialization; that packet arrived at 09:41:24. The next database record, a position packet received at 09:45:07. shows the preceding packet at 09:42 is missing. Similarly, the packets at 10:06 and 10:12 got lost along the way. The TT3+ also sends a status string (Ed - Bike Mobile PL100) after every third position report, but the 10:00 status wasn’t received. Those missing packets probably www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
were due to network effects. collided with packets sent by other Of course, I didn’t build the intertransmitters at the same time face to determine the location of my because, unlike wired Ethernet networks, RF networks generally cannot driveway. Figure 3 shows my APRS track during a ride across downtown detect and avoid collisions. All RF Philadelphia, a dense urban area with networks suffer from what’s called plenty of APRS activity and digithe hidden transmitter problem: a peaters. Starting from the middle of receiver (the digipeater) may be able the Benjamin Franklin bridge at to hear two stations that cannot hear 10:13, the next five beacons occurred each the other’s transmissions. during 33 minutes. That’s enough My radio uses the standard APRS time for about a dozen three-minute Voice Alert tone-squelch settings beacons, so, obviously, you must not and will remain silent unless the depend on receiving any particular received audio includes a 100-Hz packet! tone, which is generally not present My path on the east side of the on APRS transmissions. As a result, Delaware River has far more beacons, neither I nor the TT3+ will hear but that section required far more most of the data traffic. That’s easy time over a much shorter distance. on my ears, but the TT3+ may transWe had an organizational meeting, mit simultaneously with another listened to several speeches, and APRS station it cannot detect. Most admired the spectacle of 350 riders simple APRS GPS stations do not have a receiver and can’t hear anything anyway: my station isn’t all that unusual. That may explain the second packet in Figure 2: while the K2MHV-6 IGate was busy handling a packet it received directly over the air from another local station, the K2DF-15 digipeater caught my packet and retransmitted it a fraction of a second later, when K2MHV-6 was available. The hidden transmitter problem applies to all stations, so K2DF-15 simply didn’t receive the other packet. I parked my bike in the driveway during the entire test, as shown by the unchanging GPS position data at the end of each packet. As a result, all the Figure 5—These Power-Height-Gain circles show the coverage packets had nearly the area of the digipeaters and IGates that recorded my route same strength at the from White Haven through the Lehigh Gorge State Park to Jim digipeaters and most Thorpe, then to Allentown. VHF signals do not deal well with gorges and rugged terrain! of the differences
December 2010 – Issue 245
worldmags
45
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 46
worldmags
hauling their bikes up two long flights of steel stairs from the street to the bridge walkway. In case you were wondering, a long-wheelbase recumbent does not handle stairs well at all. Figure 4 shows a half-hour section of a ride in a suburban area with very little APRS traffic and the K2DLL-12 digipeater within line-of-sight. In addition, I reconfigured the TT3+ to operate in SmartBeacon mode, transmitting packets about every half mile and whenever the bike changes direction. The difference is striking: essentially all of the packets transmitted during the 32 minutes between the first and last beacon reached the APRS-IS database. As nearly as I can tell, 43 packets arrived and at most four were lost, giving a very accurate record of my progress along the convoluted route. The amateur radio packet network depends on many digipeaters, each with a relatively small coverage area, that relay packets to their destinations. One of my packets on that ride went through K2DLL-2 (located about 12 miles west of K2DLL-12), KA2QYE-10 (40 miles south along the Hudson River), and then to WA2MHV-6 (another 50 miles downriver in Poughkeepsie). Despite starting more than 100 miles away, that packet reached the same IGate most of my around-home rides use! The amateur packet network also offers datagram connections with guaranteed delivery, but there’s no magic involved: every data packet requires an acknowledgment and every missing packet triggers a retransmission and another acknowledgment. That additional traffic can quickly clog the RF link with collisions producing even more retransmissions. Eventually, the network link collapses and no packets reach their destinations. APRS sends a single connectionless packet and depends on redundant paths with many digipeaters and good network management to get through. It works surprisingly well under most conditions, while not attempting to achieve the impossible.
December 2010 – Issue 245
RF SIGNAL COVERAGE
46 worldmags
Over the course of two days I rode from White Haven, in the upper-left corner of Figure 5, south through the Lehigh Gorge State Park to Jim Thorpe, then southeast to Allentown in the lower right corner. The APRS network recorded only the last third of that trip, as shown by the red track of my route. The coverage area for a VHF RF transmitter depends mostly on its RF power output, the height of the antenna above the surrounding terrain, and the antenna gain pattern. Given those numbers, you can compute what’s called the PHG (Power, Height, Gain) Circle around the transmitter, showing where a similarly equipped receiver can probably hear the signal. Because APRS beacons originate from relatively lowpower mobile transmitters using short antennas in poor locations, a rule of thumb says that the digipeater can reliably receive packets within a radius about half that of its computed PHG circle. Figure 5 shows sections of two
half-diameter PHG Circles; the purple “circle” for W3CE-3 is actually a cardioid indicating that its antenna has an asymmetric pattern directed southward, with a null toward the mountains to the north. Actually, those circles are a significant overestimate for a bicycle-mounted APRS transmitter. A typical automobile APRS radio outputs 50 W through an antenna above a vehicle roof serving as a good ground plane. My transmitter is 11 dB below that level, with an antenna mounted to the bike’s seat frame. W3CE-3 digipeated the packets from my bike when I emerged from the deep northern valleys shielding me from its antenna. However, the southern section took three hours, indicating that reception remained spotty, at best: over 50 beacons vanished between the first and last spots shown in Figure 5. Even though several digipeaters cover the area from White Haven to Allentown, none can receive a weak VHF signal from the bottom of a valley. Indeed, over the next two days I rode from Allentown to Easton, then south along the Delaware River Valley to Trenton, while remaining hidden from the APRS network for the entire distance. When I returned home, however, I popped back on the map!
CONTACT RELEASE Unlike commercial GPS services, essentially everything in the amateur radio APRS network is open for tinkering and improvement. Your contributions will be welcome! In reference to some recent columns, a reader chastised me for using parts bought through eBay, claiming that a published project should use components with part numbers from “reliable vendors.” That would certainly be a valid complaint if I were producing finished products for assembly by untrained readers who simply solder components from a kit into a prefabricated PCB. However, that’s not what Circuit Cellar and this column have ever provided. The hardware and firmware you find here exist only to illustrate engineering concepts: they’re not simple assembly projects. I expect you to work through and verify the equations; check the references for more details; download the original schematics, PCB layouts, and firmware; modify them to suit your needs; then create a suitable gizmo that will solve your problems. At the end of that process, you will have learned far more than by simply buying some parts and building a kit. Fair enough? I Ed Nisley is an EE and author in Poughkeepsie, NY. Contact him at
[email protected] with “Circuit Cellar” in the subject to avoid spam filters.
PROJECT FILES To download the schematic and project files, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2010/245.
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112004_nisley_Layout 1 11/3/2010 3:36 PM Page 47
worldmags
NEED-TO-KNOW INFO
RESOURCES APRS-IS Internet database, www.aprs-is.net. Automatic Packet Reporting System, www.aprs.org. Automatic Packet Reporting System, Wikipedia, http://en. wikipedia.org/wiki/Automatic_Packet_Reporting_System. AX.25 Protocol, Wikipedia, http://en.wikipedia.org/wiki/AX.25. S. Bragg, “SmartBeaconing,” 2007, www.hamhud.net/hh2/smartbeacon.html. Lehigh Valley Gorge State Park, www.dcnr.state.pa.us/ stateparks/parks/lehighgorge.aspx. Maps, Tracking, and PHG Circles, http://aprs.fi. E. Nisley, “HT Audio, GPS for APRS, and What Works,” Circuit Cellar 219, 2008. NJ2BB Amateur Radio Station on BB62 Battleship New Jersey, http://nj2bb.org/.
SOURCES TinyTrak3+ tracker and GPS receivers Byonics | www.byonics.com Amateur radio products ICOM America | http://icomamerica.com/en/amateur/ default.aspx
Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Ed Nisley’s Issue 245 article, the Circuit Cellar editorial staff highly recommends the following content: — NimbleSig by Thomas Alldread Circuit Cellar 208, 2007 The NimbleSig is a versatile DDS RF signal generator. It provides a frequency-agile RF output signal source with 1-Hz step resolution. Topics: RF, DDS, Signal Generator, Resolution — Signal Generation Solution by Neal Martini Circuit Cellar 182, 2005 Tired of going to a local university lab to use a signal generator, Neal designed his own. Topics: RF, Signal Generator, VSWR, Impedance Matching — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
Save Sa ve 10% at at
Shop now now using promo pr omo code
HOLIDAY10 HOLIDA HOLID AY10 a att c checkout. heckout.
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
CC-Webshop.com! CC-We CC-W ebshop.com!
47
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
2112005_lacoste_Layout 1 11/9/2010 1:01 PM Page 50
worldmags
T
HE DARKER SIDE
by Robert Lacoste (France)
Parasitic Components When Capacitors Behave Like Inductors Every engineer understands the importance of capacitors. But what happens when a capacitor starts behaving like an inductor? The experiments presented in this article show that capacitors aren’t always as simple as they seem.
H
December 2010 – Issue 245
ello, folks. In my last column, I talked about frequency-domain test equipment. In particular, I presented a vectorial network analyzer, or VNA for short. I said that such equipment is useful but rather expensive. This is true and false. It’s true if you buy it from one of the top suppliers (e.g., Agilent or Rohde & Schwarz) or even on the second-hand market. But it could be false if you build it yourself. A fellow engineer working with me
50 worldmags
at Alciom, Yannick Avelino, built such a VNA (starting from the VNWA design published by Dr. Thomas C Baier). Its performance is really impressive! We played with it together and bench-tested it by measuring simple capacitors, as one of a VNA’s applications is impedance measurement. As is often the case, the measurements seemed strange at first. Interestingly, the second time around they turned out to be exact.
Figure 1—This simple simulation, done with the QUCS Simulator, shows the behavior of a perfect capacitor. The current INET and voltage UNET across the resistors are measured with virtual meters, and then the capacitor impedance is calculated as Z = U/I. As you can see, the plots on the right show the impedance magnitude (top) and phase (bottom) when the frequency is increased from 1 to 20 MHz. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112005_lacoste_Layout 1 11/8/2010 3:42 PM Page 51
worldmags
In this article, I’ll share the experiments with you. Plus, Yannick describes his VNA design at the end of the article. Take care, you may never look at a capacitor the same way again!
CAPACITORS You know what a capacitor is, right? If you take a capacitor and apply an AC signal to its terminals, there will be a current circulating in it. This current will be higher and higher when the frequency increases, or when the capacitor value increases, as the impedance of a capacitor is Z = 1/(2πfC), where f is the signal frequency in hertz and C is the capacitance in farads. Lastly, the phase of the current is 90° behind the voltage. I made a small simulation of a
Photo 1—Here is the first experiment. I soldered a standard 100-nF capacitor between a 50microstrip track and the ground plane, leaving wires 1 cm in length. www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
perfect capacitor using the freeware QUCS simulator, and the result is shown in Figure 1. As expected, the impedance is lower and lower when the frequency gets higher, and the phase stays at a constant –1.57 which is –90° = –π/2 rad. Simple, isn’t it? Let’s review the test. In order to have a clean measurement, I used a PCB from an old RF project modified to provide a simple and clean way to connect a capacitor to a coaxial SMA connector. The connector’s central pin was connected to a pad through a 50-Ω microstrip wire—meaning, with a 50-Ω controlled impedance. (Refer to my article, “Microstrip Techniques,” Circuit
Figure 3—This QUCS simulation explains the behavior shown in Figure 2. Each 1-cm wire is equivalent to an inductor, which is here assumed to be 6 nH in total. The circuit is then an LC series resonant circuit, which appears to self-resonate around 6 MHz.
December 2010 – Issue 245
Figure 2—This is the result of an impedance measurement from the test setup shown in Photo 1. The top curve shows the measured capacitance from 100 kHz to 500 MHz. The bottom plot shows the equivalent serial inductance. The capacitor is no longer a capacitor as soon as the frequency is above 6 MHz!
Cellar 223, 2009.) The capacitor to be tested could then be soldered between the pad and the bottom face ground plane through a via. I first soldered a standard 100-nF ceramic capacitor, keeping 1-cm-long wires so I could reuse the capacitor if needed (see Photo 1). A note of caution: Any VNA needs a proper calibration before measurement, especially for impedance measurements. This calibration is usually done using the so-called SOLT method. The output of the analyzer is first connected to a short-circuit (S) that’s as perfect as possible. Next, it’s connected to a perfect open circuit (O), and then to a reference 50-Ω load (L). Lastly, the VNA’s output and input are connected together through (T) a reference link. This last step is required only when transmission measurements are needed, which is not the case for this article. The analyzer can then calculate the calibration factors and correct most of its measurement errors, as long as the references are good. It’s important to perform this calibration with not only the analyzer, but also with all interconnecting cables and test setups to cancel their influence and measure the actual component and only this component. I first soldered an SMT 0-Ω resistor on the PCB in place of the capacitor and used it as a “short” reference. A test without any component soldered on the pad gave the “open,” while a 49.9-Ω SMT resistor provided a reasonable reference “load.” Then
51
2112005_lacoste_Layout 1 11/9/2010 1:09 PM Page 52
worldmags
December 2010 – Issue 245
Photo 2—Another test, done with drastically shortened wires, should provide better results.
52 worldmags
a reasonable reference “load.” Then the capacitor to be tested could be soldered in place. The measurement is performed in Reflection mode: the analyzer sends to the capacitor a sine wave of varying frequency and measures the amplitude and phase of the signal reflected back by the capacitor to the source. A calculation allows it to calculate the capacitor’s impedance both in module and phase. The measured impedance with this first test setup is shown in Figure 2. The capacitance is effectively measured close to 100 nF, but only for very low frequencies. There is a strange bump in capacitance at about 6 MHz; and for frequencies above this limit, the capacitor behaves exactly as an inductor—more precisely, as an 8-nH inductor! What’s happening? As you know, the legs of the capacitor were kept quite long, and a straight wire acts as an inductance. Back in 1908, E. B. Rosa gave a formula to calculate this inductance: Lsw (in nH) = 2 L (ln(2L/r) – 0.75), where L is the wire length and r is the wire radius (both in centimeters). When the frequency is high enough, the formula is still the same, but the 0.75 parameter slowly increases up to 1. Do the math. With a 1-cm wire and a diameter of 0.6 mm, you get an inductance of 5 nH. You should multiply it by two because there are two legs and that gives 10 nH, which is close to the measured 8 nH. But why does the capacitor’s behavior change at a frequency of 6 MHz? Simply because the 100-nF capacitor and this 10-nH parasitic inductor
Figure 4—Real capacitors have not only a parasitic inductance, but also a parasitic serial resistance (their ESR). Taking it into account in the simulator gives the same behavior as shown in Figure 3 but with smooth curves. makes a serial LC resonant network. Such a network is equivalent to a capacitor below the resonance frequency. It’s equivalent to an inductor above, as simulated in Figure 3, or more exactly as an RLC network if you take into account the capacitor’s ESR (see Figure 4). The resonant frequency of such a network is calculated as the inverse of 2π times the square root of L × C: F=
1 2π LC
When C = 100 nF and L = 8 nH, you get 5.6 MHz, which is close to 6 MHz, isn’t it? So, the strange behavior we observed was normal. Conclusion: Never use a 100-nF capacitor with 1-
cm-long legs if you are interested in a frequency in the megahertz range or higher! How do you increase the resonant frequency and use a capacitor with signals far higher than 5 MHz? Look at the previous formula. There are only two solutions: decrease L or decrease C. Let’s start with L. I soldered the same 100-nF capacitor with short wires (see Photo 2). The result of the measurement is shown in Figure 5. It’s far better, with an inductance in high frequencies reduced from 8 to 2 nH, but this only doubled the resonance frequency, which is now 12 MHz. These 2 nH would correspond to twice the inductance of a 3-mm straight wire, which doesn’t seem unrealistic when
Figure 5—The impedance of the 100-nF capacitor with shorter wires still shows a resonance, but now at 12 MHz, which is two times higher than previously determined. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112005_lacoste_Layout 1 11/8/2010 3:42 PM Page 53
worldmags
Photo 3—The next test, still with a 100-nF capacitor, is done with a ceramic surface-mounted 0603 capacitor. The parasitic inductance is drastically reduced.
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
Figure 6—The measurement of the SMT 100-nF capacitor no longer shows a resonance; however, its measured value decreases as frequency increases. At 30 MHz, its value is only a little more than 50 nF. Such a capacitor is then usable up to 30 to 50 MHz depending on the application.
CAPACITOR CLARITY In this article, I covered only basic experiments, but I hope I convinced you that capacitors may not always be as friendly as they look. Have you ever seen schematics or reference
designs with several capacitors in parallel? For example, have you seen 1 µF plus 100 nF plus 100 pF all in parallel on a power supply rail? Have you ever been tempted to replace them all with 2.2 µF? Now you
December 2010 – Issue 245
short wires as well as the internal conductors of the capacitor. To go even higher in frequency, you must avoid all wires, which means using surface-mounted components (SMT). I replaced the capacitor with a 0603 100-nF ceramic SMT capacitor (see Photo 3), and this time the measurement didn’t show any resonance up to at least 500 MHz (see Figure 6). However, the measured capacitance quickly decreased, from 100 to 50 nF at 30 MHz and a mere 4 nF at 160 MHz. Take the last measurement carefully because measurement and calibration errors can be really significant here. In particular, it’s possible there’s a resonance below 500 MHz, but it’s hidden in the calibration errors (as the reference short was a 0603 0-Ω resistor, which also has a parasitic inductance close to the parasitic inductance of a 0603 capacitor. Nevertheless, you can see that a 100-nF 0603 SMT capacitor like mine is at least usable up to 30 or 50 MHz as long as a precise value is not needed. How do I go even further? By using smaller capacitor values, which increase the resonance frequency. Figure 7 shows a standard 100-pF 0603 capacitor. Its capacitance stays close to 100 pF up to 500 MHz and probably far higher. For microwave designs, you can even find specialized SMT capacitors from suppliers like American Technical Ceramics (ATC) with guaranteed self-resonance above 10 GHz and higher, but only with very small values in the picofarad range.
53
2112005_lacoste_Layout 1 11/8/2010 3:42 PM Page 54
worldmags
understand why it would be a bad idea. The 1 µF is good at low frequencies, but it will inevitably have a resonance below some megahertz. For high frequencies, only the 100 pF will supply some filtering, as long as it is SMT and very close to the noise source. Please refer to the Sidebar titled “Vector Network Analyzer Design” in which Yannick Avelino presents his VNWA-based vectorial network analyzer (see Photo 1 sidebar). It’s a clever way to get a VNA for a fraction of the cost, as long as you are working on passive systems that will accept the unusual test signals generated by the ultra-low-cost VNWA architecture. Capacitors may be on the darker side, but you now know how to switch the light on! Good luck. I
Figure 7—This is the measurement of a standard 100-pF SMT capacitor in a 0603 package. The top red curve shows that its measured value is 104 pF in low frequencies. It is still 90 pF at 500 MHz. However, its quality factor (purple) is lower and lower. Forgive the spurious spikes, which are measurement artifacts.
Robert Lacoste lives near Paris, France. He has 20 years of experience working on embedded systems, analog designs, and wireless telecommunications. He has won prizes in more than 15 international design contests. In 2003, Robert started a consulting company, ALCIOM, to share his passion for innovative mixed-signal designs. You can reach him at
[email protected]. Don’t forget to write “Darker Side” in the subject line to bypass his spam filter.
PROJECT FILES To download the schematic and project files, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2010/245.
RESOURCES American Technical Ceramics, “The RF Capacitor Handbook,” www.atceramics.com.
December 2010 – Issue 245
T. C. Baier, “A Small, Simple, USB-Powered Vector Network Analyzer Covering 1 kHz to 1.3 GHz,” QEX, http://sdr-kits.net/DG8SAQ/VNWA/Baier_ VNWA2_QEX.pdf.
54 worldmags
E. B. Rosa, “The Self and Mutual Inductances of Linear Conductors,” Bulletin of the Bureau of Standards, Volume 4, Number 2, 1908, www.g3ynh.inf/zdocs/ refs/NBS/Rosa1908.pdf. Referenced by T. Healy, www.ee.scu.edu/eefac/healy/indwire.html.
SOURCES QUCS Simulator SourceForge.net | http://qucs.sourceforge.net
NEED-TO-KNOW INFO Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Robert Lacoste’s Issue 245 article, the Circuit Cellar editorial staff highly recommends the following content: — Accurate Capacitance Meter by Alexander Popov, Jordan Popov, & Peter Popov Circuit Cellar 179, 2005 There’s no need to shell out big bucks for a reliable capacitance meter. Peter, Alexander, and Jordan joined forces to design a comparable capacitance meter around a CY8C27443 MCU. Topics: Capacitance Meter, DC, Current Source, Comparators, PSoC, UART — RF Attenuation Resistors at RF by Ed Nisley Circuit Cellar 179, 2005 The tracking generator on Ed’s spectrum analyzer produces RF at levels too high for receivers. He built an attenuator so he could study his radio’s behavior. But like capacitors, resistors can behave in unexpected ways at high frequencies. In this article, Ed studies signal levels and takes a closer look at resistors at RF. Topics: Attenuation, RF, Resistors, Capacitors — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
2112005_lacoste_Layout 1 11/8/2010 3:42 PM Page 55
worldmags
Vector Network Analyzer Design
think that we should first review Dr. Baier’s VNWA.
by Yannick Avelino (France)
CORE SYSTEM First, as with every VNA, you must have both transmission and reflection measurement capabilities. This is achieved using a simple SWR bridge formed by 50-Ω resistors at the TX port. Next, in order to make RF measurements, an RF source is obviously needed. Dr. Baier’s brilliant idea: the RF source is a standard Analog Devices AD9859 DDS chip. The output of the DDS is unfiltered. If you’re a regular reader of Robert Lacoste’s “The Darker Side” column, you’re probably frowning. And you’re right! This deserves some explanation. With the affordable AD9859, the fundamental frequency can’t be higher than few hundred megahertz. But, as Robert explained in his 2008 article titled “Direct Digital Synthesis 101” (Circuit Cellar 217), the output of a DDS generator is a DAC. Even a perfect digital sine signal applied to a DAC does not provide a pure analog sine signal. It’s a succession of steps that match the sine curve.
The vector network analyzer (VNA) used for this column is a homemade device (see Photo 1 sidebar). In fact, it’s nothing more than my implementation of the excellent Dr. Thomas C. Baier’s VNWA (see Figure 1a and Figure 1b sidebar). This amazing device (originally published in the ARRL’s QEX and now sold as a kit) offers accurate results up to 500 MHz and usable performance up to 1.3 GHz. These results are wonderful considering the low-cost architecture. Unfortunately, everybody knows that an engineer can’t be fully satisfied, and when he looks at a schematic, he’s always considering changes and enhancements. So, I decided to improve this original design as much as possible, but with some limits: I forced myself not to redesign the VNWA PCB itself, and in particular, I wanted to avoid the need for four-layer PCBs. My aim was to improve the measurement accuracy in the range 0.5 to 1.3 GHz. I’ll say more on that later, but I
a)
RF
TX Port
SWR Bridge
Audio IF
DDS RF
b) Power plug (1A-t fuse)
240-V Filter
Reference channel
Transformer 15 V
Reflected power
9V
12-VDC Switching PSU 12 V
12 V 5V RX Port
9V 5V
DC linear PSUs 5V
Transmitted power Fit-PC2
DDS LO
Mini-PCI-E
Mini PCI-E
USB
USB
PCI-E
PCI-E VNWA-USB Xonar D2X sound card
SPI
Mic. input
SPI VNWA-RF
TX Port
RX Port
Figure 1a sidebar—The VNWA2 architecture is based on a pair of DDS oscillators slightly shifted in frequency, mixed to provide measurement signals in the audio range. b—The architecture of my VNA is illustrated in this diagram. Its main blocks are the VNWA2 USB-driven circuit from Thomas C. Baier, a CompuLab fit-PC2 embedded PC, and a custom low-noise power supply.
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
Low-frequency signals
55
2112005_lacoste_Layout 1 11/8/2010 3:42 PM Page 56
worldmags
This means that, in the frequency domain, the spectrum at the output will be much more complex than the only fundamental sine. This phenomenon is called “aliasing,” and the idea is to use aliasing frequencies as a source signal, and that’s why there isn’t a filter after the DDS. Note that the spectral distribution of these signals is mathematically defined by the DDS clock frequency and the fundamental frequency to generate. Of course, a major drawback of such a generator is that the output spectrum of the VNA is very dirty and, as soon as you’re using an alias as RF source, there is more power at other frequencies than at the working one. There is no problem with that when working on linear devices (filters, diplexers), but it must be taken into account if the device under test is nonlinear (a preamplifier for example). Finally, we need to measure the signals in order to compare phase and amplitude. We all have a quite good sampling device able to do that, and this is the sound card of a personal computer. As it can only accept signals in the audio frequency band, a down-conversion is necessary. The local oscillator for this conversion is another DDS generating a signal at a slightly different frequency. (The difference being an “intermediate frequency” chosen in the audio band.) Again, note that the clock frequencies of both DDSes must be different in order to have different distribution of aliasing frequencies for RF and LO. Thus, it prevents other aliasing frequencies to give mixing products in the same audio IF band.
December 2010 – Issue 245
IMPLEMENTATION
56 worldmags
Dealing with small signals in a digitizing system always means simultaneously improving the dynamic range and noise floor. So, the conclusion was simple. For improved accuracy, a better sampling device was needed and driving noise away was necessary. In order to keep Dr. Baier’s software compatible, a sound card was needed. So, the first step was to find a suitable audio interface. In such a situation, if you want a portable system, use a USB CODEC. Unfortunately, these devices are exactly what Dr. Baier used, and none of them had an ADC that could exceed 92-dB SNR. The choice was quickly focused on a good 24-bit PCI Express sound card: the Asus Xonar D2X. This device integrates a Cirrus Logic CS5381 ADC reaching 120-dB SNR. Well, the main problem is that you need a desktop computer for such a sound card. Everybody has the feeling that putting a noise-sensitive device into in a PC wouldn’t be a good idea, and this is true. Moreover, the mobility of my VNA clearly would’ve been affected! My solution was to put the PC into the VNA. I spent a lot of time looking for an embedded platform that would be small, energy-efficient, able to run Windows XP, and have a PCI Express slot. The only affordable solution and the best PC platform for my
application was CompuLab’s fit-PC2 (www.fit-pc.com). It is fan-less, smaller than a soft drink can, and therefore easy to integrate into the VNA. Windows XP runs well, and plugging the PCI Express card can be done through the miniPCI Express expansion port. Mini-PCI Express is electrically compatible with PCI Express 1x, but the connecPhoto 1 sidebar—This is my tor’s form factor is different. vectorial network analyzer. Another good point is that it The small black box in the is enclosed in a die-cast alutop-left corner is the fit-PC, minum box that is perfect for with a high-performance sound board on its left. The EMC. VNA circuit itself is the PCB Finally, I’d like to touch on on the bottom left. The an essential topic: the power upper-right section is the supplies. With the aim of power supply circuit. reducing the noise level in the VNA enclosure, every sensitive part of the system is powered from linear power supply. The switching PSU is kept for the fit-PC2 itself. The VNWA DC/DC converter was also removed, and no less than six linearly regulated power rails are used to feed the entire system.
RESULTS The results are very interesting, and the dynamic range of the complete VNA are clearly improved. Up to 500 MHz, more than 90 dB is achieved. Above that, the dynamic range still drops, but it remains around a remarkable 80 dB at 1.3 GHz. I Author’s note: I would like to thank Robert Lacoste for giving me the opportunity to write these few lines in Circuit Cellar. I am very proud of this design, and I really hope this short project description encourages you to take up the soldering iron. Yannick Avelino is a radio and design engineer who has been working at ALCIOM since 2005. He has worked on numerous embedded projects ranging from RF telemetry devices to high-speed FPGA-based processing systems. You may reach him at
[email protected] SOURCES Xonar D2X sound board ASUS | www.asus.com CS5381 ADC Cirrus Logic | www.cirrus.com fit-PC2 embedded computer CompuLab | www.fit-pc.com VNWA2 kit SDR-Kits.net | www.sdr-kits.net
CIRCUIT CELLAR®
•
www.circuitcellar.com
57_Layout 1 11/9/2010 1:25 PM Page 1
worldmags
worldmags
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 58
worldmags
F
ROM THE BENCH
by Jeff Bachiochi (USA)
Encoder Essentials How to Close the Loop with Hardware
Component control is a key aspect of any successful robotics or mobile application. But a control system is ineffective without accurate, timely feedback. Enter the encoder, which can play a variety of important roles in a robotics application. This article details why closing the loop with feedback is an important part of the “control formula.”
December 2010 – Issue 245
W
58 worldmags
e typically go about our daily routines without giving them a second thought. The shower’s too hot? Turn up the cold. Can’t see the words on this page? Turn on the three-way lamp. Smell smoke? Turn down the toaster oven. Can’t hear yourself over the rest of the band? Turn up the amp. Morning coffee bitter? Add more sugar. You are constantly using feedback to help control your environment. This feedback helps you to “zero in on” or “close the loop between” what you want and what you need to do to get it. Sure, you can do this “open loop,” but the results often won’t be what you anticipate. Have you ever turned on the shower without testing the temperature? Chances are you ended up with chilly surprise or a bad scalding. Without the body’s sensitivity to temperature, you couldn’t set the shower’s dial to a comfortable level. When you start a process like adjusting the water temperature in the shower, you already know that you want a comfortable temperature. The problem is that there are no temperature settings on the shower’s dial, so you likely just turn it to an arbiPhoto 1—Incremental encoders come in both rotary and trary position. linear designs. Each outputs a quadrature signal based on interrupting the optical path. This produces a
control variable—let’s say a mix of 50% hot and 50% cold water. By poking your hand into the spraying water, immediate temperature feedback from your skin produces a process variable. Your brain uses this feedback and determines whether this falls into a level of comfort. If it does, great! You hop in and enjoy. If it doesn’t, your brain creates an error message that is the difference between the control variable, the shower dial’s position, and the process variable, the relative temperature of the water. This error has direction, too hot or too cold, as well as magnitude, way too hot or cold. Your brain uses the error direction to determine which way to turn the shower’s dial and the magnitude to determine how much to turn it. If you’re guessing this is an introduction to an article about PID loops, you’re wrong. Although PIDs are an important part of the control loop, it’s the feedback that I want to spend some time on here. Feedback in relation to movement. When something moves and there is a need for accuracy, there’s a need for feedback.
MOTION Motion can take many forms, such as rotary, linear, reciprocating, harmonic, circular, Brownian, etc. Most mechanical processes fall under the rotary or linear categories. Even this can be nebulous, because you can use rotary motion to produce linear movement and vice versa. In any case, what you want is to accurately move a CIRCUIT CELLAR®
•
www.circuitcellar.com
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 59
the servo to center itself between its for signs of impending doom extremes). The servo is a combination from vehicles is no fair! No wonder it’s so hard to be a robot. of DC motor, gear train, and feedback sensor (and circuitry). The motor Without absolute positioning, knows nothing of its position. It is we’d quickly find ourselves discontrolled by the feedback circuitry oriented. You might be able to either to move the servo clockwise or successfully get to the other counterclockwise. The position feedside of the street, but then back device is usually a potentiometer what? Have you memorized a connected to the gear train such that map of your environment? the servo’s maximum and minimum Without the use of your eyes positions directly relate to the pot’s you might call on the rest of maximum and minimum position. your available sensors to help The feedback circuitry looks at the you get an absolute position. It control variable (pulse width) and the might come from a smell in the process variable (potentiometer) and air, the touch of the concrete Figure 1—Quadrature output comes from two sendecides if and when the motor needs beneath your feet, the sound of sors out of phase with one another, giving four disto move and in which direction. In an traffic, a conversation, or the tinct states. From this, one can determine direction RC vehicle, this might set the throttle, sound of machinery. Slowly you and incremental count. steering, or rudder. In a robot, this build a map of your environmight control a joint or appendage. RC ment. You need to be able to count your steps and move in the right servos also can be modified to rotate specific distance and angle, from here continuously. In this case they lose to there. This can take place in 2-D, as direction. You need to have feedback. their position feedback as the pot isn’t movement in a plane, or in 3-D, as a multiple-turn device and must be movement in space. A SMALL WORLD removed or disconnected. Without its Most people have a rather narrow To accomplish what may seem like feedback (pot), the motor will continue view of the field of robotics. It’s either the simplest of tasks (e.g., vacuuming to run and never reach its destination. R2D2 or some arm on an assembly a room or mowing a lawn), your line. But when you think about it, robots need to be super smart. While today we have technologies ranging you can turn them on and let them POSITION SENSING from robotic medical devices to the randomly attempt to do their jobs Many position sensors are based on Mars Rover. The list is endless. Our without any attempt at mapping, a disk that is rotated by a shaft somerobots are machines that can do a task some sensors must be implemented to where in the gear train. In the case of on their own and usually react to their avoid catastrophe. After spending a linear sensor, it is a strip pulled environment. Reacting to the environhours creating a specialized robot, you through the sensor (see Photo 1). The ment is key, as we want robots to do a don’t want to lose it from a fall down wheel is a good place to start. Think job properly and safely. So, closed-loop the stairs or have it mow down your of a wagon wheel with 10 spokes. If control is a necessity. wife’s roses! Without feedback, you you count the spokes as they go by, can’t even tell if your robot is moving. you’ll know that the wheel has made How useless is that? one complete revolution when the POSITIONING Let’s begin by looking at how a number reaches 11 and you are seeing There are two basic methods of posicommonly used method of movement the first spoke again. If the wheel’s tioning—absolute and relative—and we uses feedback to ensure position. The radius is approximately 19″ and it use them continuously. Absolute posi(unmodified) RC tioning refers to locations that do not servo can rotate change (or at least do so rarely). We can 90°. Its position determine an absolute position from is controlled by environmental cues. As humans, we a 1- to 2-ms rely on vision to recognize these cues pulse repeated (e.g., a house, the curb, an office, etc.). every 20 ms. Close your eyes and you’ll be using relPulse widths ative positioning (for the most part). To between 1 and 2 get across the street, I only have to ms will set the walk forward about 30′. Without using servo’s position external cues, I would need to rememproportional to ber to step down off the curb, walk in a the pulse’s width Figure 2—A quadrature signal can be produced using two sensors straight line for 30′, and get back onto (e.g., a pulse of the opposite sidewalk without stumspaced at odd half slot multiples around a single track. Or, using two skewed tracks, the sensors are placed on a radial. 1.5 ms requests bling or getting hit by traffic. Listening www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
December 2010 – Issue 245
worldmags
59
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 60
worldmags
you need to know the movement down to the inch or less for a wheel? The simplest way is to increase the number of spokes to, say, 120. That would give you distance by the inch. You can see that this is about to get a little crazy, because wagon wheels don’t have room for 120 spokes! Luckily, technology has saved the day. We can make or purchase encoders that give increased resolution without having to rely on changing the wheel’s design. Figure 3—Absolute decoders have one track per bit of resolution, so they can require large diameters. This gives them a nonvolatile and unique output for each position. makes one revolution, you have moved 19 × 2 × π, or a circumference of approximately 10′. That’s around 1′ per spoke, so we could tell how far our wagon has traveled within a resolution of ±1′! Not a bad odometer for a covered wagon. What if the opposite wheel was stuck in a gully? The wagon would be going in circles yet the odometer would be happily clicking away the miles! Looks like you’d better use two counters, one for the left and one for the right. What about going backwards? Rotational direction cannot be determined just by counting the spokes! This is where a little logic can be applied. A second counter is added to each wheel so that when one counter sees a change (spoke edge), the second counter is between spokes. When the wheel rotates in one direction, the counters alternately count first one and then the other. If the wheel were to stop and reverse direction, one counter would get an extra count (out of turn so to speak). This indicates a change in direction. Now we have established a way to determine distances and also changes in direction for each wheel. But what if
December 2010 – Issue 245
Wheel diameter
60 worldmags
Circumference
X
S
N
COUNT In order to count things, you need to determine the presence or absence of the object. This can be done using a light source and light sensor, a magnet and magnetic sensor, or with mechanical contact switches. While mechanical switches might be used in very slow applications like a wagon wheel, contact bounce and cycle lifetime make it a bad choice for most applications. But let’s look at noncontact shaft/rotary encoders. Most optical encoders are made with a light source shining through a slotted disk with light sensors on the opposite side. The slotted disk alternately allows light to shine and blocks light from the sensor on the other side. The staggered mounting of dual sensors (at an odd multiple of half a slot width) produces the output waveform shown in Figure 1. This also can be achieved by aligning the sensors along a radial and using two shifted slot patterns (see Figure 2). When the slot/spoke density is reasonable, you can make your own encoder by printing a disk either on transparency film (using the light interruption method) or on paper (using the light reflection method). The cost of encoders is continually dropping, and if contamination is a factor in your robot, you’ll want to invest in a completely enclosed encoder. Check out my 2007
RPM at 32″/second
Accuracy ± 1″
1/8″
1/16″
2.55″
8″
240
8 PPR
64 PPR
128 PPR
5.1″
16″
120
16 PPR
128 PPR
256 PPR
10.2″
32″
60
32 PPR
256 PPR
512 PPR
20.4″
64″
30
64 PPR
512 PPR
1024 PPR
Table 1—This table shows how wheel diameters (chosen to produce binary integer circumferences) and accuracy will determine an encoder’s required resolution.
Figure 4—The Melexis MXL90316 produces a 1,024-bit (analog) output using a single magnet. article titled “Gearing Up to Go the Distance: Slotted Optical Switches” (Circuit Cellar 203) in which I describe using slotted opto-devices to count teeth on a gear to create an odometer for an electric bicycle. An alternate type of encoder uses magnetic poles as spokes or slots. The magnetic encoder uses Hall effect or magneto-resistive devices to sense the passing of a small magnet. Magnets may be attached to a rotating disk or the disk might be manufactured out of magnetic material and contain many poles. In reality, you don’t need to determine a change in direction as you have control over the motors and should already know which direction the motor is being run. However, the two systems are isolated and you may find good reason for keeping this redundant information separate. In the past, you were forced to use discrete ICs to keep track of counting. Today, many microcontrollers have decoders among their peripheral set. These can be initialized to automatically keep track of count and direction in the background.
ABSOLUTES The aforementioned encoders are relative encoders—that is, they can tell you how far you’ve moved, but they provide little information about where they are except in relation to where they were. When power is lost, so are CIRCUIT CELLAR®
•
www.circuitcellar.com
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 61
worldmags
Manufacturer A B C C C D E D E D E
PPR 8 16 16 32 64 64 64 128 128 256 256
Maximum RPM 300 100 300 300 300 300 3000 300 3000 300 3000
Cost $20 $5 $20 $20 $20 $50 $50 $50 $50 $50 $80
Table 2—Continuous duty, detent-less, optical shaft encoders come in many configurations. You can expect to pay a premium for those with higher resolutions and maximum RPM ratings. the relative encoder counts. (They are volatile.) Another type of encoder keeps track of where it is at all times: the absolute encoder. As you’ve seen, the relative encoder has two outputs of information giving you four discrete states (that repeat over and over again). The absolute decoder adds an additional track (ring of slots) and associated light source and sensor for each additional bit of position information. You can see that higher-resolution encoders need to get larger in diameter to accommodate additional rings. In addition, every ring has a different slot pattern to it because there must be a unique state for each position (see Figure 3). These encoders are not meant to be used in continuous
Photo 2—You can see a Grayhill 61R256 optical encoder (just above the motor) tied directly to the final (largest) gear in this speed reduction gearbox which has been removed from a robotic platform. rotating (multi-turn) configurations. They are meant for angular measurements, within one rotation. You might use one for steering or joint position. They are considered absolute because they will always give a true position as opposed to a count. These tend to be expensive. Refer to my November 2008 article titled “Drive by Wire: A Look at Noncontact Sensing” (Circuit Cellar 220). The Melexis Microelectronic Systems MXL90316 absolute
Mixed signal with protocol decoding Zoom on one byte
Mixed Signal Oscilloscope + Signal Generator
1.000 + 1.001 MHz mixed sine spectra
50 MHz width
www.cleverscope.com www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
8 kHz width
In the USA call:
December 2010 – Issue 245
+ Windows and Linux + 10ns resolution on 40 msec display + Disk save at 1.5 MSPS, to 500 GSamples. + Spectrum analysis – see 50Hz in 50 MHz. + Driver software for Visual C#, C++, Basic, Labview, Delphi and C Builder with examples. + Protocol decoding – SPI, I2C and UART + Isolated Ethernet option
Zoom on two sines
61
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 62
worldmags
encoder I implemented uses a magneto-resistive bridge and a 10-bit DAC to output an analog voltage proportional to a 360° rotation from a single magnet (see Figure 4).
PLACEMENT
December 2010 – Issue 245
I’ve already discussed using the actual wheel or drive axle as points of measurement. Depending on the wheel size and resolution you are looking for (assuming you will use some kind of pulse producing optical encoder), this will determine what kind of count you need to accumulate and therefore the resolution of the
62 worldmags
encoder. Different wheel diameters are noted in Table 1. Standard encoders have a shaft (like a potentiometer). You need to look carefully at the specifications for optical shaft encoders. Some have detents and are used for setting control values. These are not constructed for continuous rotation and the life ratings are low (thousands). Look for non-detent encoders that can withstand continuous rotations in excess of 100 RPMs and have life expectancies of millions of revolutions. Table 2 shows typical costs for various encoders. As you might have expected, higher-resolution encoders
and those that are rated for higher maximum RPMs are more expensive. Is the maximum shaft rating important? Well, let’s look at some numbers. I chose a maximum platform speed for this discussion of 32″ per second, as it is a nice round number that will allow for easy calculations. As you can see in Table 1, the two robots with the smallest wheels have a maximum shaft speed in excess of 100 RPMs. So, you can see that the lowest cost 4-bit encoder won’t hack the maximum speeds at which these shafts will rotate. In addition, that 16count encoder can just about handle
Photo 3—This gearbox diagram shows alternate positions where an encoder might be added along the gear train. The resulting resolution (PPR) is shown for both 5- and 8-bit encoders. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 63
worldmags
Photo 4—CUI’s AMT-103 is a universal optical encoder that can handle many shaft sizes and resolutions. Since it mounts directly on a shaft, it requires no additional linkage. an accuracy of 1″. I think most designers are looking for more accuracy than that. If the wheel shaft speeds are in the range of 20 to 240 RPMs. How fast is your motor spinning? Most likely, much faster than this (probably in the thousands of RPMs). You had
N
e
w
n
e
s
two choices when you chose a motor. You could’ve bought a motor and built your own gearbox, or you could’ve bought a motor with gear reduction already incorporated. The latter was probably the route you took. If that’s the case, you probably don’t have access to either the motor’s main shaft or any of the intermediate gear reduced shafts. Some manufacturers have options like an encoder or brake to be added to motor’s armature shaft. That’s great if you can afford it, but it’s probably overkill because you won’t want to count fractions of a motor’s rotation at thousands of RPMs. So, the main wheel shaft is the only place available for an encoder to go. Since most encoders have a shaft, you will need to somehow connect the encoder shaft to the wheel shaft. You might use a couple of pulleys or gears to do this. Gears with a chain or belt between them have an advantage over pulleys. The O-ring used between pulleys can have some “give” to it and is more prone to slippage, making the two shafts somewhat out of sync on fast accelerations. However, these are easier to use and less expensive. If you need to add some kind of linkage, you can easily change the effective resolution and maximum RPMs of the encoder shaft by using different sized pulleys or gears to reduce or increase the encoder’s shaft speed in relation to the wheel’s shaft speed. This can effectively increase your encoder’s resolution, but at the same time, it will increase the RPMs applied to it. You have all kinds of options if you designed your own gearbox to reduce your motor speed down to the appropriate
P
r
e
s
s
Education Never Ends. Everything you need to know to get started.
By: Gina Smith ISBN: 9781856177061 $44.95
By: William Kafig ISBN: 9781856177047 $44.95
By: Robert Lacoste ISBN: 9781856177627 $44.95
Stop by booth 1823 at ESC West to check out these titles and more!
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
December 2010 – Issue 245
By: Michael Parker ISBN: 9781856179218 $54.95
63
2112002-Bachiochi_Layout 1 11/8/2010 3:46 PM Page 64
worldmags
wheel speed. Photo 2 shows the original location of an expensive (8-bit) encoder. The image in Photo 3 shows two alternate locations where encoders might be placed along a gear train, ENC2 and ENC3. With the 8-bit encoder at ENC1, the travel per count is 0.016”. By moving the encoder’s location from ENC1 to ENC3, you might be able to use a less expensive (5-bit) encoder and actually increase the accuracy to 0.01” per count. The new location (ENC3) spins the encoder 16.345 times faster than the original location (ENC1). This makes the 5-bit encoder do the work of a 9-bit encoder. Using the same 32″ of travel per second from Table 1, you find this 8″ wheel shaft capable of reaching 76 RPMs. The rotational speed at ENC3 will be 16.345 × 76, or 1242 RPMs. The 5-bit encoder has the same maximum operating speed as the 8-bit encoder—300 RPMs. This is where the encoder’s maximum specified RPMs becomes important. It looks like you can’t save any money in this case.
December 2010 – Issue 245
DIG DEEP
64 worldmags
You never know where you’re going to find gold. I recently worked on a design that used a linear actuator—you know, the kind used to move satellite dishes or solar panels. I ordered one with an optical encoder from Nook Industries. What I found inside was an encoder that mounts to the shaft of the actuator. This is the kind of encoder a motor manufacturer might offer as an option. It is shaft-less—that is, it can directly mount onto an exposed shaft (see Photo 4). Although it isn’t in my paper DigiKey catalog, it is available on the website (AMT-103 $30). What makes this device so great? It has a resolution of 2,048 counts per revolution, it comes with all the hardware to mount on any shaft diameter from 2 mm × 8 mm (including 0.125, 0.1875, and 0.250″), and it has a maximum RPM of 7,500 at 2,048 pulses per revolution (PPR). The resolution is programmable through a set of DIP switches from 2,048 down to 48 counts. It uses the somewhat standard five-pin configuration (GND, IDX, PHA, +5 V, and PHB) available in either a straight or right angle locking header What can be done with these counts? If nothing else, you can tell that the wheel is actually moving. It’s nice to know if the wheel stops for some reason. This might be due to component failure or just one of your dirty socks wedged into the wheel well. When moving an appendage, a halt in the count could be used to signal that the joint has reached an extreme or signal that there is an environmental interference that requires the motor to be halted. There are two additional important roles that an encoder can provide to your robot’s control system. One role is for the encoder to serve as an odometer, where its count represents the number of countconstants the wheel has traveled (distance = count × count constant). Another role is to provide feedback to the motor controller. If you look back at the 10.2″ wheel in Table 1, you see that the top speed is one revolution per second. If this uses a 256 PPR (8-bit) encoder, you can expect to see 256 counts every second at top speed. At half speed, you can expect 128 counts every second. When you want the motors to drive at half speed, what value PWM should you apply to them? Well, by trial an error, you might
find that a 65% PWM gives the motors the correct current to drive at the expected 128 counts from the encoder. But what happens when the robot goes over a rug or up/down a hill? The motor will require more of less current, and if you don’t alter the motor’s PWM value, the robot will slow down or speed up. The feedback from the encoder lets you know when the actual speed changes due to whatever environmental influences the robot encounters. The motor control can adjust the PWM value until the encoder outputs the correct required count. You do this unconsciously while driving up and down hills. To keep a constant speed, with one eye on the speedometer, you step on the gas going up a hill and let off the gas when going down a hill.
CLOSING THE LOOP Closing the loop with feedback is an important part of the control formula. Without it, your robot can’t tell where it is going or when it gets there. Without feedback, if a motor stalls while trying to go up a hill, the system won’t realize it. Every sensor on a robot is a feedback device. You add ultrasonics, lasers, bumpers, IR, and other devices to your robot to make it aware of its surroundings. Don’t treat movement any differently. Close the loop. Add some feedback to make your motion control system smarter. 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.
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 topics covered in Alexander and Jeff Bachiochi’s Issue 245 article, the Circuit Cellar editorial staff highly recommends the following content: — LCD Digital Voltage Meter by Dale Wheat Circuit Cellar 209, 2007 Dale built a digital voltmeter around an ATmega48. The system measures the supply voltage of a rechargeable battery and displays the data on an inexpensive LCD. Topics: Digital Voltmeter, DVM, ADC, Resistor — Real-Time Feedback by Jeff Bachiochi Circuit Cellar 243, 2010 LEDs are efficient and serve an important role in many embedded design projects. But when you’re looking for real-time feedback, a versatile LCD module is the way to go. Topics: Feedback, Display, LCD, Character Generator — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
65_Layout 1 10/27/2010 1:16 PM 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
ded Audio ollers & Embed l Microcontr Analog Digita
[
February 2010
Audio Test & Measurement
]
US $ 7.95 - Canada $ 7.95
www.elektorusa.com
ent ] Test & Measurem
There’s More $ 7.95 US $ 7.95 - Canada
Preselector forthan just USB! Life Elektoto r SD R Here’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 Ther LTspice ore& Excel Tech ATM18 pared e’s M
nolo gy to Life than Proj
ects just USB! Logic Analyzer USB Magic Eye
N
OW ACKD Dimmer with a Micro a Sto PFCPutCR Throw led! eayism Christmas Hol p toto awa rev fac Buses mp rida ys Cirrcuits we po 13 pag yo esnd La be of beg US 2 B inne an r’s d and I junkbox C projollers & Embedded Test & Measurement ] My First AVR-USB 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 Audio Analogue Digita February 2010
2pen Logic AnalOyz TS 6 NEW PROJerEC Han
ty paci ery Ca Batt ker Chec
elektor.com stem PA Sy
& Excel
th luetoo TTL Bgle Don ain ke Ch orbi ot M
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 actt ... pac mp -com a-co ltra Ultr
ULO D MOD amplifier fledged stereo
Creative & fresh articles since 1961
$ 7.95 US $ 7.95 - Canada
A full-
PUZZLE H ELECTRONICS WIN $100 WIT
ues 11 Iss the ing includ e doubl r e m t sum or jus f e u s is 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
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 66
worldmags
S
ILICON UPDATE
by Tom Cantrell (USA)
What’s My Line? Moving Toward a General-Purpose Chip Processor, controller, DSP? Once the difference was clear, but over time it has blurred. Sure, there are still obvious differences at the extremes: the ’x86 in a PC is a processor, a PIC is a controller, and a SHARC is a DSP. But otherwise, the trend is toward general-purpose chips that cover all the bases.
December 2010 – Issue 245
I
66 worldmags
t’s been interesting to watch the evolution of our Boolean buddies. It was only 50 years ago that a mainframe computer filled a room and kept a team of caretakers busy catering to its myriad whims. Now yesterday’s “Big Iron” is all crammed into a shiny sliver of silicon that takes care of itself. Good thing, because now the caretakers who were once needed to tend the machine are freed up to give tech support to befuddled users. Along the way, we’ve seen architectural trends come and go—and then, more often than not, come again. Nevertheless, over time, there has been a Darwinian evolution where the best features get carried forward while the dubious ones eventually become extinct. The result is that even though there’s still a huge difference between a PIC, SHARC, and PC, they’re all kind of playing by the same rules.
RISC ROOTS In the beginning, processor architecture was “reduced” because it had to be. Considering that the ENIAC of the 1940s required many
thousands of tubes just to handle basic calculations, keeping it simple was the only option. But it wasn’t long before the miracle of “solid state” transistors and then chips gave architects freedom to roam—and roam they did, loading down computers with ever more baroque architectural trinkets. The 1960s and 1970s saw the introduction of virtually every architectural feature you can think of, including many that persist to this day, and many that don’t. The 1980s saw a backlash against architectural fat and feature creep in the “RISC Revolution.” It was kind of a replay of the 1950s (i.e., a computer designed by a few grad students has to be “reduced” by definition). Once again, the worthy ideas of RISC persist while others have succumbed to the siren song of free transistors. Most of today’s 32-bit “controllers” trace their roots to earlier “processors.” The Atmel AT32UC3L is no exception (see Figure 1). It’s a downsized single-chip version of the original AVR32 I covered back in 2006 (Circuit CIRCUIT CELLAR®
•
www.circuitcellar.com
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 67
JTAG Interface
RESET_N
Nexus class 2+ OCD
aWire
Instruction interface
Data interface
M
M
S
Memory protection unit
M
High-speed bus matrix
S
S Configuration
GCLK[4…0] RCSYS
DMA DMA
Reset controller
Capactive touch module USART0 USART1 USART2 USART3
DMA
Sleep controller
SPI
TWI Master 0 TWI Master 1
TWI Slave 0 TWI Slave 1
Nine-channel ADC interface
CSA[16…0] CSB[16…0] SMP SYNC RXD TXD CLK RTS, CTS SCK MISU, MOSI NPCS[3…0]
RC32K XIN32
RC120M
XOUT32 OSC32K XIN0 OSC0 XOUT0 DFLL
System control interface
64-KB Flash
Peripheral DMA Controller
HSB-PB Bridge A
DMA
Clock controller
16-KB SRAM
Registers Bus
DMA
Power manager
Local bus
M
DMA
PA PB
General-purpose I/Os
HSB-PB Bridge B
Local bus interface
TWCK TWD TWALM TWCK TWD TWALM
General-purpose I/Os
TCK TDO TDI TMS
AVR32 UC CPU
Flash controller
MCKO MDO[5…0] MSEO[1…0] EVTI_N EVTO_N
Memory interface
worldmags
PA PB
BOD
EXTINT[5…1] NM
PWM[35…0]
AD[8…0] ADVREF
External interrupt controller PWM Controller
A[2…0] Timer/counter 0 Timer/counter 1
B[2…0] CLK[2…0]
Asynchronous timer
ACBP[3…0] ACBN[3…0] ACAP[3…0] ACAN[3…0] ACREFN
AC Interface Waterdog timer Frequency meter
OUT[1…0] IN[7…0]
Glue logic controller
Figure 1—The ’UC3L packs a sophisticated AVR32 processor with DSP features into an MCU form factor. Cellar 195). That chip, designed to serve as the brains of a Linux SBC, was definitely a processor any way you look at it. The ’UC3L diet starts with jettisoning www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
high-performance features that aren’t needed in controller applications. The original AVR32 had a sevenstage pipeline, instruction, and data caches supporting triple-digit clock
rates, a high-speed external memory bus (SDRAM with ECC), a full-featured virtual-memory MMU, and a 256-pin package crammed with bigticket I/O, including USB, Ethernet,
December 2010 – Issue 245
Interrupt controller
67
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 68
December 2010 – Issue 245
worldmags
68 worldmags
Alternatively, the SAU can raise the safety bar by requiring software to specifically “unlock” I/O locations that MUL Multiply unit are deemed critical (e.g., the output pin controlling a motor, laser, etc.) before access is granted. The SAU is configured Regfile Regfile by specifying the protected location and IF ID ALU ALU Unit read write the key value that must be written to Prefetch unit Decode unit the unlock register. To guard against the possibility a software crash could leave Load-store LS the door open, you also specify how unit many cycles the location remains unlocked. If the location isn’t accessed in time, the SAU automatically re-locks it and raises an exception noting someFigure 2—The ’UC3L’s relatively short three-stage pipeline is a good compromise thing has gone amiss. There are addibetween performance and efficiency, while a dedicated multiplier allows the chip to do tional sanity checks that trap, such as double-duty as a DSP. attempts to unlock more than one location at a time or read the unlock register. Kudos to Atmel for recognizing the myriad ways and LCD controller. That all makes sense for a Linux things can go wrong and giving designers some defensive SBC, but it’s overkill for blue-collar embedded applicaoptions. tions. FlashVault is a clever extension of the usual flash proBy contrast, the ’UC3L has a shorter and simpler clastection (e.g., region, bootblock) features. It allows a porsic three-stage pipeline (see Figure 2) that tops out at a tion of the flash to be preprogrammed with software that leisurely 50 MHz. That approach makes sense considercan be executed, but can’t be read either internally (e.g., ing execution speed is ultimately bound by on-chip flash CPU instruction, DMA) or externally (e.g., debugger). access time. Like other flash bottlenecked MCUs, the This allows a chip to be shipped preprogrammed with ’UC3L counters with a wide (64-bit) flash bus. It also proprietary software that a subsequent application prohas small-scale caching features (prefetch, branch target) grammer can use, but can’t see, change, or copy. which can be disabled if you need cycle accurate determinism. In addition, there’s a ‘high-speed’ flash mode that boosts performance at the expense of higher power DSP DOINGS consumption (see Figure 3). Instead of jacking up the The ’UC3L pipeline has a dedicated single-clock 32-bit clock rate, Atmel touts the AVR32’s ability to get more multiplier with 48-bit accumulator that provides the done in each cycle by delivering up to 1.5 DMIPS/MHz venerable MAC function at the core of DSP inner loops. comparing quite favorably to other 32-bit MCUs such as Going beyond a mere multiply opcode, there are a couARM Cortex-M3 (1.25 DMIPS/MHz) and Microchip ple dozen DSP instructions that handle 16- and 32-bit Technology’s PIC32 (1.5 DMIPS/MHz). The big-ticket I/O is gone, along with a couple of hundred extra pins. But don’t be misled by the ’UC3L’s mild-man50 nered 48-pin package. Under the hood, it carries forward 45 many high-performance features of the fancier original. 40 For example, vestiges of the OS-capable MMU remain 35 in the form of a Memory Protection Unit (MPU), Secure 30 Access Unit (SAU), and what Atmel calls “FlashVault.” 1 Wait state The MPU determines the access rights (e.g., user/super25 0 Wait state visor, read/write/execute) for regions of memory and I/O Megahertz 20 (which is memory mapped). Typically, a critical I/O 15 function would be configured for supervisor-only access. 10 The SAU embellishes the scheme by selectively 5 enabling a higher (but slower) or lower (but faster) level 0 Normal High-speed of protection for specific memory-mapped I/O addresses. For instance, the set-up registers for an I/O device could generally be protected by the MPU, requiring supervisor Figure 3—The ’UC3L offers a “fast” access mode as an option to access to change the configuration. But at the same bypass the “flash bottleneck” at the expense of higher power contime, the SAU could be set up to allow user code to sumption. Depending on the particulars of an application, switching access the data registers directly, eliminating the cycles gears (i.e., between “normal” and “fast” access mode) may be useful to optimize the performance/power consumption trade-off. (i.e., time and power) burned by a supervisor call. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 69
worldmags
DP0 DP1
ADtspo+0 XP YP XM
ADtspo+2
ADtspo+3
Figure 4—A resistive touch screen works by applying a voltage to one plane (i.e., X and then Y) while sensing the voltage imparted to the other plane at the point of contact. The ’UC3L ADC features built-in hardware that handles the gory details of the drive/sense sequence.
signed and unsigned integer and fractional operands, saturation, and rounding. Number crunching is a necessary capability for a DSP—make that necessary, but not sufficient. The ability to stream data through the chip is equally important because in order to crunch numbers you have to get at them in the first place. Chip bandwidth is where the rubber meets the road, and if the tires are too skinny, a big MAC engine will just smoke them and go nowhere fast. Here the ’UC3L stands out by virtue of its processor roots and corresponding big-iron bus structure. Let’s take a look by starting at the core and working our way out to the edge of the chip. A high-speed bus matrix is Grand Central Station for data with connections to all corners of the chip. It allows simultaneous access between masters (instructions, data, DMA, debug) and slaves (flash, RAM, peripherals) and any contention is resolved with round-robin or fixedpriority arbitration. Typically, access through the matrix adds a clock cycle of latency, albeit only to the first cycle in a burst transfer. However, a slave (e.g., flash) can be configured to remain connected to a default master (e.g., CPU instruction fetch) to eliminate the arbitration delay. It’s funny how people will latch onto minor differences in processor www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
performance while ignoring I/O capabilities. A picture is worth a thousand words, and when it comes to moving data around, a DMAC is worth a thousand (well, maybe a hundred) MIPS. The ’UC3L obliges with a formidable 12-channel peripheral DMAC. It has some unique features, such as dual-reload registers for
Leading Embedded Development Tools...
ZZZDUPFRPWRROV
ZZZNHLOFRP For Microcontroller:
® 6RIWZDUHGHYHORSPHQWWRROVIRU$50 70 &RUWH[DQG&0&8V 5726DQGPLGGOHZDUHOLEUDULHV 'HEXJDGDSWHUVDQGHYDOXDWLRQERDUGV
For ARM Application Processors:
(FOLSVHEDVHGGHYHORSPHQWWRROVIRU/LQX[ DQG$QGURLG 6XSSRUWIRUDOO$50DSSOLFDWLRQSURFHVVRUV +LJKSHUIRUPDQFHGHEXJDQGWUDFHDGDSWHU
1-800-348-8051
December 2010 – Issue 245
YM
ADtspo+1
“ping-pong” double-buffering so the CPU can process one buffer while the DMAC fills or empties another. Recognizing the DMAC’s critical role, there are two channels worth of performance counters that track read and write bandwidth (transfer count), overall congestion (stall count), and maximum latency. Going a step further, a “Peripheral Event System” is able to independently make certain peripheral-toperipheral transactions without consuming any CPU cycles or bus bandwidth. For instance, a timer rollover can trigger an ADC (peripheral event user) conversion “event” (e.g., greater than, less than, inside window, outside window), which automatically increments or decrements a PWM duty-cycle register. Besides eliminating the many CPU cycles required using a typical interrupt scheme, autonomous peripheral operation tightens up the sample timing, which is a must for DSP applications. Configuring the ADC
69
2112003-Cantrell_Layout 1 11/9/2010 1:13 PM Page 70
worldmags
aWire
JTAG
aWire
JTAG
if you need it. Do note the ADC input range is limited to 1.8 V (the core voltage), which increases the resolution (V/LSB) but limits dynamic range (VMAX – VMIN).
AUX
On-chip debug
I/O U Memory service unit
Service access bus
Watchpoints
Transmit queue
Debug PC Debug instruction
Program trace
Breakpoints
CPU
Internal SRAM
HSB Bus matrix
Data trace
Ownership trace
Memories and peripherals
December 2010 – Issue 245
Figure 5—Even small programs can have big bugs, so the ’UC3L features sophisticated debug capability going well beyond that found on a typical MCU.
70 worldmags
to trigger directly from a timer guarantees jitter-free sampling no matter what else is going on (i.e., schedule unaffected by CPU or bus activity). Speaking of the ADC, the native resolution for the nine-channel unit (one channel for an on-chip temperature sensor) is 10 bits, but there are other options. If you don’t need the full 10 bits, you can cut it back to 8 bits for convenience (i.e., byte alignment of conversion results). Alternatively, resolution can be increased to 11 or 12 bits by provision for automatic oversampling that averages 4 or 16 samples, respectively. As I was reading through the ADC specs I noticed a “pseudo-random noise generator” feature. It generates a random binary stream of ones and zeros, the idea being you can route the stream to a pin and then use a resistor to add a measure (e.g., 1 or 2 LSB) of random noise to the analog input. At first glance, adding noise to the signal you’re trying to measure accurately seems rather counterintuitive. But remember that the basic premise of oversampling to increase resolution assumes the presence of some noise in the input. Understanding this is as simple as considering the alternative. If there’s no noise, every
sample would be the same, so there’s nothing to average. Another way to think of it is that adding noise dithers around the quantization threshold of the ADC to figure out whether the extra bit(s) of resolution should be a “1” or “0.” Along with the usual embellishments (i.e., a myriad of triggering and sequencing options), the ADC also incorporates a complete (i.e., no glue logic required) interface to a resistive touch screen (see Figure 4). Without getting into the details, suffice it to say it’s a standout-fromthe-crowd advantage for the ’U3CL
When it comes to serial interfaces, the ’UC3L has got you covered with virtually every flavor. There are two master and two slave I2C ports, a SPI port (configurable as master or slave), and four USARTs. As I went through the 76 pages in the datasheet devoted to the USARTs, I was reminded how technology marches on. Crammed with a bunch of application-specific enhancements (LIN, IrDA, RS-485, ISO7816 smart card, SPI-mode) these USARTs go way beyond the N-8-1 ports of yore. But in fact there is one plain UART onboard, the “aWire” that provides access to quite an array of on-chip debug features via a single (shared with RESET*) pin. Four-pin JTAG debugging (and boundary scan) is also an option. The Nexus-class debug capabilities go well beyond the simple breakpoints you might expect to find on a mini-me MCU (see Figure 5). For instance, there’s a “nanoTrace” function that captures trace data to on-chip RAM after which it can be examined at leisure. A remote debugger has complete control by virtue of being the source for instructions that are executed when the CPU is in the debug state.
Photo 1—The ’UC3L’s capacitive touch sensing (e.g., touch wheel) and PWM (e.g., LED fading) capabilities are aptly demonstrated with the AT32UC3L-EK evaluation kit. 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.
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 72
December 2010 – Issue 245
worldmags
72 worldmags
Touch sensing is all the rage, and the ’UC3L has that covered too (see Photo 1). The Capacitive Touch Module (CAT) supports Atmel’s QTouch (two pins per key) and QMatrix (X + 2Y pins for an XY key matrix) capacitive discharge schemes. Features include spread-spectrum drive to reduce emissions and external synchronization to sidestep mains interference. Unlike purely softwaredriven (to distraction) solutions, the CAT includes dedicated hardware to handle the detailed pin charge/discharge sequence and timing measurement. The CAT can even handle a single-key completely by itself using a built-in detection and calibration algorithm. Better yet, this feature works even when the chip is asleep, making it perfect for use as a pseudo-power (i.e., wake-up) touch switch. Another unique feature is the “Glue Logic Controller” (GLOC). It’s a mini-PLD comprising two four-input/single output LUTs connected to the peripheral bus (see Figure 6). Since the truth table resides in registers (i.e., not flash), it is dynamically reconfigurable. There’s a clocked output option to filter combinatorial glitches that might otherwise propagate to the output when inputs are changing. Of all the worthy I/O features, timing, counting, and PWM arguably deserve first prize. For a start, consider the fact nearly every single pin has PWM output capability! Each pin so assigned has its own 8-bit duty cycle register, but interlinked operation is supported as well. Any or all of the channels can be updated with the same duty cycle, or up to four channels with different duty cycles, at one time. As with the touch sensor, there’s a spread-spectrum option that softens the PWM timebase to reduce emissions. While you’re figuring out what to do with dozens of PWMs, don’t forget you’ve also got three 16-bit timer/counters with a full selection of timing, counting, waveform generation (yes, even more PWMs if you need them), and clocking options. You can choose between three external and five internal clock sources including the ability to chain the timers for even larger range. Timing relies on an accurate clock so Atmel tosses in a dedicated “Frequency Meter” (FREQM). It allows you to compare the myriad of clocks flying around the chip to an accurate (e..g, crystal) reference, measuring the ratio with 24-bit accuracy. The “Asynchronous Timer” (AST) wins the battle of the bits with a 32-bit counter and a 32-bit prescaler. Note that 64-bit numbers make my brain freeze, but Atmel says that’s good for a timeout of 100 years! Alternatively, the AST can be configured in calendar mode and even handles leap years. As the name implies, the AST can be clocked independently (e.g., 32-kHz internal or external clock) of the CPU making it a natural for use as a wakeup timer. Even the watchdog timer (WDT) gets gussied up with a window feature that narrows the time when clearing is allowed. For example, consider a scenario where a crashed program is stuck in a tight loop that happens to
clear the watchdog. A conventional watchdog will be waving its tail while the ’UC3L watchdog will smell a stranger (i.e., watchdog cleared too soon). In the seemingly unlikely case you actually need to do some bit banging, the ’UC3L has got you covered. Notice on the block diagram that there’s a side-channel connecting the pins and the CPU local bus. It’s a fast (one-clock) direct link to the pins that completely bypasses the bus matrix and peripheral bus. That means the CPU can access some pins with software while the peripherals and DMAC are accessing others, all at the same time with zero interference.
FEMTOPOWER? Over the course of the IC era, power consumption was generally a secondary consideration. But over the last decade or so, it’s become a big deal. Atmel promotes their low-power mindset as “PicoPower,” but whatever they call it, they’re definitely pushing the efficiency envelope. It’s not a matter of a fundamental breakthrough. No cold fusion here. Everyone’s holding pretty much the same low-power silicon hand. Rather, it’s attention to a myriad of details that make the difference. The UC3L core itself runs at 1.8 V, but it can run on anything from 1.62 to 3.6 V thanks to an on-chip regulator. The I/O lines have their own supply rail that you can connect to the input or output of the regulator. Thus, the power options are a 3.3-V single supply, 1.8-V single supply, or 3.3-V supply with regulated 1.8-V I/O. The latter option limits overall I/O current (IOL is 2 mA,
Peripheral bus
Truth OUT[0] … OUT[n]
Filter
FILTEN
AEN
IN[3:0] … IN[(4n+3):4n]
Figure 6—Don’t you hate it when you end up scrounging for a gate or two as the deadline looms? The ’UC3L has a bit of extra glue logic (two four-input LUTs) just in case. CIRCUIT CELLAR®
•
www.circuitcellar.com
2112003-Cantrell_Layout 1 11/8/2010 3:47 PM Page 73
worldmags
Mode
Conditions
Consumption (typical)
Active
CPU running a recursive Fibonacci algorithm from flash at 50 MHz with one wait state, all peripheral clocks enabled
300 µA/MHz
Idle
150 µA/MHz
Frozen
90 µA/MHz
Standby
70 µA
Stop
30 µA
Deep stop
20 µA
Static
AST and OSC32K running
7 µA
Static
AST and OSC32K stopped
5 µA
Shutdown
AST and OSC32K running
1.5 µA
Shutdown
AST and OSC32K stopped
0.1 µA
Table 1—Whether running flat out at 15 mA or sleeping at 100 nA, the ’UC3L power consumption specs are impressive.
TRIPLE THREAT So, is the ’UC3L a processor, a controller, or a DSP? By now you can see what I mean when I say the answer is yes. It’s got the “Big Iron” architecture (pipelined 32-bit CPU, DMAC, bus matrix) of a processor, the numbercrunching of a DSP, and the practical package, peripherals, and power consumption of an MCU. You know the old saying “Jack of all trades, master of none”? There will always be some truth to that, but the fact is, relatively few applications truly need the expertise, expense, or fussiness of an evermore specialized “master” to get the job done. With the ’UC3L, Atmel ably demonstrates that the “chip of all trades” is the future. Processor, controller, DSP? As long as it does more for less, it’s all good whatever you call it. So put on your hat, make that hats, and have at it. I www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
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 AT32UC3L AVR32 32-bit flash MCU Atmel | www.atmel.com
NEED-TO-KNOW INFO Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about some of the topics covered in Tom Cantrell’s Issue 245 article, the Circuit Cellar editorial staff recommends the following content: — AVR-Based Fuel Consumption Gauge Get Started with the W5100 by Bruce Lightner Circuit Cellar 183, 2005 Wouldn’t it be useful to be able to monitor your vehicle’s fuel consumption rate in real time? Bruce’s fuel consumption gauge is the answer. Topics: AVR, Fuel Gauge, OBD-II, Analog Meter — Maxed-Out PGA by Brian Millier Circuit Cellar 183, 2005 Brian shows you how he built an evaluation board and shares code routines that you can implement with an AVR microcontroller to configure an Analog Devices’s AD8555. Topics: PGA, AD8555, AVR, AT90S2313 — Go to Circuit Cellar’s webshop to find these articles and more: www.cc-webshop.com
December 2010 – Issue 245
except for five 4-mA “high drive” pins), but has the advantage of supporting the lowest of the eight lowpower modes (see Table 1). The ’UC3L designers give you plenty of power-saving options with explicit control over every single clock in the system. They go even further with a cleverly named “Sleepwalking” technique that handles clock control for you, with nary a cycle of CPU time consumed. Let’s say you want to periodically limit check an analog input and only wake up the processor if necessary. In this case, the entire processor complex can be shut off (i.e., clocks stopped) including the ADC. The aforementioned asynchronous timer (AST) is the only thing running to trigger the sampling. But, instead of waking up the CPU, using the aforementioned peripheral event system, the AST “event” wakes up the ADC (i.e., starts its clock) and triggers the conversion. The ADC itself is configured to perform the limit check and only generate an interrupt (thereby waking up the CPU) if necessary (i.e., above, below, inside, outside limits). Once the conversion is complete, the ADC goes back to sleep (stops its clock). As long as the input remains within limits, the CPU remains blissfully unaware and completely shutdown.
73
crossword2_Layout 1 11/8/2010 4:27 PM Page 78
worldmags
1
3
2
4 5
6
7
8 9 10
12
11
13
14
15
December 2010 – Issue 245
16
74 worldmags
Across
Down
1. 4. 7. 8. 10. 12. 13. 14. 16.
2. 3. 4. 5. 6. 9. 11. 15.
To suppress Rectifier; Johann W. Kolar Newton’s First Law Period to straighten out [two words] 19, 23, 29, 31, 37, 41, 43, 47 [two words] Coordinated Universal Time 103 Insulator for a wire 106
BIT [three words] Superscript number Variable resistor Behind a connector; shield [two words] BOB [two words] < 15 Hz 0.001″ Behind time
The answers will be available in the next issue and at www.circuitcellar.com/crossword. CIRCUIT CELLAR®
•
www.circuitcellar.com
ib-245_Layout 1 11/3/2010 3:45 PM 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.
I/O-Rich SBC Supports Embedded Ethernet/WiFi
O
O O O O
O
PDQ Board with
The PDQ Board Ethernet module a low cost 2.5”x4” C-programmable single-board computer Fast 16-bit Freescale HCS12 processor Ideal for data acquisition and control Embedded dynamic web server Email program-controlled messages from your instrument Plug-in modules for any kind of I/O, including GPS, A/D, D/A, UART, USB, AC and DC relays, and many more...
Mosaic Industries Inc.
tel: 510-790-1255 fax: 510-790-0925
www.mosaic-industries.com
Evaluate * Educate * Embed
Microcontroller Modules x8 & 32 bit xFreescale Flexis xMC9S08 series xMCF51 series
Adapt9S12 Modular Prototyping System For education & development
ndustries, Inc. (510) 790-1255
ww.mosaic-industries.com Toll-free: 1-877-963-8996
I/O Modules
x2x20 LCD xKeypad
Kits Available ORDER NOW
BASIC On Board Eliminates Development Tools
ATRIA Technologies Inc. www.TechnologicalArts.com
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
www.AtriaTechnologies.com
December 2010 – Issue 245
Communication GREAT For: xProjects Modules xBreadboards xBluetooth xExperiments xRS-232 xLabs xUSB
75
ib-245_Layout 1 11/3/2010 3:45 PM Page 76
December 2010 – Issue 245
worldmags
76 worldmags
CIRCUIT CELLAR®
•
www.circuitcellar.com
ib-245_Layout 1 11/3/2010 3:45 PM 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
December 2010 – Issue 245
www.maxbotix.com
www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
77
ib-245_Layout 1 11/3/2010 3:45 PM Page 78
worldmags
TCPmaker TCPmaker ffor or ccontrol ontrol o over ver the W Web eb
Simple Up Upgrade grade M Management anagement S System ystem
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,
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,
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!
From the makers of HIDmaker FS:
www.tracesystemsinc.com 888-474-1041
UART-WiFi, UHF EPC Gen2 RFID Reader, Powerline Communication
U ,J
U 'FBU VS FT * OD M VEF O F N r ' VM M T QFFE 64# J OU FS G BD F Q P
M F r 4PG U XBS F M J CS BS J FT T VQQPS U J OH )* % W F BOE $%$ D M BT T FT % # 4 r & Y B NQ M F T J O D M V E F ) * %
C V M L NP E F U S B O T G F S 6 WJ S U VBM $0. QPS U r %F W FM PQNFOU ,J U XJ U I G VM M * %& 1* $¥ .$6 $PNQJ M FS * $% 6 1S PHS BNNFS %FCVHHFS
! "
##
$ #
%& &
4U BS U J OH BU
64# 2! " $ # +
& (
! ' ) &* &
(&
)(
,() (()(
-
)( )(
& ( , '& - %& $ 1 "!
.) & )0 & / .& ( (()( %& & /
www.linksprite.com
1* $' % P F T O P U S F R V J S F E FE UB LF J E OM H PF X M P G 6 4 # 1 S P U P D P M
XXX D D T J OG P D PN 64#
.J D S PD IJ Q 5IJ S E 1BS U Z 5 PPM 1S PWJ EFS
T BM FT !D D T J OG P D PN Y
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
CROSSWORD ANSWERS from Issue 244
December 2010 – Issue 245
Down 2. INDUCTANCE—Rad : Angle :: H : _____ 3. ZENERVOLTAGE—VZ [two words]
78 worldmags
4. INTERLEAVE—The I in AVI 5. FRAGMENT—Frag 6. HASHCHARACTER—“#”; comment designation [two words] 7. PEERTOPEER—P2P [Three words] 8. CURRENT—Eddy 10. PASSIVE—Transistor : Active :: Resistor : _____ 13. SHUNT—For diverting a current 14. BATCHFILE—BAT [two words] 16. MODEM—Modulator + demodulator 17. ZERO—NRZ is a non-return to?
Across 1. AUXILIARY—AUX 6. HONEYPOT—A “sweet" trap for hackers 9. KERNEL—OS core 11. CONTACTS—A relay is an electromechanical switch that closes and opens these 12. SENSORS—Measure temperature, pressure, acceleration 15. F E M P T O S E C O N D — 1/1,000,000,000,000,000 s 18. FLASHMEMORY—Fujio Masuoka, Toshiba [two words] 19. OPENSOURCE—Linux, Apache, Thunderbird [Two words]
1
2
A U X I
3
L I
A R Y
N 5
4
Z
I
E
N
6
D
F
H O N E Y P O T
U
R
A
E
E
C
A
S
R
R
P
T
G
H
V
L
E
7
8
9
C
A
M
C
O
N
E
H
L
K E R N E L
10
U
P
R
A
C O N T A C T S
S
E
A
R
V
T
E
O
11
R 12
R
A
A
G
P
B
C
E
E
A
T
T
13
S E N S O R S 14
N
H
T
U
I V 15
N
E
16
R
F E M P T O S E C O N D 17
T
O D
C
R
Z E
H 18
E
F L A S H M E M O R Y
M
I
O
L 19
O P E N S O U R C E
CIRCUIT CELLAR®
•
www.circuitcellar.com
79-advertiser's index_Layout 1 11/8/2010 4:29 PM Page 79
worldmags
I
NDEX OF ADVERTISERS Page
Page
41
2011 Int’l CES
78
75
Page
26, 27
Elektor
C3
Jameco
AAG Electronica, LLC
65
Elektor
23
Jeffrey Kerr, LLC
All Electronics Corp.
63
Elsevier, Inc.
9, 32
JK microsystems, Inc.
C4
Parallax, Inc.
AP Circuits
14
EMAC, Inc.
75, 77
JK microsystems, Inc.
53
PoLabs
75
Atria Technologies Inc.
77
Embedded Adventures Ltd.
69
Keil Software
21
Pololu Corp.
76
Bitwise Systems
71
Embedded Developer
77
Lawicel AB
77
Reach Technology Inc.
57
CC Archive
39
ExpressPCB
Lemos International Co.
76
Scidyne
61
Cleverscope
14
ezPCB/V-Module
78
LinkSprite
25
Sealevel Systems
Comfile Technology, Inc.
78
FlexiPanel Ltd.
32
Linx Technologies inc.
78
Custom Computer Services, Inc.
47
Grid Connect, Inc.
77
MCC (Micro Computer Control)
75
Technological Arts
33
CWAV
19
HuMANDATA Ltd.
77
Maxbotix, Inc.
77
Tern, Inc.
75
Decade Engineering
IC Bank
76
microEngineering Labs, Inc.
78
Trace Systems, Inc.
23
DesignNotes
1
Imagineering, Inc.
75
Mosaic Industries, Inc.
15
WIZnet Co., Inc.
77
Earth Computer Technologies
9
Ironwood Electronics
11
Mouser Electronics, Inc.
8
5
P
48, 49
REVIEW
8
C2
7
2, 3
NetBurner
NXP mbed Design Challenge
Technologic Systems
A TTENTION A DVERTISERS of January Issue 246
Theme: Embedded Applications
Bicycle ABS Brake System Embedded Platform Development: A SoC TCP/IP Control Platform for EthernetEnabled Devices Mobile Application Development (Part 2): A Sound Detection Algorithm Stress-Free Probing
February Issue 247 Deadlines Space Close: Dec. 10 Material Close: Dec. 17
Theme Wireless Communications Bonus Distribution
THE CONSUMMATE ENGINEER Surge Suppression: Tips and Tools for Protecting Circuitry LESSONS FROM THE TRENCHES Big Changes in the Embedded World (Part 2): Implement an RTOS and a Real SPI FROM THE BENCH Smart Network Access Point SILICON UPDATE Power Tripping www.circuitcellar.com
worldmags
•
CIRCUIT CELLAR®
APEC, CTIA Call Peter Wostrel now to reserve your space! 800.454.3741 or 978.281.7708 e-mail:
[email protected] December 2010 – Issue 245
Page
79
steve_edit_245_Layout 1 11/8/2010 4:32 PM Page 96
worldmags
RIORITY
PINTERRUPT by Steve Ciarcia, Founder and Editorial Director
Winging It
December 2010 – Issue 245
E
80 worldmags
very once in a while I get an e-mail asking how to start a business. Apparently, I look like I must have done something right to still be around to ask. The short answer is, perhaps, but I assure you that having a “real business” is harder than you think. Let me start by saying that nothing I say here has any legal authority and it is my experience-based opinion. Let’s face it. Other than a government job, the rest of us either have to have a business that sells some product or service, or we work for an entity that does. Back when I got out of school, the economy wasn’t as bad as today, but jobs weren’t a whole lot more secure. The good news was that engineers in that era who got fed up with the corporate rat race always felt like they had the expertise to develop some product or other that yielded an alternative career path, albeit with definite risks. The fact is, “starting” a business doesn’t require any expertise; however, maintaining something that supports yourself and others does. The trouble with answering an e-mail from someone asking how to start a business is that without some real face time or investigation, there’s no way for me to give a quick answer. To a corporate test engineer with great ideas, little resources, and a family, I have to take it slow and warn him to carefully gauge the risks. For the single engineer or software guru with a wad of cash who has had three jobs in three years because he continually disagrees with management about design philosophy, I don’t hesitate to suggest throwing a lot more on the table and thinking bigger. To all of them I stress that a successful start, regardless of the product type, is a combination of exposure and tactics. Exposure is all about generating credibility. If your product is consulting services, you get the next job by demonstrating how well you did past efforts. Similarly, if you’ve designed some kind of widget, sales outlets want to see previous products before talking about any volume commitments. Yes, I realize it’s a “chicken or the egg” situation, but that’s where advertising helps. Online and print advertising can build a market for those initial products, which in turn creates credibility. The only variable is money. Add money and exposure comes more quickly. I was lucky because someone else paid for my advertising and created my exposure. Ten-page monthly design projects in BYTE magazine made a name for me and credibility for lots of successful first products. (In retrospect, perhaps I should have left BYTE and gone high volume, but then Circuit Cellar never would’ve started.) Today, BYTE is gone, but the Internet provides the perfect venue for low-cost exposure for everyone. Get an idea, create a webpage, and blast it to thousands for a whole lot less than it used to cost. That’s why I say “starting” a business is easy. Making a business successful enough to employ yourself and others is where we separate the wheat from the chaff. I have my own philosophy about manufacturing which I’m sure seems radical to purists. If you are starting a business, ask yourself what you want out of it. Do you want to be the next Bill Gates or simply the master of your own destiny? Achieving the former involves big money, big talent, and big fingers in the pie like venture capitalists. They require elaborate business plans, board membership, lawyers, detailed product analysis, progress reports, etc. Based on all the people I’ve known who went this route, 5% made millions and 95% got lost in the shuffle. If you don’t mind giving up your corporate jet and thinking a little smaller, then perhaps my method for simply controlling your own destiny can work for you too. Basically, stop sweating the small stuff and wing it! Seriously, most small businesses evolve as they grow. I started as an embedded control manufacturer and ended up owning a magazine. The first product is always done on a shoestring, but getting it out there quickly and cost-effectively is what funds something better-designed and better defensed. (Say what?) Too often, engineers don’t start companies because they spend too much time worrying about details—especially patents. Frankly speaking, virtually everything in life is already against the law. So too is the expectation that anything you design probably infringes some patent someplace. But, short of stupidity like calling it “iPad” or utilizing “not for commercial use” ingredients, something you design can be profitable enough in the short run to bootstrap the next product that has been designed to withstand legal competition. In my experience, except for trademarks (e.g., iPad, Droid, Core 2, etc.), big companies only whip patents out of the closet when you’ve created a product successful enough that they want a piece of the action. In either case, you’ve achieved your goal. With the money from such success you can give them a royalty, pay for your own lawyers, or simply move on to the next idea. At least you get the choice. Starting a business isn’t without risk and there is no simply answer when someone asks how to guarantee success. My game plan was merely to control my own destiny and not get fired. ;-) Regardless of philosophies or tactics, the one absolute truth about any business endeavor is this: Nothing ventured, nothing gained.
[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
11_Layout 1 10/27/2010 1:25 PM Page 1
worldmags
worldmags