Ubuntu Webcam Server C Language Rules and Assignments USB
Transcription
Ubuntu Webcam Server C Language Rules and Assignments USB
Why Specifications Matter, p. 14 | X10 Controller Design, p. 28 | Hexapod Robot Development, p. 44 THE MAGAZINE FOR COMPUTER A P P L I C AT I O N S July 2010 Issue 240 Ubuntu Webcam Server C Language Rules and Assignments PLUS The Professional Method: Research, Design, Write, Then Repeat USB and Standard Device Descriptors A Look at Powerline Communication Chips Wireless Data Transmission $7.50 U.S. ($8.50 Canada) www.circuitcellar.com Personal Download for [email protected] I © Circuit Cellar SSH Encrypted SERIAL TO ETHERNET SOLUTIONS Instantly network-enable any serial device Works out of the box no programming is required Device P/N: SB70LC-100CR Kit P/N: NNDK-SB70LC-KIT $47 Qty. 1000 Customize to suit any application with low-cost development kit SB70LC 256-bit encryption protects data from unauthorized monitoring 2-port serial-to-Ethernet server Features: 10/100 Ethernet TCP/UDP/SSH/SSL modes DHCP/Static IP Support Data rates up to 921.6kbps Web-based configuration Device P/N: SB700-EX-100CR Kit P/N: NNDK-SB700EX-KIT SB700EX 2-port serial-to-Ethernet server with RS-232 & RS-485/422 support $129 Qty. 1000 Need a custom solution? NetBurner Serial to Ethernet Development Kits are available to customize any aspect of operation including web pages, data filtering, or custom network applications. All kits include platform hardware, ANSI C/C++ compiler, TCP/IP stack, web server, email protocols, RTOS, flash file system, Eclipse IDE, debugger, cables and power supply. The NetBurner Security Suite option includes SSH v1 & v2 support. Device P/N: CB34-EX-100IR Kit P/N: NNDK-CB34EX-KIT $149 Qty. 1000 CB34EX industrial temperature grade Information and Sales | [email protected] Web | www.netburner.com Telephone | 1-800-695-6828 2-port serial-to-Ethernet server with RS-232 & RS-485/422 support and terminal block connector Personal Download for [email protected] I © Circuit Cellar Personal Download for [email protected] I © Circuit Cellar Personal Download for [email protected] I © Circuit Cellar Personal Download for [email protected] I © Circuit Cellar T ASK MANAGER July 2010 – Issue 240 I 4 THE MAGAZINE FOR COMPUTER APPLICATIONS Circuit Cellar: The Next Iteration FOUNDER/EDITORIAL DIRECTOR Steve Ciarcia PUBLISHER Hugo Vanhaecke EDITOR-IN-CHIEF C. J. Abate have noted here before that Circuit Cellar’s on-going mission is to educate professional engineers and academics so they may design the next generation of embedded applications and systems. This month marks an important step forward in our endeavor to provide exciting new content and need-to-know information. As you’ll see, we’re using all of our resources to deliver readers a new monthly column, an informative interview section, easier access to essential content, and more. Let’s move in chronological order. I don’t usually reference ads here, but check out page 7 for an example of a new product we developed after reviewing feedback from readers. It’s an 8-GB waterproof flash drive with every issue of Circuit Cellar and all the associated code. We call the flash drive “CC Gold.” It’s a great example of delivering today’s engineers what they require—in this case, a portable storage drive holding literally “everything Circuit Cellar” in one small package. And with gigs of space to spare, it’s a great place to store future issues and personal project files. Turn to page 8 to read our new “Questions & Answers” section. There you’ll find my recent interview with Jan Axelson, author of the often-referenced USB Complete and seven Circuit Cellar articles. After meeting Jan at the 2010 Embedded Systems Conference in San Jose, CA, it occurred to me that she would be the perfect first interviewee for this new section, which is dedicated to giving readers insight into how talented professionals achieved their success, cultivated their skills, and contributed to the computer applications industry. In future issues, we’ll present interviews with other notable engineers. After learning about Jan’s background and considering her ideas regarding the future of USB technology, check out George Novacek’s new column titled “The Consummate Engineer” (p. 14). The purpose of the column is to provide readers with tips on becoming more well-rounded practitioners of their trade. Sure, all of our readers are soldering and coding pros. But what separates a workaday engineer from a go-to guru is an understanding of “robust design.” In this column, George will touch on topics such as proper spec development, system hazard analysis, reliability analysis, and more. With a background in engineering and management, George is an excellent resource for readers looking to take their designs and careers to the next level. The rest of the issue touches on some of the most intriguing subjects in the field of computer applications. Examples include server development (p. 16), mobile robotics (p. 44), and data transmission (Bluetooth on p. 36 and powerline communication on p. 66). Lastly, keep in mind that we are constantly updating and upgrading our digital magazine and website in an effort to meet our readers’ rapidly changing needs. Be assured: if you want it, we’ll deliver. Stay tuned. [email protected] ASSOCIATE PUBLISHER Shannon Barraclough WEST COAST EDITOR Tom Cantrell CUSTOMER SERVICE Debbie Lavoie CONTRIBUTING EDITORS Jeff Bachiochi Robert Lacoste George Martin Ed Nisley CONTROLLER Jeff Yanco ART DIRECTOR KC Prescott GRAPHIC DESIGNERS Grace Chen Carey Penney NEW PRODUCTS EDITOR John Gorsky PROJECT EDITORS Ken Davidson David Tweed STAFF ENGINEER John Gorsky ADVERTISING 800.454.3741 • 978.281.7708 • www.circuitcellar.com/advertise ADVERTISING REPRESENTATIVE Peter Wostrel Strategic Media Marketing, Inc. 1187 Washington St., Gloucester, MA 01930 USA 800.454.3741 • 978.281.7708 [email protected] • www.smmarketing.us Fax: 978.281.7706 ADVERTISING COORDINATOR Valerie Luster E-mail: [email protected] Cover photography by Chris Rakoczy—Rakoczy Photography www.rakoczyphoto.com PRINTED IN THE UNITED STATES CONTACTS SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 Address Changes/Problems: E-mail: [email protected] GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION 860.875.2199, E-mail: [email protected] AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article. CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $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® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Let your geek shine. Meet Leah Buechley, developer of LilyPad—a sew-able microcontroller—and fellow geek. Leah used SparkFun products and services while she developed her LilyPad prototype. The tools are out there, from LEDs to conductive thread, tutorials to affordable PCB fabrication, and of course Leah’s LilyPad. Find the resources you need to let your geek shine too. »Sharing Ingenuity SP A R K F U N.C OM ©2010 SparkFun Electronics, Inc. All rights reserved. Personal Download for [email protected] I © Circuit Cellar 240 INSIDE ISSUE July 2010 16 28 36 44 • Internet & Connectivity Ubuntu Webcam Server Denny Lin Webcam Server, p. 16 Build an X10 Controller (Part 1) Circuit Design Devlin Gualtieri Wireless Data Exchange Build a 2,700-lb. Bluetooth Headset Tom Struzik Hexapod Kinematics Motor Communication, Motion Planning, and Image Processing Matt Bunting & John Rogers X10 Control, p. 28 Hexapod Robot, p. 44 14 54 July 2010 – Issue 240 58 6 66 THE CONSUMMATE ENGINEER It All Begins With a Spec George Novacek LESSONS FROM THE TRENCHES Put C Language to the Test (Part 3) Rules and Assignments George Martin FROM THE BENCH Application Communication with USB (Part 2) The Importance of Descriptors Jeff Bachiochi SILICON UPDATE Wall Whisperer A Fresh Take on Powerline Communication Tom Cantrell TASK MANAGER Circuit Cellar: The Next Iteration C. J. Abate QUESTIONS & ANSWERS Research, Design, Write, Then Repeat An Interview With Jan Axelson C. J. Abate 4 8 NEW PRODUCT NEWS 10 TEST YOUR EQ 13 CROSSWORD 74 INDEX OF ADVERTISERS August Preview PRIORITY INTERRUPT 72 Flavors and More Steve Ciarcia CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • 79 80 www.circuitcellar.com Personal Download for [email protected] I © Circuit Cellar QUESTIONS & ANSWERS Research, Design, Write, Then Repeat An Interview With Jan Axelson Jan Axelson is the author of USB Complete (Lakeview Research, Fourth Edition, 2009), Serial Port Complete (Lakeview Research, Second Edition, 2007), and many other books and articles about hardware interfacing. Between 1997 and 2008, she wrote seven articles for Circuit Cellar. I met Jan Axelson at the April 2010 Embedded Systems Conference in San Jose, California. In a May 2010 interview, I asked Jan about topics ranging from her earliest design experiences to the future of USB technology. — C. J. Abate, Editor-in-Chief CJ: Tell us about yourself. What’s your current occupation? JAN: I live in Wisconsin. When I’m not doing computer projects, I like to spend time outdoors. My favorite gadgets for outdoors are a GPS for navigating and an iPod with BirdJam software for identifying bird songs. I’m working on the design of a hand-held data logger that records the date, time, and GPS coordinates of sightings of target birds. With my books, articles, and website, I help developers use USB and other computer interfaces in their projects. CJ: How long have you been reading Circuit Cellar? JAN: I’ve subscribed to Circuit Cellar from the beginning. CJ: What was the first technology that really caught your attention and led you into the field of engineering? July 2010 – Issue 240 JAN: I’ve long been interested in what’s outside the box—how PCs and embedded systems can talk to the world outside themselves. Early on, the options were parallel and serial ports, including RS-485 networks. From there, I expanded my horizons to USB and Ethernet. 8 JAN: I have a degree in electronics technology. What led me to writing was my frustration in trying to find useful information about the components and circuits I was interested in. To write about something, you have to understand it inside out, so writing is a good excuse to dig deep. CJ: Before writing books, what was your profession? JAN: In one job, I installed and maintained long-distance telephone circuits. Each channel extended anywhere from across town to across the state. Troubleshooting was a group effort, with one technician on each end and another in the middle. I also worked as a test technician for a manufacturer of computer-controlled scientific equipment. That job was my introduction to serial and parallel ports. CJ: You wrote seven articles for Circuit Cellar between 1997 and 2008. The main topics were connection (USB and parallel/serial ports) and memory (EEPROMs). What interests you about these two subjects? CJ: How long have you been working with electronics and “embedded technologies”? JAN: I like to work on projects where a computer monitors and controls the world outside itself, and to do that, you need an interface to provide the link. For me, EEPROMs are just a reason to explore synchronous serial interfaces such as SPI and I2C. JAN: I have over 30 years experience with electronics and computers. CJ: Give us a quick review. What are the main differences between USB from the late 1990s and USB of today? CJ: What was your first MCU-based design? JAN: The chips, speeds, and tools have all changed dramatically—in good ways—over the last decade. The number of silicon providers for USB host and device controllers has grown from a few to several dozen. You can find everything from bare-bones interface chips to intelligent controllers that handle many of the higher-level USB protocols for you. With the release of USB 3.0 in 2008, USB offers four bus speeds, though host computers are just beginning to support USB 3.0. Drives and video devices have been the first to JAN: My first microcontroller project used an Intel 8052 microcontroller with a BASIC interpreter in ROM. An alphanumeric LCD displayed the temperature, maximum and minimum temperatures, and time. CJ: Describe your training. Are you trained as an electrical engineer, computer scientist, programmer, other? CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com incorporate USB 3.0. Perhaps the best news for developers is that prices for debugging tools have plummeted. A bus analyzer captures, decodes, and displays USB traffic and is essential for debugging. You can buy a low/full-speed analyzer for one-tenth the price of a similar tool 10 years ago, and high-speed analyzers are available for under $1,000. (Expect to dig deep for USB 3.0 tools, however.) International is another good source for modules. CJ: Where is USB technology headed? Is there something beyond USB? CJ: More advice. What would you say to a talented university student who asked you to suggest a topic to research for a dissertation? CJ: Many Circuit Cellar authors and readers consider your book, USB Complete, a “go-to” reference. What about you? What books do you recommend on the subject? JAN: For anyone using the new Vinculum-II embedded host chip from FTDI, I recommend Embedded USB Design by Example by John Hyde, a free e-book from www.usb-byexample.com. The .NET Micro Framework is an underappreciated and now mostly open-source programming platform for small systems. A good programming guide is Expert .NET Micro Framework (Second Edition) by Jens Kühner. Programming 16-Bit PIC Microcontrollers in C: Learning to Fly the PIC 24 and Programming 32-Bit PIC Microcontrollers in C: Exploring the PIC32, both by Lucio Di Jasio, are great sources for useful code snippets and tips. CJ: I enjoyed meeting you at the Embedded Systems Conference 2010 in San Jose. How do you keep up with the latest technologies? By attending conferences? JAN: The expo at ESC is a great way to find out what’s new. There’s something about wandering the physical space and talking with real people that’s completely different from seeking out the same information on the web. I find web forums useful for finding out what technologies are catching the interest of developers (or causing them headaches). I’ve added a PORTS forum to my website (www.lvr.com) in part to replace the discontinued USB developer’s forum at usb.org. Of course, Circuit Cellar provides inspiration for projects. CJ: Did you see anything at ESC 2010 that really excited you? JAN: I got a look at some inexpensive Linux-capable modules for high-end USB host applications. The BeagleBoard (BeagleBoard.org) is based on a TI OMAP3530 processor and has a large and enthusiastic user community. Emac, Inc.’s iPac9302 board is based on a Cirrus EP9302 processor and comes with Linux installed and an Eclipse IDE. Digi www.circuitcellar.com • JAN: My advice is to develop writing skills. Most jobs involve some writing, and the ability to produce useful documents can make you stand out. JAN: The iPhone aside, so many devices still have difficult and frustrating user interfaces. I would like to see more research on how to improve that situation. CJ: If you were to research and write about something other than USB, what would be? JAN: I’m interested in wireless technologies, especially inexpensive ways to do remote, real-time monitoring. CJ: What projects are you currently working on? JAN: I’ve been looking at ways to add USB host capability to small systems. Because the USB host manages the bus, implementing a host is a much bigger job than implementing a device. Microchip and other vendors help by providing example code for their microcontrollers with embedded host-controller hardware. If you want host capability without messing with the low-level details, a variety of products can help. The USBwiz (see Photo 1) from GHI Electronics and the Vinculum from FTDI are host modules that handle the USB host protocols and communicate via commands sent over a UART, Photo 1—On this Microchip Explorer 16 development board, SPI, or other serial or parallel a PIC24FJ256GA110 microconinterface. For devices protroller is used with a USBwiz grammed using the .NET OEM module to access USB Micro Framework, GHI Elecdevices. tronics has modules with USB host support. Applications that require a major OS can use a module running Linux or one of the Windows editions for embedded systems. CJ: Are you planning any other projects for the near future? JAN: Watch for my book on USB hosts for embedded systems in 2011. Thank you for this chance to share my thoughts with the readers of Circuit Cellar! I CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 JAN: USB 3.0 promises data throughputs of up to 400 MBps, 900 mA of bus current per device, and new power-saving protocols. The interface adds a new 4-wire, 5-Gbps, dual simplex bus that is similar to PCI Express. Higher-level details such as the four transfer types and USB classes remain the same. CJ: Advice time. Is there one thing that you think every electronics engineer needs to know? Why? 9 N S W E N CT DU R O EW P Edited by John Gorsky A MINI LINUX PC FOR UNIVERSAL USE July 2010 – Issue 240 The PortuxG20 is a miniature Linux PC that’s energy-saving, compact, and comes with numerous interfaces. Its connection possibilities make it ideally suited for a wide variety of applications like data logging or computer interfacing. For instance, data can be recorded over time and periodically read into another device for additional processing as needed. In addition to the immediately available on-board interfaces, additional peripherals also can be connected. Depending on the multiplexing, up to four serial interfaces at TTL level, two SPIs, one I²C-compatible bus, an SSC, or up to 32 digital I/O ports are available. The SBC is equipped with an Atmel AT91SAM9G20 processor core running at 400 MHz and includes 64-MB SDRAM and 128-MB NAND Flash. The board measurements are 100 mm × 75 mm × 17 mm. It supports many common interfaces, including Ethernet, USART, USB 2.0 full speed, Micro SD card, JTAG, and the Portux Extension Bus (PXB). Additional interfaces such as SSC, SPI, TWI, an external SD card, a fourchannel 10-bit ADC, a 16-bit parallel bus, and up to 64 digital I/O ports are available via the PXB. Current consumption is 150 to 170 mA at 5 V (with an active Ethernet interface). Measurement, control, and regulation technologies are well-suited applications for the PortuxG20 compact single-board computer. The Linux operating system, the “U-Boot” boot loader, and the “JamVM” Java Virtual Machine with the “GNU Classpath” Java Class Library are all preinstalled. The board itself costs about $225. Several starter packages are also available. 10 taskit GmbH www.Taskit.de CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com CC430 PLATFORM FOR COMPLETE SOLUTIONS FOR WIRELESS NETWORKING The CC430F513x MCUs combine the world’s leading ultra-low-power MSP430 MCU with the high-performance, sub-1-GHz CC1101 RF transceiver. The CC430F513x devices offer up to 20-MIPS performance in a small package (7 mm × 7 mm) and support security options such as an integrated AES hardware module. Also available is the CC430F61xx series of LCD control devices, providing developers with more options to meet varying design needs. With the capability to support multiple protocols and a broad frequency range, the CC430 MCUs, along with the extensive third-party ecosystem, spur innovation in applications like home and building automation, smart metering, energy harvesting, asset tracking, and portable medical applications. Developers can also immediately jumpstart CC430 MCU-based designs with the EM430F6137RF900 and eZ430-Chronos wireless development tools that include all the hardware design information required to develop a complete wireless project. Eight devices offer non-LCD and LCD options, as well as a range of pin count, memory and high-performance analog integration to meet varying design needs. The devices draw low enough current to enable battery-operated wireless networking applications that operate without servicing for several years, reducing maintenance costs and overall BOM. Production quantities of the CC430F513x MCUs are immediately available and pricing starts at $4.15 (1,000 units). Sampling quantities of the CC430F61xx family with integrated LCD are also immediately available to order with pricing starting at $4.35 (1,000 units). ICs AUTOMATICALLY AND SAFELY DISCHARGE X CAPACITORS CAPZero is a family of innovative, two-terminal, automatic X capacitor discharge ICs that eliminates power losses while allowing power supplies to comply with safety standards. CAPZero acts as a smart high-voltage switch when placed in series with discharge resistors. When AC voltage is applied, CAPZero blocks current flow in the X capacitor safety discharge resistors, reducing the power wasted in these components to zero at 230 VAC. When the AC voltage is disconnected, CAPZero automatically and safely discharges the X capacitor by closing the circuit through the bleed resistors and directing the energy away from the exposed AC plug. This approach provides engineers with total flexibility in their choice of the X capacitor used to optimize differential-mode EMI filtering without worrying about the effect of the required bleed resistors on system no-load and standby power budget. The innovative design inherently meets international safety standards for all open and short-circuit fault tests, allowing CAPZero to be used before or after the system input fuse. CAPZero is suitable for all AC-DC converters with X capacitors that require very low standby power. It’s offered with 825- or 1,000-V MOSFETs to support a variety of power supply design needs. It is ideal for a wide range of applications, including PCs, servers/workstations, monitors and TVs, printers and notebooks, and appliances requiring EuP Lot 6 compliance and adapters requiring ultra-low no-load consumption. CAPZero devices are available now in an SO-8 package at $0.40 each for 10,000piece quantities. Power Integrations, Inc. www.powerint.com Leading Embedded Development Tools... Texas Instruments, Inc. www.ti.com ® ! "#$ $% $ !&'"( )$% For ARM Application Processors: *+$% ,$) $ ) $+$ + /$26 +%)2 + . NPN www.circuitcellar.com • www.keil.com 1-800-348-8051 CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 For Microcontroller: 11 OBD-II INTERPRETER MODULE IN A DIP-24 PACKAGE The microOBD 200 (#440101) is a complete OBD‐II interface in a vibration-resistant DIP-24 module. The only product of its kind, it offers engineers a simple and inexpensive way to add OBD-II support to any embedded project and tap into the wealth of information available on the vehicle’s communication bus. The interface is fully compatible with the popular ELM327 command set and supports all legislated OBD-II communication protocols, as well as the heavy-duty SAE J1939. It features automatic protocol detection, a large memory buffer, a UART interface capable of speeds of up to 10 Mbps, and a bootloader for easy firmware updates. The microOBD draws less than 1 mA in Standby mode, which makes it suitable for permanent in-vehicle installations. The host can force the module to enter the lowpower state by sending it an explicit “sleep” command or pulling the digital “host present” pin low. The module can also put itself in Standby automatically on UART inactivity or by sensing that the engine is off. Typical applications include diagnostic scan tools, code readers, data loggers, digital dashboards, fleet management, and vehicle tracking. Product documentation and volume pricing are available from www.microOBD.com. The module costs $49 in single-unit quantities. ScanTool.net LLC www.scantool.net NPN /,- /,- /, ( , -)&0 *,. $( '$&&$)( .) -#)1 3)/ 1#.5- ./&&3 #** ($(" /, ), $. $"$.$4 , "$0 - 3)/ 2 && (. ( .#$- 2'*& 1 -'*& .1) -$( 10 - )! ( 4 '$2 .)" .# , #0 4))' )( %4 *),.$)( $( .# 4 $-*&3 (1$.# ). )/, 2 *.$)(& , -)&/.$)( $(. , ')/&.$)( $-.),.$)( ( July 2010 – Issue 240 # $,- 12 '! ( $ %##$ #!%!! ! "%#& )$$ )! %$ &$%! & %$ !") "$% #%!# !# %# % !# $"$ $%!# * $" & !# % (% ## % "&%$ $ #% #$- +/$0& (. $-*&3 #- '2$'/' !, +/ (3 , -)&/.$)( )! *,. $( # $. $"$.$4 , &$'$.- )1 , $( )''/($.$)(- (3 )1 , $( )''- -3-. '/- (,,)1 ( -$"(&$(" $( .# 6 #4 !, +/ (3 ,(" )/ ( ")) !, +/ (3 , -)&/.$)( ( $"(& .) )$,.$) .) - 1#. $- ")$(" )( -$(" & 0 ,-)* 3)/ ( # % )/. )/*$ (1$.# .# !! .- )! ()$- ( -1$.#$(" ( &)" ,$0 0&/ - -/# ( 0)&." (5. - .# .1) * %- # -$("& * % )/*$ - %4 )! $-*&3 (1$.# # $-*&3 *),.$)( $- 4 1$ )/ #0 () $ 1#. $- ")$(" )( CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com CIRCUIT CELLAR Edited by David Tweed Problem 1—Assuming that VP and VN are connected to voltage sources (negligible source impedance), what is the value of VOUT of the following circuit? The two RX have the same value, as do the two RY. Assume the op-amp is “ideal.” EQ Test Your Problem 3—What kind of feedback circuit do you need in order to construct a switching regulator whose output is exactly half of its input voltage? Problem 4—In the C programming language, name at least two ways in which the following structure for (expr1; expr2; expr3) { ... } is not precisely equivalent to this structure: Problem 2—What is the significance of this circuit? What’s your EQ?—The answers are posted at expr1; while (expr2) { ... expr3; } www.circuitcellar.com/eq/ Contributed by David Tweed July 2010 – Issue 240 You may contact the quizmasters at [email protected] www.circuitcellar.com • 13 CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar T HE CONSUMMATE ENGINEER by George Novacek (Canada) It All Begins With a Spec Your goal is to become a well-rounded, multidisciplinary engineer who can address hardware and software issues alike, tackle difficult design problems, and deliver quality work on a consistent basis. But achieving this goal takes time, effort, and guidance. So let’s start with the basics. E ngineering is fun. Where else do we get to invent, create and play with such exciting toys—from iPhones to advanced military aircraft—and get paid for it? I know, I know, we also have to worry about schedules, budgets, and managers who are not engineers—but in the end, nothing beats the satisfaction of seeing our ideas become realities. The creative fun, however, goes hand in hand with a great deal of responsibility: to the end users, to our employers, to our colleagues, to our companies, and ultimately to ourselves in terms of professionalism and pride. Not only must we ensure our design will work as specified; we are equally responsible for making it reliable, ensuring that it’s safe to operate, making it environmentally friendly, and ensuring it can be manufactured consistently and economically. In future columns, I will address engineering activities and procedures to achieve those goals. The idea is simple: you want to become a well-rounded engineer. But that’s easier said than done. So, let’s begin with the basics. July 2010 – Issue 240 WHAT’S IN A SPEC? 14 At the beginning of all our efforts has to be a good, concise specification defining in no uncertain terms what we, the engineers, are expected to deliver. Unfortunately, this is not always the case. Sometimes such a specification is impossible to develop, namely for systems and products with long life expectancy, where continuous technological improvement takes the product well beyond its original concept. The Internet is a good example. Let’s imagine what the Internet could be, had its original creators had the benefit of knowledge of technological advances of the several following decades and developed the architecture and the protocols accordingly. Abuse of the Internet would be much harder today, although I don’t believe the Internet could be made bullet proof. Only a few of us will ever have the opportunity to be at the birth of a system with the impact and longevity of Internet, where inadequacies of the original specification could not be prevented. In the majority of development programs there is no excuse not to start with a specification cast in stone, with no detail left to a chance. It has been shown that most of product shortcomings are not the result of poor design, but poor, inadequate specification. Why is that? One excuse is economics. There were times when top-level system integrators, such as airframe manufacturers, had a team of experts specifying subsystems and their components as black boxes in minute detail. A specification for a simple embedded controller would have been a hundred or more pages long. For those not familiar with the concept, engineers like to talk about black and white box designs. These exist at all levels of a system. The black box design defines all the functions, interfaces and performance characteristics as viewed from the outside with no regard for how are those design goals achieved. White box design is the actual implementation, typically schematic diagrams and source code for an embedded controller. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com SPEC AMBIGUITY Spec ambiguity is another pitfall we need to watch for. Engineers preparing a higher level specification may forget that while they understand the system well, engineers given the task to design to this spec may, without understanding the context, give it a different interpretation. Specifying the working environment of an equipment is one thing, but good engineer must also consider what extreme use and environments the equipment may be exposed to and take steps to ensure the equipment remains safe even outside its specified operating envelope. You must expect the unexpected. Once I worked on a controller where four sets of 380-V loads were connected to four separate MIL connectors, each about 4 inches in diameter. Because inserting a wrong plug into a wrong receptacle could result in catastrophic consequences, each connector set was color coded and keyed. We convinced ourselves that mismatching the connectors was impossible. Yet, it happened on the very first unit being installed. The fireworks, I was told, were spectacular. Fortunately, no one was injured, only the controller was destroyed and the customer extremely upset. Within hours an www.circuitcellar.com • engineer was flying across the continent to investigate. He discovered that the installer, when the very first cable connector he touched didn’t mate with the receptacle, decided to take a monkey wrench to it, forced the plug into the wrong receptacle, breaking off the key in the process, then proceeded hammering the remaining three connectors in their wrong places. To prevent the “impossible” from happening again, we added monitors to the controller to stop the power from being turned on should someone invented another way to mate wrong connectors. While much of circuit design can be performed by junior engineers under supervision, the top-level spec development requires in addition to solid engineering knowledge something no school can give you—experience. LOOKING AHEAD Moving forward, I’ll share my engineering experiences with you. Hopefully, they will help you to avoid learning the hard way from your own mistakes. 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 in Canada. 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. To learn more about George Novacek’s design tips and projects, the Circuit Cellar editorial staff recommends the following: — Building an Electric Airplane by George Novacek Circuit Cellar 150, 2003 Many engineers see electric motor technology as the ticket to an energy-efficient, cost-effective future. With this in mind, George shows you how to design an electrically actuated system, with a focus on control and braking. Topics: Aeronautics, Actuator, PWM, Control, Braking, EMF, Fly-by-Wire Go to: www.circuitcellar.com/magazine/150toc.htm — Working with EMC by George Novacek Circuit Cellar 142, 2002 George explains differences between magnetic and electric emissions. You can design your next project to handle both. Topics: EMC, EMI, Electromagnetic Compatibility, EMI, Protection, Shielding Go to: www.circuitcellar.com/magazine/142toc.htm CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 To reduce non-recurring engineering costs, the burden to generate the black box definition of a sub-system, in other words the specification, was gradually shifted down the supply chain until it eventually ended up on the controller designer’s desk as perhaps a single paragraph of technical requirements, with a laconic statement “you are the experts, write your own spec”. Needless to say, expecting an electronics engineer, even though he may have designed similar controllers in the past, to be an expert on, say, aircraft dynamics is quite a stretch. What looked as a perfect way to save money to an accountant usually results in even higher cost of development, blown schedules and finger pointing. No better results come from a similar approach called “concurrent engineering,” where time and money should be saved by having the black and white boxes developed concurrently. This is an engineering version of the chicken or the egg dilemma. Several teams are second guessing each other, occasionally ending up in a dead end or having to do things the complicated way because the simple route had been blocked. Over-design, spaghetti code, less than optimum design, those are the results. Another cause of a poor up-front specification is that its importance is underestimated, its preparation considered boring. Many a hardware designer likes to start drawing schematics, just as a software designer likes to start by writing code without a previously developed and understood architecture and a set of requirements. This is a sure way to get in trouble. No engineer should start white box design before he has shown the black box to be correct, traceable to the top level spec and testable. In my experience the time spent up front developing a solid spec supported by black box description has always brought the best results. 15 F EATURE ARTICLE by Denny Lin (USA) Ubuntu Webcam Server Ready to take a look inside an Ubuntu webcam server? Once you finish this project, your viewers will have access to your streaming video via any modern browser (Internet Explorer, Firefox, Safari, Opera, or Chrome) and desktop OS platform (WindowsXP, MacOS, or Linux). T he Department of Mathematics and Computer Science at La Sierra University (Riverside, CA) where I work maintains a display area in which we showcase many of the cool gadgets we develop. One such design is a computer-controlled monkey we affectionately call Kiki, which users can control from any Internet connection and view via a LinkSys webcam (see Photo 1). The webcam originally had a serious shortcoming. It required the use of Internet Explorer, an ActiveX module, and a series of obscure procedures to enable the module. As a result, people using non-Microsoft browsers couldn’t see Kiki. We simply needed a video stream that was compatible with as many browsers as possible. Fortunately, I had a used IBM PC camera (which I’d bought July 2010 – Issue 240 a) 16 at a thrift store for less than $4) and a bunch of computer parts from a good friend. As a result, I decided to build a web camera server from the ground up, one that would offer broader browser compatibility. While assembling this server, I realized that displaying the inner workings of a functional server would effectively turn a video webcam server into useful, and educational, eye-candy. So, for $67, I bought a transparent computer case that came with three 80-mm fans illuminated by eye-catching blue LEDs (see Photo 2). SYSTEM OVERVIEW The design features several key pieces of hardware: an Intel motherboard, a 1.70-GHz Intel processor, 256-MB memory, a b) Photo 1a—The Kiki computer-controlled monkey is located in a display case at the entrance to the Mathematics and Computer Science Department at La Sierra University where I work. My webcam server monitors Kiki. b—This is the Altera Nios web server controller board. It is the creation of Dr. Enoch Hwang at La Sierra University. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com a) b) c) Western Digital 6-GB hard drive, a BenQ DVD-ROM (16×), an NVIDIA GeForc video card, an Antec 300-W power supply, a Logisys Model CS888CL case, and an Xirlink IBM PC Camera KSX-X9903. Because I was building this system on the cheap, the next step was to find a free operating system. I chose the popular Linux distribution called Ubuntu, and downloaded the entire operating system as an image file to be burned onto a bootable CD-ROM (which can even run on a computer without a hard disk). Figure 1 shows the relationship between the Ubuntu webcam system I describe in this article and the Kiki Altera webserver displays. Figure 2 shows the components that make up the Ubuntu webcam system. Although there is a server edition of Ubuntu 9.04, I chose the desktop version because it’s easy to configure and provides a simple-to-learn graphical user interface (GUI). Many configuration steps still require the use of the command prompt; but fortunately, these simple commands can be documented in step-by-step instructions. This is how www.circuitcellar.com • the idea for this article began! Building this Ubuntu webcam server involves three main steps. Let’s consider each one. The first step is to install Ubuntu onto the computer. This step is straightforward since the installation program on the Ubuntu CD-ROM includes a step-by-step “Wizard.” The second step is to install, configure, and update the servers. This configures the computer’s operating system to be used as a server and installs the two servers that run the webcam. Critical security updates are installed at the end of this step. The third step is to configure start-up scripts to automatically start the webcam server. Doing so loads the IBM PC camera driver that links the camera images to the computer’s video device, and it creates a start-up script for the webcam server. I added two additional steps. Although they’re optional, I recommend them. One, set up a remote desktop. Doing so makes it possible to manage the server from a remote computer. Next, set up a firewall. This step disables all ports that are not essential for the functioning of the webcam server. While the hardware and software cost very little, considerable time and effort went into learning about and setting up the software. I found websites that contained bits and pieces of information needed to get my hardware and software to work. If your hardware or software differs significantly from mine, use common sense (and lots of patience) to troubleshoot any issues. The configuration files were created and modified by a text editor called Pico, which is included in this Ubuntu distribution. While Pico lacks a GUI, I found it easy to use. Context-sensitive commands, listed on the bottom of the screen, can be accessed by pressing a combination of CTRL and letter keys. For example, help (labeled ^G Get Help) is accessed by pressing CTRL-G. INSTALLING UBUNTU To begin, find and download the 32-bit Desktop Ubuntu 9.04 disk image. Any computer with a browser connected to CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Photo 2a—An IBM PC camera is pointed at Kiki. b—This is my completed webcam server housed in a transparent case. c—This is a close-up shot of the server. The system is pretty eye-catching, especially with its blue LEDs. 17 Internet Forwards off-campus requests for 192.156.214.81 to 10.1.31.24 Forwards off-campus requests for 192.156.214.80 to 10.1.31.23 IP Address forwarding firewall Ethernet network traffic Ethernet network traffic Network switch Local IP Address: 10.1.31.24 Local IP Address: 10.1.31.23 Video IBM PC USB Camera Drumming monkey 3-V DC On/Off Relay 115-VAC to 3-VDC Adapter Ubuntu webcam server: Host server’s main page, the webcam video, and embeds the Altera web server page Altera web server and Kiki controller: Host embedded page containing the monkey on control button Welcome to Kiki’s Webcam! Webcam video (Java applet) Existing Altera controller monkey display by Dr. Enoch Hwang Inline frame (iframe) tag embeds the Altera web server page within the Ubuntu webcam server’s main page The server’s index.html main page Monkey On Ubuntu webcam system display Figure 1—This block diagram shows the relationship between the Ubuntu webcam system and the Kiki Altera web server displays. the Internet, equipped with a CDROM drive and burner software, can be used to create (burn) the CD-ROM. Using a Windows XP computer, I saved the image file, and right-clicked on its icon to burn an Ubuntu-bootable CDROM. I configured my computer’s ROM-BIOS to boot from the CD-ROM drive. I completed the installation using the steps noted in Figure 3. IBM USB Camera Sends video to Supplies video feed to IBMCAM USB Driver module July 2010 – Issue 240 18 Runs on Configuration and maintenance tools Executes Configured and maintained by Runs on Webcam server Starts Loads driver CONFIGURE SERVERS First, the computer is set to a static Internet protocol (IP) address and domain name server settings are configured. Second, the Apache web server is installed and configured to host the video stream produced by the webcam server. Third, an HTML file that serves the video stream from the webcam server is configured. The Update Manager must be allowed to download users have a fixed target to connect to the webcam server. In addition, having a registered domain name makes it easier to access your server. If critical security updates that have become available since Ubuntu was released. You need a static IP address so that Startup modules, scripts, and symbolic links Provides webcam video to Runs on Ubuntu 9.04 operating system Runs on Runs on Sends web page to client via Network interface Apache web server Forward client request to Get requests from and send images to Internet Figure 2—This is a context diagram of the components described in the article that make up the Ubuntu webcam system. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com The Newest Products For Your Newest Designs Get Connected Faster. CFP Compliant Ethernet Connectors & Components mouser.com/tycocfpcompliantconnector Molex iPass+™ HSC CXP Interconnect System mouser.com/molexipassplus Ultra Hard Metric (UHM) Backplane Connector www.mouser.com/3muhm USB 3.0 SuperSpeed mouser.com/AmphenolUSB3 WARNING: Designing with Hot, New Products May Cause A Time-to-Market Advantage. Micro USB, Industrial Ethernet, Hard Metric, Fiber Optic, MicroTCA, HDMI, SFP, Mini SAS, SATA, QSFP, SFP+, Displayport get the newest Interconnect products and technologies. Experience Mousers time-to-market advantage with no minimums and same-day shipping of the newest products from more than 400 leading suppliers. mouser.com 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. Personal Download for [email protected] I © Circuit Cellar (800) 346-6873 the computer is turned off and on. If you are creating a web server of any sort, I recommend purchasing a static IP address plan from your ISP and getting a domain name from a domain name registrar. Another alternative is to use a free domain name service that can translate your dynamic address to a fixed domain name that you choose. Since this webcam server is located at my university, I picked an IP address from a pool of static addresses reserved 1. Insert the Ubuntu 9.04 CD ROM and boot computer from the CD ROM 2. Select English 3. Select Install Ubuntu, press Enter a. Wizard Step 1: Select English, click Forward b. Wizard Step 2: Pick your region and city, click Forward c. Wizard Step 3: Pick a keyboard layout (I used Suggested option: USA), click Forward d. Wizard Step 4: Select Use the entire disk, click Forward e. Wizard Step 5: Enter your name, login and password, and computer information. i. Enter your full name: [administrator] ii. Pick a login name: [administrator] iii.Pick your password <enter this twice> iv. Name your computer: [administrator-desktop] v. Click Log In Automatically vi. Click Forward f. Wizard Step 6 is automatically skipped. In Wizard Step 7: Click Install 4. Restart computer: Click Restart Now 5. Remove CD ROM when prompted, and press Enter Fi gure 3—The steps for installing Ubuntu your ISP provides a dynamic IP address (using the dynamic host configuration protocol or DHCP), your server’s IP address could be different every time by our campus network administrator. I also set up the domain search and name server (DNS) look-up information in the webcam server’s resolv.conf file. I received valuable help and advice from the university’s network administrator while setting up domain names for the webcam server. Next, I had to download and install servers. I used Donn Morrison’s webcam-server program to make the video stream available to the Apache web server. Morrison’s Sourceforge.net page provides the webcam_server (notice the underline in the name) program, but that did not recognize my webcam. The webcam-server (notice the hyphen in the name) program (also authored by Morrison) works well with my webcam, and it is the version that is available using the apt-get command in July 2010 – Issue 240 1. Start Terminal: Go to Applications -> Accessories -> Terminal 2. Type sudo -i a. press Enter. b. enter the administrator’s password. 3. Define a static IP address: a. Go to the network directory. Type: cd /etc/network b. Type: pico interfaces c. Modify the interfaces network settings file so the contents of that file looks like listing 1. In our case, we set the static IP address to 10.1.31.241. You must use a different IP address, so consult your Internet Service Provider (ISP) or your network administrator for details about your particular environment. d. Exit pico: CTRL-X, Y(es) to save changes, press Enter to accept filename and exit. 4. Restart the computer. Type: reboot 5. Repeat steps 1 and 2 to use Terminal to get super user access 6. Configure the domain search and name server settings in the resolv.conf file. a. Go to the /etc directory. Type: cd /etc b. Type: pico resolv.conf c. Edit the resolv.conf file so the contents of this file looks like listing 2. In our case, the domain search is lasierra.edu, and our DNS server address is 192.156.214.14. You must use a different address, so consult your Internet Service Provider (ISP) or your network administrator for details about your particular environment. d. Exit pico: CTRL-X, Y(es) to save changes, press Enter to accept filename and exit. 7. Install webcam-server. Type: apt-get install webcam-server 8. Install apache2 server. Type: apt-get install apache2 a. Type Y to continue installation. 9. Install the Java browser plugin. Type: apt-get install icedtea6-plugin a. Type Y to continue installation. 10. Copy webcam server files to apache server directory. Type: cp /usr/share/doc/webcam-server/applet/* /var/www 11. Change to /var/www. Type: cd /var/www 12. Edit webcam.html and change the URL to your IP address; change the frames per second to 5, using listing 3 as reference: a. Type: pico webcam.html b. Look for the phrase http://localhost:88882 and replace “localhost” with the IP address you picked in step 3. For example, if your server’s IP address is 10.1.31.24, change this to http://10.1.31.24:8888 c. Look for the phrase FPS value= “1” and replace “1” with “5”. d. Exit pico: CTRL-X, Y(es) to save changes, press Enter to accept filename and exit. 13. Copy webcam.html to index.html. Type: cp webcam.html index.html 14. Go to the Update Manager a. Click Check to look for new updates. b. Enter the administrator password. c. Click Install Updates 15. Restart computer, click Restart Now 20 1 The webcam server is actually located within a private sub-network; this is why I have a static IP address that starts with “10.” It is normally not possible for offcampus computers to directly connect to any devices in our private sub-network. So, a special public IP address “192.156.214.81” and a domain name of “cswebcam.lasierra.edu” were created by my network administrator to redirect traffic from off-campus machines to the webcam server in our private sub-network. On-campus users must either type the private IP address or use the private domain name “cswebcam.int.lasierra.edu” (notice the .int. in the domain name) to access the webcam server. 2 The webcam-server uses port number 8888 to send the video stream. If the client’s ISP blocks this port, they will get an “Error connecting to the video” message, though the rest of the web page will be visible. Figure 4 —The steps for installing and configuring servers CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Personal Download for [email protected] I © Circuit Cellar Figure 4 (for installing and configuring servers). Morrison’s program provides a simple webcam_server.log file, in the /var/log directory, with connection statistics such as the date, time, and requestor IP address. Apache is used to serve the webcam page containing the video stream. This full-fledged web server is capable of hosting Java applets and even keeping track of website traffic. The access.log file can be used to analyze web traffic. It is found in the /var/log/apache2 directory and details every connection request (including IP address, operating system and version, browser and version, access date and time, which pages were visited) made to the web server during the current week. In addition, it is automatically rotated to access.log.1 at the end of each week. Li sting 1—Contents of the interfaces file, found in /etc/network directory # File path and name: /etc/network/interfaces # Define the loopback interface lo auto lo iface lo inet loopback # Define the interface eth0 with static IP address auto eth0 iface eth0 inet static address 10.1.31.24 netmask 255.255.255.0 network 10.1.31.0 broadcast 10.1.31.255 gateway 10.1.31.1 L isti ng 2 —Contents of the resolv.conf file, found in the /etc directory # File path and name: /etc/resolv.conf search lasierra.edu # Search list for host-name lookup nameserver 192.156.214.14 # IP address of the campus name server July 2010 – Issue 240 L isti ng 3 —Contents of the webcam.html and index.html files, found in the /var/www directory 22 <!--File path and name: /var/www/webcam.html copied to /var/www/index.html --> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Kiki's Webcam</title> <style type="text/css"> html, body, div, iframe { margin:0; padding:0; height:1020; } iframe { display:block; width:100%; border:none; } </style> </head> <body> <table cellspacing="15" width="80%" align="center"> <tr> <tr> <CENTER><H1>Welcome to Kiki's Webcam at La Sierra University!</H1></CENTER> </tr> <td> <APPLET CODE = "WebCamApplet.class" archive="applet.jar" WIDTH = "352" HEIGHT = "240"> <param name=URL value="http://10.1.31.24:8888"> <param name=FPS value="5"> <param name=width value="352"> <param name=height value="240"> </APPLET> </td> <td> Kiki's Webcam runs on Linux Ubuntu 9.0.4, which can be downloaded for free <A HREF="ubuntu-9.04-desktop-i386.iso">here</A>.<P> You can get step-by-step instructions to make an Ubuntu webcam, in <A HREF="UbuntuWebcam.doc">MS-Word format</A> and in <A HREF="UbuntuWebcam.pdf">PDF format</A>.<P> The computer that runs Kiki's Webcam was donated by Craig Kinzer, alumnus of the <A HREF="http://www.lasierra.edu/cs">Math & Computer Science</A> department.<P> This webcam display, and the Ubuntu webcam setup instructions were created and written by <A HREF="http://www.lasierra.edu/~dlin">Denny Lin</A>, Assistant Professor of Computer Science. </td></tr> </table> <div> <iframe src="http://10.1.31.23" height="1020" width="100%"> <p><a href="http://10.1.31.23">Kiki Cam</a></p> </iframe> </div> </body> </html> CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com What is the missing component? Electronics instructor Ollie Circuits planned to show his class of freshman electrical engineering students how to use a super capacitor as a memory back-up capacitor, but first he wanted to show how the students could make their own super capacitor and demonstrate its charge/discharge cycles with the simple circuit above. Most of the components were already on his workbench, the homemade super capacitor would be made from several layers of lemon juice-soaked paper towels interleaved between several layers of a mystery material to form a multi-layer stack.The stacked layers would then be sandwiched between the two copper-clad PC boards and held together with a rubber band. Ollie rushed to a nearby pet shop. What did he buy? Go to www.Jameco.com/teaser7 to see if you are correct and while you are there, sign-up for our free full-color catalog. 1-800-831-4242 | www.Jameco.com Personal Download for [email protected] I © Circuit Cellar 1. Start Terminal: Go to Applications -> Accessories -> Terminal 2. Type sudo -i a. press Enter b. enter the administrator’s password. 3. Change to the etcetera directory. Type: cd /etc 4. Type: pico modules 5. Listing 4 is the /etc/modules file, which loads the ibmcam module. Make sure the contents of the options following ibmcam are on a single line. 6. Change to the startup directory. Type: cd /etc/init.d 7. Type: pico webcam_server 8. Create the startup script by typing the contents of listing 5. 9. Exit pico: CTRL-X, Y(es) to save changes, press Enter to accept filename and exit. 10. Grant execute permission to the file you created. Type: chmod 755 webcam_server 11. Define a symbolic link so the script is automatically executed when the computer starts. Type: update-rc.d webcam_server defaults 24 12. Restart the computer. Type: reboot July 2010 – Issue 240 Fi gure 5 —The steps to configure automatic start-up scripts 24 the word “localhost” with the server’s asked for the administrator’s password Older files are automatically comstatic IP address. Then, the frames per before updates were installed, and I was pressed and saved as access.log.n.gz, second (FPS) setting was increased from prompted to restart the computer for where the number n is two or larger for 1 to 5. I picked a value which would the updates to take effect. older files. not burden the server with a too-high Regarding the static IP address to Next, I downloaded and installed the frame rate, but would still allow the 10.1.31.24 in Figure 4, note that the Java browser plugin. (Windows and OS X user to observe the motion of Kiki beatwebcam server is actually located withcan run Java applets without this Java ing her drum. Finally, for testing, I in a private sub-network. This is why I plugin, so step 9 in Figure 4 for entered http://10.1.31.24/webcam.html have a static IP address that starts with installing and configuring servers is “10.” It is normally not possible for arguably optional.) The video stream into a browser running on a different hosted by the webcam server is a Java computer and modified the webcam.html off-campus computers to directly connect to any devices in our private subapplet that runs within the web browsfile on the server until I got the network. So, a special public IP address er. In order to view the video stream desired results. “192.156.214.81” and a domain name while using the server’s web browser, I Once I was satisfied with the webof “cswebcam.lasierra.edu” were creatinstalled the Iced Tea 6 Java plugin. cam.html file, I copied it to ed by my network administrator to This project aimed not only to show index.html, the default file that is redirect traffic from off-campus video images of Kiki, but also to allow automatically displayed whenever a machines to the webcam server in our users to control Kiki. The webcam-servuser types the IP address or the domain private sub-network. On-campus users er package provides a default web page name of the webcam server into a (named webcam.html) that serves a sim- browser: http://10.1.31.24 (notice there must either type the private IP ple video stream. I made several changes is no /index.html after the IP address). address, or use the private domain to this file so that it is seamlessly I then ran Update Manager. This tool name “cswebcam.int.lasierra.edu” linked to Kiki’s controller web page lists patches and updates that keep the (notice the .int. in the domain name) (served by a stand-alone Altera Nios server current and protected from vulto access the webcam server. board) while serving the video stream. I nerabilities. Ubuntu automatically runs As for the note regarding the phrase used inline frame tags to seamlessly the Update Manager to look for and http://localhost:8888 in Figure 4, the link Kiki’s controller web page to the install updates (step 14 in Figure 4 for webcam-server uses port number 8888 video stream in the webcam.html page, installing and configuring servers). I was to send the video stream. If the client’s so there are no wires that directly connect the webLi sting 4—Contents of the modules file, found in the /etc directory cam server to Kiki’s controller web page. Since I # File path and name: /etc/modules wanted to turn this webibmcam init_hue=96 init_color=250 init_brightness=48 init_contrast=110 lighting=0 site into a teaching tool, init_model2_yb=170 init_model2_sat=28 links to the step-by-step # Loads the ibmcam module (driver) upon startup instructions for creating # All of the numbers have a range from 0 to 255: # The initial hue set is 96 this webcam server were # The initial color is set to 250 posted in index.html. # The initial brightness is set to 48 Clearly, your circum# The initial contrast is set to 110 stances will vary, so # The lighting (photosensitivity of camera) is set to type 0 # The init_model2_yb parameter adjusts color balance, and is set to 170 adding inline frame tags, # The init_model2_sat parameter adusts the saturation, and is set to 28 for example, may not apply to your project. # More information about options for the ibmcam module can be found here: I first edited # http://www.mjmwired.net/kernel/Documentation/video4linux/ibmcam.txt webcam.html by replacing CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Listi ng 5 —Contents of the webcam_server file, found in the /etc/init.d directory #!/bin/sh # File path and name: /etc/init.d/webcam_server # The first two characters in this file MUST be a number and an exclamation mark, because # they tell the operating system that this is a script, to be executed by the Bourne shell # interpreter found in /bin/sh webcam-server -s -c " Kiki The Monkey %D %H:%M:%S Viewers: %%v" # The -s option starts the webcam-server in daemon mode # The -c option defines the caption to be displayed: # %D inserts the system date # %H inserts the current hour from system time # %M inserts the current minute from system time # %S inserts the current seconds from system time # %%v inserts the number of connected viewers to the webcam-server ISP blocks this port, they will get an “Error connecting to the video” message, although the rest of the webpage will be visible. Listing 1 shows the content of the interfaces file found in /etc/network directory. Listing 2 shows the content of the resolv.conf file found in the /etc directory. Listing 3 shows the content of the webcam.html and index.html files found in the /var/www directory. This step lists the IBM PC camera driver in the modules file, so the driver is loaded when the server starts up. In addition, this step creates a startup script that launches the webcam server in daemon mode. Instructions to configure automatic startup scripts are listed in Figure 5. During start-up, Ubuntu loads drivers listed in the modules file. The ibmcam module allows the IBM PC camera to send its images to the /dev/video0 device. I found that when the module was loaded without any options, the images appeared overexposed; under minimal light, the image had a greenish tinge. I came across a website describing the options available for adjusting the video signal. I spent several hours of trial-and-error testing to figure out the best combination of settings for initial hue, color, brightness, contrast, and lighting. Subtle changes in lighting require different adjustments, so be patient while trying different settings. I named the webcam server startup script “webcam_server” in order to differentiate it from the executable file (which contains a hyphen instead of an www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 START-UP SCRIPTS 25 July 2010 – Issue 240 26 underline). All of the Li sting 6—Listings of the /etc/rc2.d and /etc/rc0.d directories options for the webcamserver program can be >ls /etc/rc2.d README S20hotkey-setup S50rsync S90binfmt-support viewed by typing “webS01policykit S24hal S50saned S91apache2 cam-server –h” in a termiS10acpid S24webcam_server S50system-tools-backends S98usplash nal window. I only needed S10apmd S25bluetooth S70bootlogs.sh S99acpi-support two options for my setup. S10sysklogd S30gdm S70dns-clean S99laptop-mode S11klogd S50avahi-daemon S70pppd-dns S99ondemand The -s option was used to S12dbus S50cups S89anacron S99rc.local launch the server in daeS16ssh S50NetworkManager S89atd S99rmnologin mon mode, so its execuS20apport S50pulseaudio S89cron S99stop-readahead tion is not tied to a termi>ls /etc/rc0.d nal session. The -c option K01gdm K63mountoverflowtmp S30urandom defined the caption that K02usplash K74bluetooth S31umountnfs.sh identifies the video and K09apache2 K99laptop-mode S35networking shows the date, time, and K20apport README S40umountfs K24webcam_server S01linux-restricted-modules-common S60umountroot number of users connected. K25hwclock.sh S15wpa-ifupdown S90halt The webcam_server K50alsa-utils S20sendsigs startup script is kept in the /etc/init.d directory; it’s made executable by using the chmod command in step sequence, remove the symbolic links. First, type: 10 in Figure 5 (for configuring automatic start-up scripts). It “update-rc.d - f webcam_server remove.” Then reissue the turns out that the order for executing this script is very update-rc.d command in step 11 from Figure 5 (for configurimportant. The Ubuntu Hardware Abstraction Layer must ing automatic start-up scripts) to establish a symbolic link. be started before the webcam_server script. Listing 4 shows the content of the modules file found in the Most users will run their Linux desktops at run level 2, 3, /etc directory. Listing 5 shows content of the webcam_server 4, or 5, which are multi-user modes. By default, Ubuntu uses file found in the /etc/init.d directory. Listing 6 shows the conrun level 2. Run levels 0 and 6 are used to kill processes durtent of the /etc/rc2.d and the /etc/rc0.d directories, produced ing system shutdown or reboot, while run level 1 is used by the ls command displayed at the top of each list. when Ubuntu is in single-user mode. Each run level has a Let’s move on to the topics of setting up the remote desktop matching control directory that contains executable symboland firewall. Both are optional. ic links to services that are started or ended during startup, shutdown, or reboot. Thus, for run level 2, the symbolic REMOTE DESKTOP SETUP links are in /etc/rc2.d, while the symbolic links for run level Remote Desktop is a virtual network computing (VNC) 0 are stored in /etc/rc0.d. These symbolic links are identified server program that runs on the webcam server, allowing by the initial letter S to start processes, or with the initial remote control of the server through a VNC client viewer. letter K to kill processes. The computer in our display case is not connected to a The number after the letter S of every symbolic link monitor, but VNC allows me to see what the webcam server denotes the order in which those services are started. Since is displaying. While I can and do use a secure shell terminal the webcam_server must be started after the hardware emulator program (PuTTY) to quickly access the server, abstraction layer (HAL), its number should be equal to or VNC provides access to Ubuntu’s GUI desktop environment. greater than the number for the HAL service (labeled as VNC is platform-independent, so any computer running a S24hal). There should be S24webcam_server links in the VNC client can be used to control your webcam server. You /etc/rc2.d, /etc/rc3.d, /etc/rc4.d, and /etc/rc5.d directories. For can download the “VNC Free Edition for Windows” if you wish to control the webcam server from a Windows PC. Try run levels 0, 1, and 6, there are symbolic links that start with “Chicken of the VNC” if you wish to control the webcam K, which kill processes during shutdown, single-user mode, server from a Macintosh. Refer to the resources listed at the or reboot. There should be K24webcam_server links in the end of this article for more information. /etc/rc0.d, /etc/rc1.d, and /etc/rc6.d directories. These startTo connect to your webcam server through the VNC up and shutdown symbolic links were created using the client, enter the IP address of the webcam server and the update-rc.d command in step 11 (for configuring automatic password chosen in step 2 of Figure 6 (to set up Remote startup scripts) shown in Figure 5. Desktop). Pick a secure password that is at least eight charIf you need to change the start-up or shutdown acters long. Set up the VNC server pro1. Start Remote Desktop. Go to System -> Preferences -> Remote Desktop 2. On the Remote Desktop Preferences dialog box: gram so that authorized users a. Check the “Allow other users to view your desktop” and “Allow other users to control your computer” checkboxes. can view and control your b. Un-check the “You must confirm each access to this machine” checkbox. c. Check the “Require the user to enter this password” checkbox, and enter a secure password. computer, and remove the d. Click Close requirement to confirm each Figure 6—The steps to set up Remote Desktop access to the webcam server. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com 1. Start Terminal: Go to Applications -> Accessories -> Terminal 2. Type: sudo -i a. press Enter b. enter the administrator’s password. 3. Check the ufw status. Type: ufw status (you should get a Status: inactive) 4. Set ufw to deny all connections by default. Type: ufw default deny 5. Allow browser traffic. Type: ufw allow 80 6. Allow secure shell traffic. Type: ufw allow ssh 7. Allow webcam traffic. Type: ufw allow 8888 8. Allow remote desktop traffic. Type: ufw allow 5900 9. Enable ufw. Type: ufw enable 10. View the status of the firewall, and list ports you have opened. Type ufw status 11. Restart the computer. Type: reboot Figure 7—The steps to set up the firewall D. Morrison, Webcam Server Project, http://webcamserver.sourceforge.net/. IBM C-it USB Camera Driver FAQ, www.linux-usb.org/ ibmcam/ibmcamFAQ.html. IBM C-it USB Camera Driver for Linux, www.linuxusb.org/ibmcam/. Official Ubuntu Documentation, https://help.ubuntu. com/. PuTTY: A Free Telnet/SSH Client, www.chiark.green end.org.uk/~sgtatham/putty/. During set-up, I kept a monitor connected to the webcam server while connecting from a remote VNC client to make sure that my remote computer could display the same images as the webcam server’s monitor. README for the Linux device driver for the IBM CIt USB Video Camera, www.mjmwired.net/kernel/ Documentation/video4linux/ibmcam.txt. RealVnc, www.realvnc.com. Ubuntu’s uncomplicated firewall (ufw) front-end program easily removes avenues used by hackers to attack your server. I shut off all network ports to the webcam server and then reopened just the ports the server requires to provide its services. Port 80 must be open to serve web pages. Port 8888 must be open to allow the webcam-server software to stream video. I opened port 22 (ssh) to allow secure shell terminal emulator access. Port 5900 was opened to allow Remote Desktop (the VNC server) to connect. Figure 7 is a list of the steps associated with setting up the firewall. DESIGN SUCCESS This project taught me a lot about setting up an Ubuntu server and interfacing it with a USB camera. And now it serves to inspire curiosity and excitement about computer technology in our department’s display case. Each day, curious students are lured to the display because of the attractive lights on the server and Kiki’s drumming. One student called his father, who lives several hundred miles away, to watch and control Kiki with the webcam server. You too can connect to the webcam server and control Kiki at http://cswebcam.lasierra.edu. I Denny Lin ([email protected]) has a BA in Music and a BS and an MSc in Computer Science. He is an Assistant Professor of Computer Science and a Senior Programmer/Systems Analyst at La Sierra University. Besides teaching C++ Programming, Software Engineering, and Systems Analysis courses, Denny also teaches Computer Music Synthesis courses in the Music Department and Electronics in the Physics Department. Ubuntu 9.04 (Jaunty Jackalope), http://releases.ubuntu. com/jaunty/ubuntu-9.04-desktop-i386.iso. SOURCES Nios embedded processor Altera | www.altera.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 Denny Lin’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — Build Your Own 8051 Web Server by Jim Brady Circuit Cellar 146, 2002 Building a web server doesn’t have to be difficult. Jim built an 8051 server and describes the project in this article. Topics: Web Server, TCP/IP, Ethernet Chicken of the VNC, http://sourceforge.net/projects/cotvnc/. Go to: www.circuitcellar.com/magazine/146toc.htm — Web Camera Design by Minas Kalarakis Circuit Cellar 228, 2009 This versatile web camera system can take pictures, pan a camera, and change its IP and gateway address to match a network. An Ethernet module transmits the packets over the Internet. Topics: Webcam, Servo, Ethernet, Packet Transmission Dynamic Network Services, www.dyndns.com/. Go to: www.circuitcellar.com/magazine/228.html RESOURCES www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 FIREWALL SETUP 27 F EATURE ARTICLE by Devlin Gualtieri (USA) Build an X10 Controller (Part 1) Circuit Design This article series details the process of building an X10 controller from start to finish. Here you learn about the circuit design before moving on to the software. B ack in the 1980s, I combined my interest in carrier-current communication technology and embedded systems to design my first timed automatic control system. The design featured a Zilog Z80 microprocessor and a carrier-current transmitter that I built myself. Three decades later, I still find myself rethinking my first design. But now I have a lot more experience under my belt and new technologies to put into play. In this article series, I’ll describe my original X10 controller and then present my newest design. This article covers the circuitry (see Photo 1). Next month, I’ll describe the software side of the project. When I went off to college, I saw that the same trick was used by the campus radio station. It had transmitters on the AM broadcast band coupled to the power lines in each of the dormitories. In that way, a low-power signal, legal under the FCC Part 15 rules, could reach a large audience. It was still done using vacuum tubes. Carrier-current communication didn’t enter my mind again until I was a homeowner in the early 1980s wrestling July 2010 – Issue 240 CARRIER CURRENT 28 When I was a grammar-school student, my parents had what I considered a magical device in their kitchen. It was an intercom that allowed them to talk with our next-door neighbor who had an identical unit. The amazing part about these intercoms was that there were no wires connecting the devices. They just plugged into an electrical outlet. Later, when I was in high school and more familiar with electronics, I realized that they were carrier-current devices. They had a low-frequency amplitude-modulated transmitter and a complementary AM receiver. The transmitter signals were injected into the power lines, and that’s how they traveled between houses. Everything was done using vacuum tubes because it was the 1960s at the time. Photo 1—The finished controller. The ICSP connector is visible at the bottom of the board. The back-up lithium cell, in a home-built battery holder made from a small plastic bottle and some switch parts, is at the lower right. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 with the unreliable mechanwith the zero crossings of the 8.333 ical timers I was using to AC line, they’re able to exam5.556 control the exterior lighting ine the proper time interval at my home. At about the to determine the presence or 2.778 same time, the X10 system absence of this signal. The 1 hit the stores. X10 is a carripresence of 120 kHz at the er-current system that appointed time is interpretallows control of lights and ed as a logical one, and its appliances. It’s a nicely inteabsence is a logical zero. 1 grated system of modules Only a single bit is trans2.778 that replaces the light mitted at each zero crossswitches and utility outlets ing. The data protocol calls 5.556 in your house. These modfor a 4-bit preamble, fol8.333 ules have the same function lowed by an 8-bit house as the switches and outlets code and a 10-bit device Figure 1 —Timing in milliseconds of the carrier-current signal for they replace, but they number or function code. X10 communication. The data is transmitted as 1-ms bursts of a include remote switching The 8-bit house code is actu120-kHz carrier synchronized with the zero crossings of the 60-Hz voltage sine wave. Each bit is transmitted redundantly three times circuitry. I was able to purally just four bits of informain a half cycle. chase these X10 devices tion, but each bit is followed with a companion control by its complement. If a logibox that injected carrier-current sigcal one is transmitted on one zero specifications, and I was able to build nals into the power lines to turn crossing, a logical zero is transmitted a reliable X10 controller using 1980slights on and off, brighten and dim on the next. The same is true for the era technology. lights, and turn appliances on and off. device number/function code. It’s just All this was nice when I was present five bits alternated with their compleTHE X10 SYSTEM to push the buttons on the control ments. Figure 2 summarizes the transThe X10 signal, as shown in Figure 1, box, but I wanted a timed automaticmission protocol. Table 1 shows the is a pulsed 120-kHz oscillator that’s control system. I was doing embedded binary values of the house codes and synchronized with the zero crossing systems work in the same period, so I device codes. Table 2 shows the binary of the AC power line. The X10 innohad the tools to roll my own concommand codes. The preamble, which vation, which made it a patentable troller. In those days, this was no sim- idea, was this synchronization of the is not interleaved with its complemenple task. An embedded system tary bits, is always 1110. Since it has datastream with the AC power line involved a Z80 microprocessor, a mul- zero crossings. The receiver modules three logical one bits in series, it can’t titude of peripheral chips, an ultraviobe confused with the home or know when to look for data, and this let-light-erasable EPROM burned with leads to noise immunity and device/function data. an assembly language program, and a enhanced reliability. The transmitter few kilobytes of static RAM with a accommodates the existence of INTO MODERNITY hefty NiCd battery backup. receivers on any of three possible My original X10 controller had an There was another problem. I needphases of the AC line by transmitting event table that was updated by a ed to design and build my own carriredundant signals at times where the serial data link, so it survived my er-current transmitter to mimic the zero crossings at these other phases transition from an early CP/M comX10 signals. These were the days would occur. puter system to an MS-DOS computbefore the Internet. But fortunately, The data signals are transmitted in er. After a time, computers became some hobby magazines published short bursts of the 120-kHz oscillator. ubiquitous enough for manufacturers information about the X10 signal Since the receivers are synchronized to notice, and an X10 controller with a similar serial access became available. This controller was the CP290, which came with a 1 2 3 4 5 6 7 8 9 10 11 simple DOS program for programming events and enough H1 * H1 H2 * H2 H4 * H4 H8 * H8 D1 * D1 D2 * D2 D4 * D4 D8 * D8 D16 * D16 Preamble information for programmers to 1 1 1 0 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 0 1 roll their own advanced serial interface. I purchased a CP290 “Start” code and retired my Z80 controller, Device code “7” House code “A” 1110 01010 0110 which was still operating after many years of service. More Figure 2—The data format of an X10 command. A command requires 11 full cycles of the power than ten years ago, I migrated line. After the transmission of the start code, the data bits and their complements are transmitted on successive half cycles of the AC voltage sine wave. from Windows computers to 29 Code M N O P C D A B E F G H K L I J H8 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 H4 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 H2 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 H1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Device 13 14 15 16 3 4 1 2 5 6 7 8 11 12 9 10 D16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 D8 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 D4 0 0 0 1 0 1 1 1 0 0 0 0 1 1 1 1 D2 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 D1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Table 1—The house codes and device codes are listed in order of ascending binary values. ! New $99 OSD-232+ RS-232/TTL controlled on-screen composite video character and graphic overlay in a small 28 pin dip package. July 2010 – Issue 240 Intuitive Circuits www.icircuits.com (248) 588-4400 30 Linux—first Red Hat, then Gentoo, and now Ubuntu. I happily migrated nearly all my tools to Linux, but I still needed to keep a DOS diskette with the CP290 control program on it. I dutifully booted from this diskette once each month to update the CP290 event table with new times. Several years ago, my CP290 started to do strange things. It started to turn on lights at odd times. A dump of the on-board memory showed that it was corrupted, a fact that I attributed to an exhausted back-up battery, which I replaced. The problems were solved for a few months, but they reappeared. The back-up battery was again exhausted, which led me to suspect that the CP290 power supply wasn’t putting out its rated voltage. As is usual for equipment that’s been operating continuously for many years, the electrolytic capacitor in the power supply had gone bad. It was a simple fix, but I started thinking of how I would use today’s technology to build another X10 controller. PL513 & EMBEDDED MCUs Controlling X10 devices is simpler now, since you don’t need to build your own carrier-current transmitter. The PL513, shown in Photo 2, is an X10 carrier-current transmitter module that’s available from many sources for less than $20. The PL513 has circuitry that converts power line zero crossings to a logic signal, and it accepts a logic signal to activate a 120-kHz carrier-current transmitter. Using the PL513 lets you safely interface with the AC power line. It’s a well-designed circuit that has optical isolation between itself and your circuitry. One of its claimed benefits is that it enables you to use the X10 system commercially without infringing on any of the X10 patents. This may have been true in the past, but the fundamental X10 patents (4,200,862, 4,628,440, and 4,638,299) have now expired. However, it would be Command D16 D8 D4 D2 D1 hard to duplicate the All devices off 1 0 0 0 0 PL513 for $20, so Dim 1 0 0 1 0 that’s not recommendOn 1 0 1 0 0 ed. The only problem All lights off 1 0 1 1 0 with the PL513 is that All lights on 1 1 0 0 0 it’s supplied without a Bright 1 1 0 1 0 mating connector or Off 1 1 1 0 0 cable, but more on that later. There is a Table 2 —The command codes are listed in order of ascending similar X10 module, binary value. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com appealing to hobbyists because of the availability of free software tools and the fact that these tools will run under Linux. I’ve been using the PIC microcontrollers with the PICBasic Pro compiler for many years, so I used what was familiar. PICBasic Pro has built-in statements for X10 control, which makes for easy programming. CONTROLLER HARDWARE Photo 2 —The PL513 X10 carrier-current transmitter module the TW523, which both sends and receives X10 signals. This would be useful for an alarm-type system, but it wasn’t needed in my home system. It might be worthwhile buying the TW523 instead of the PL513, since it contains the PL513 circuitry and it would allow a future alarm system feature. The TW523 is just a little more expensive. Today’s designer has a choice of many microcontrollers, most of which are more than adequate for a simple task such as an X10 controller. The Arduino system, which uses an Atmel chip, is especially Figure 3 and Figure 4 are schematics of the X10 controller. A PCB layout and parts placement guide are available online. Since I often etch my own circuit boards, this board is laid out as single-sided with a few necessary jumper wires. Through-hole parts are used, since surface-mounted components don’t make sense for a one-off board built by a hobbyist. The Microchip Technology PIC16F877 microcontroller I used has a built-in hardware USART for the serial interface, another feature that makes the programming easier. The PIC16F877 is a 40-pin DIP package, which might appear overkill for this application. EMBEDDED SERVER Standard SIB (Server-In-a-Box) Starting at $305 Quantity 1. Since 1985 2.6 KERNEL ! Power Supply Included ! Locked Compact Flash Access ! Analog SVGA 3D Video ! Optional Wireless LAN ! EMAC Linux 2.6 Kernel ! XP Embedded & WinCE 6.0 www.emacinc.com/servers/standard_sib.htm OVER 25 YEARS OF SINGLE BOARD SOLUTIONS Phone: (618) 529-4525 · Fax: (618) 457-0110 · www.emacinc.com www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 ! Fanless x86 500MHz/1GHz CPU ! 512MB/1GB DDR2 RAM On Board ! 4GB Compact Flash Disk ! 10/100 Base-T Ethernet ! Reliable (No CPU Fan or Disk Drive) ! Two RS-232 Ports ! Four USB 2.0 Ports ! Audio In / Out ! Dimensions: 4.9 x 4.7 x 1.7” (125 x 120 x 44mm) 31 Figure 3 —This is a schematic of the X10 controller showing the PIC16F877 microcontroller and most of the peripheral circuitry. I had a few of them in my surplus parts drawer—a design decision known to all designers. The PIC16F877A is slightly different from the PIC16F877. It has a comparator option for some input pins, but this feature is disabled at power up to make it code-compatible with the PIC16F877. I used a 20-MHz chip, since high clock speeds are July 2010 – Issue 240 Aside from its hardware USART feature, it has other redeeming features. There are its 256 bytes of EEPROM for storing events, a large data and code memory, and, most importantly, 32 CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com always good when doing serial communication. The clock signal in this design is derived from an oscillator, not a crystal or ceramic resonator, but those can be used instead since the precision of the timebase is not that important. The processor configuration data needs to specify the timebase type when programming the device. There’s an in-circuit serial programming (ICSP) connector on board, which is nearly essential for program development when high-pincount chips are used. Repeatedly removing such chips to program them in an external programmer would be possible only if a zeroinsertion-force (ZIF) socket is used. Such sockets are expensive and they take up a lot of board space. Every controller for real-time events needs a real-time clock. The PIC16F877 has enough horsepower to act as its own real-time clock, and the AC power line zero-crossing signal from the PL513 would make an excellent timebase. However, battery backup for timekeeping during power outages would be a problem, so I chose a standalone real-time clock chip, the Maxim DS1307. The DS1307 is inexpensive, it communicates using an I2C serial connection, and PICBasic Pro has built-in I2C commands. The clock chip handles its own battery back-up with a 3-V lithium cell. The serial data link is buffered by the usual MAX232 chip that provides the bipolar voltage signals that an RS-232 serial port expects. Of course, many computers now eschew such serial ports, but there are many USB-to-RS232 converters on the market that 2 3 solve this problem. I use a few transistors for driving external LEDs and the PL513. The PL513 driver circuitry is similar to that 4 Figure 5—The connections to the PL513 X10 carrier-current transmitter module www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 1 Figure 4—This schematic of the X10 controller shows the MAX232 serial interface and the voltage regulator. Although the voltage regulator accepts a 12-V input, a 9-V input is acceptable, and it allows for greater energy efficiency. The controller draws about 35 mA in its quiescent state, about 70 mA when an X10 command is being sent, and a maximum current of less than 100 mA. recommended by the manufacturer. I made a small change to preserve signal polarity on the output driver to maintain compatibility with the PICBasic Pro X10 commands. The output driver as published by the manufacturer inverts the data signal. The drivers have diode protection circuitry to prevent damage from voltage spikes. It is possible to drive LEDs directly from the PIC pins, but I never like that approach. I like bright LEDs, which translates to a lot of drive current, and a microcontroller shouldn’t be too abused. One LED is used to indicate whenever an X10 signal is being transmitted, and the other indicates that the back-up battery is still good. Either or both of these LEDs and their associated components can be eliminated at no real loss of functionality, although there’s another function of the transmit LED. If the connection from the controller to the PL513 is broken, the LED will remain lit when a command is attempted but no power line zero crossings are detected. One 33 advantage of the PIC microcontroller is the availability of analog-to-digital conversion on some pins. For the PIC16F877, this is a 10-bit conversion that has plenty of resolution for most applications. The PICBasic Pro compiler has commands that simplify handling analog input. Since I had an overabundance of input pins, I decided to use one of them to monitor the back-up battery voltage. The Maxim datasheet specifies a nominal 3-V lithium cell and recommends a backup battery voltage of between 2.0 and 3.5 V. It would be nice to continually monitor the battery voltage to give an indication of when the backup battery is reaching its end of life, but there’s a problem here. Maxim says that a back-up battery will last for 10 years, so attempts to monitor the battery voltage will actually reduce the battery lifetime, even if the monitor impedance is several megohms! I’ve taken the approach of using a removable jumper to one of the PIC analog inputs so the battery can be checked occasionally without a voltmeter. In normal operation, the jumper is removed so that the battery is not unnecessarily drained. A front panel push button can be used instead of the jumper, and a push button with an integrated LED would be ideal. Because of the availability of many input pins, I used jumpers to set the house code. The house code also can be set with software at the loss of one event location in the event table in EEPROM. However, the house code is rarely changed once it’s set, so the jumper approach is not a problem. One house code allows control of 16 devices. If you have a large house that needs more devices, you could modify the software to include different house codes in the event table, but the number of possible events in the table would be reduced because of the extra storage requirement. Photo 1 is the finished circuit. The ICSP connector is visible at the bottom of the board. The power source is a regulated 9-V wall transformer. It’s one that stands vertically, so it can be plugged into the same outlet as the PL513. You could probably build the PL513 and power supply into your controller box so it can use a single plug connection to a wall outlet. July 2010 – Issue 240 CONNECTIONS 34 The connector on the PL513 mates with those old telephone and modem cables you have at the bottom of a drawer somewhere, but they’re not going to work. Although the connectors have four pins, inexpensive telephone cables typically contain just two or three wires. The PL513 requires four wires. I found that handset cords, the coiled cords that connect old-style telephone handsets to the telephone body, use all four wires. Telephone cables purchased at home improvement stores usually have four wires, and I used one of these for connection to the PL513. The mating jack for the controller side is available at nearly every home improvement store. Figure 5 shows the PL513 connections. The TW523 connections are the same, except that pin 3 is an open-collector output for received signals. If you aren’t using this signal, this pin can be grounded to maintain compatibility with the PL513 connection at the controller. THE PROGRAM AHEAD In Part 2 of this article series, I’ll review the controller program and a utility I wrote to convert a human-readable event file to the serial data the X10 controller understands. The utility is written in ANSI C, so it compiles and executes under both Linux and Windows. Executables will be provided for those of you without compilers. I Devlin Gualtieri received a PhD in Solid-State Science from Syracuse University in 1974 and worked for many years doing research for a major aerospace company. Now retired, he spends his time doing various embedded systems projects. He can be reached at [email protected]. PROJECT FILES To download the code, go to ftp://ftp.circuitcellar.com/ pub/Circuit_Cellar/2010/240. SOURCES PIC16F877 Microcontroller Microchip Technology, Inc. | www.microchip.com PL513 X10 Module X-10 (USA), Inc. | www.x10.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 Devlin Gualtieri’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — XTstat A Portable Wireless X10 Thermostat by Henry Jacobs Circuit Cellar 175, 2005 Henry’s XTstat wireless thermostat allows you to adjust a room’s temperature. The PIC-based device is a great starting point for wireless temperature control projects. Topics: X10, Wireless Communication, RF Go to: www.circuitcellar.com/magazine/175toc.htm — Radio Riot by Tom Cantrell Circuit Cellar 167, 2004 Going wireless doesn’t need to be difficult. Tom has the scoop on several essential wireless solutions. Topics: Wireless, RFID, ZigBee, Bluetooth, IEEE 802.15.4, Spread Spectrum Go to: www.circuitcellar.com/magazine/167toc.htm CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com UNIQUE PRODUCTS & SUPPORT www.saelig.com event-time or pulse-counting data Standalone USB temp / hum / volt / current loop data logger. $57+ FTDI USB ICs CAN-USB FT232RL USBI2CIO L Pr owe ic st es USB to I2C Mini-logger with built-in temp/hum/ pressure/3-axis accel sensors. without a PC! No drivers needed. Versitile Function/Arbitrary/Pulse Generator offering precise waveform control demanded by engineers. Serial-Ethernet Cable Lorlin Switches Connect any SD slot (phones/PDAs) to a USB memory stick. Send files Network serial product easily without Keyboard Simulator Instant Ethernet Ethernet-IO FPGA Systems FEZ Domino / FEZ Mini Tiny open source boards using USBizi chipset: Kits $98 Compact, economical smart OLED with graphics drive from USB or RS232. CGR-101 www.saelig.com Mention offer# SBW Sound Module Temp/RH Sensors RTG005 Ether-IO 24 transducers with integral electronics. Wireless Solutions Analog input, bluetooth wireless modules 433/868/915MHz. RF Modules RS232 to 422/485 9p-9p or 25p-25p self-pwrd, isolated RS232-RS422/485 non-contact SAW digital rotary torque 14-pin module plays back prestored audio files from microSD card designs for beginners and experts! Simultaneously transmit composite video and stereo audio signals. Configurable, patented USB-output Fantastic array of stock and custom switching devices. Novel ambient sensors & modules accurately measure temp/RH. USB-Serial 1/2/4/8/16 x RS232 KK Systems Easy OLED Display $89 Ready-to-go out-of-the-box FPGA/DSP AWM6XX TX/RX .NET Board a PC using this 28” cable. UDP/IP-controlled 24 digital I/O board 3 x 8-bit TTL ports. uOLED-96-G1 No OS needed. TCP/IP offload, ICs improve system performance. WIZ110SR / W5100 Intelligent CAN connection from PC’s USB port. $299 PoKeys55T Popular UART and FIFO chips. Upgrade Legacy designs to USB. 10-bit A/D inputs, 1 x 10-bit analog O/P. PS9200 TorqSense RF Testing / EMI Tents 50MHz AWG RWT320 SD to USB Adapter “Drop-in” solution connects PC to I2C/SMBUS + 32 I/O lines. $89 USB board adds 55 I/O and 5 x APSIN6000 Portable RF test enclosures & shielding tents with external frame. SOMO-14D MSR145S RTR-50 Log and display temp, hum, volt, High-res, extremely low-noise, portable 6GHz RF generator. Add 1-16 COMports via your PC’s USB Port easily. UPSICAP / DLP-TH1 USB Loggers Multiparameter Loggers CANbus, Ehternet, USB2.0, CF. Embedded controller series: 2 x CE-USB Kits turn your PC into vehicleelectrics diagnostic tool. ! exerciser and analyzer. RF Testing/EMI Tents TG5011 Versatile USB 2.0 I2C protocol or arbitrary waveform generator. RF Generator EW I2C Xpress Wave Xpress USB2.0 speed 16-bit digital pattern CANminiBOX 2-ch 12GHz sampling scope for high-speed electrical signals. N Automotive Testing Handheld Palm PC-based 2.7GHz Spectrum Analyzer. Lorlin I2C Xpress RF & EMF Spectrum Analyzer 1Hz to 7GHz for WiFi, mikes, etc. While supplies last - not available with any other offers Worlds’s Fastest EmbedRF / Adeunis Protocol exerciser/analyzer for standard SPI and non-standard 4-wire and 3-wire serial protocol interfaces up to 50 Mbps. to get a free Starbucks Card with your >$50 order! EMC Spectrum Analyzer emPC-x133 Intuitive full-featured 16-ch 4MB 200MHz sampling memory. $240 12/16 input 1kS/s 10/12-bit PC-connected voltage logger. PL1012 / PL1216 EMC Spectrum Analyzer FREE COFFEE Call 1-888-772-3544 PSA2701T SPI Bus Analyzer SPI Xpress 16-Ch Logic Analyzer Waveform Generator Wireless Data Loggers CS328 Mephisto Analyzer and Signal Generator. $1259+ Compact compressed-serial output camera module for any host system. LAD-16128U 100MHz Scope, + Spectrum/Logic Alan Lowne Saelig CEO Multichannel DAQ eCOV-110-P $699 + 2-ch DSO 16-bit DSO, FFT, VM, logic analyzer, standalone + 24 I/O. PS3423 / KLARI-MOD analyzers and generators. microCAM EL-USB-1/2/3/4 Packet-Master™ - USB 1.1/2.0 Ethernet/3xUSB/SD. Mixed-Signal Scopes PS2203/4/5 B Va es lu t e USB Bus Analyzers USB12 / 480+ / 500AG 2-ch 40/100/200MS/s 8-bit scope range with 5/10/25MHz. $246 + Windows PC. LX800/512MB/4GB/ “I really like this scope adapter - it’s meant for teaching electronic experiments but it’s ideal for engineers too.” USB-COM probe! Up to 100MS/s. $193 / $280 Touch-input 10.2” LCD 12V-powered uCAM-232 / uCAM-TTL 10/25MHz USB powered scope-in-a- EMC RF & EMC Spectrum XP Emb Touchpanel $180 CircuitGear CGR-101™ is a unique new, low-cost PC-based instrument which provides the features of seven devices in one USB-powered compact box: 2-ch 10-bit 20MS/sec 2MHz oscilloscope, 2-ch spectrum-analyzer, 3MHz 8-bit arbitrary-waveform/standard-function generator with 8 digital I/O lines. It also functions as a Network Analyzer, a Noise Generator and a PWM Output source. What’s more – its’ open-source software runs with Windows, Linux and Mac OS’s! Only $199! Mobidapter Pen Scopes CUPC-80 25MHz 2-ch /16 logic scope and logic analyzer. $1095 Scope/Logger Low-Cost Scopes DS1052D DS1000E N RI EW GO ! L 50/100 MHz scope. $595 / $795 2-ch 1GSa/s (25GSa/s equiv.) Amazing 7 in 1 Scope! CAN-USB 20MHz / 60MHz rugged handheld USB 2-ch scope. $593 / $699 Scope + Analyzer PS2104/PS2105 Handheld Scopes PDS5022S / PDS6062T N RI EW GO ! L 2-ch + trigger standalone USB bench scope. $287 / $419 2-ch 1GSa/s Scopes HDS1022MN / HDS2062M Se Bes lle t r Color LCD Scopes A complete CP2102 USB-serial converter in a DB9 shell. $26 Above are some of our best-selling, unique, time-saving products - see our website for 100s more: WiFi/910MHz antennas, wireless boards, LCD display kits, Ethernet/IO, USB/RS232/485, USB-OTG, instant Ethernet-serial, CAN/LINbus, USB cables/extenders, line testers, logic analyzers, color sensors, motion controllers, eng. software, wireless boards, SMD adapters, I2C adapters, GPS loggers, automotive testing, security dongles, video motion detectors, crystals/oscillators, custom switches, barcode scanners, DSP filters, PLCs, Remote MP3 players, etc. FREE Starbucks card with your $50 order! Check www.saelig.com often for special offers, bargains, business hints, blog, etc. Personal Download for [email protected] I © Circuit Cellar F EATURE ARTICLE by Tom Struzik (USA) Wireless Data Exchange Build a 2,700-lb. Bluetooth Headset Building a Bluetooth-enabled device can be difficult if you don’t have any experience with the technology. Finding the right module can greatly simplify the process. The Bluegiga WT32 is a highly integrated Bluetooth module that fits the bill. Here you learn how to put Bluetooth to good use. July 2010 – Issue 240 E 36 nvy is a strong motivator. My wife bought a new Toyota Prius and it had one exceptionally “geekworthy” feature: a built-in Bluetooth interface. As if by magic, when you start the car, it automatically connects to her Palm Treo. She answers incoming calls by simply pressing a button on the steering wheel. The audio, which comes in over the car’s stereo speakers, automatically mutes whatever is playing when a call is received. All in all, it’s a slick, simple interface. Unfortunately, instead of a Prius, I have an old (2,700-lb. tare weight) Acura, and its only upgrade is a radio with an auxiliary input. My thought was that I should be able to build a Bluetooth-to-aux-in adapter that functions much like the Prius’s Bluetooth interface. However, I figured I should be able to support playing MP3s from my smart phone with a custom adapter. Plus, if I could access the phone’s voice command functionality, I thought I would really “out geek” the Prius! Thus, I started my project to construct a “2,700-lb. Bluetooth headset.” I had three goals for the project. The first was to learn something about Bluetooth. The second was to find a Bluetooth module I could use for this Bluetooth project and others. My third goal was to one-up the Prius’s Bluetooth functionality! to be a very DIY-friendly shop. They provide breakout boards for their SMD parts, manuals, user guides, and even a support forum. They’re also one of the few parts sources that offer low-cost U.S. Postal Service shipping, so you don’t have to pay a $10 shipping fee for a $2 part! So, off to SparkFun I went, and they had several different Bluetooth modules in stock (all with breakout boards). FINDING A MODULE Fi gure 1—The Bluegiga WT32 is a highly integrated device. In addition to the radio, it contains multiple digital and analog I/O sources, a programmable MCU, and a DSP. When I look for small-quantity parts, I tend to start searching at SparkFun (www.sparkfun.com). I find them USART/USB Flash PIO RAM Antenna 2.4GHz Radio I/O DSP Audio in/out MCU PCM, I2S, SPDIF XTAL RESET SPI CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com of the WT32 datasheet, the iWRAP user guide, and the circuit diagram for the WT32 breakout board. With this in hand, I thought I should be able to power up and begin interacting with the WT32 device. One thing I noticed while working on powering up the WT32 was that the SparkFun breakout board has differences in the pin nomenclature and c) d) wiring between it and the actual WT32 device. For example, the breakout board has VDDIO and VDD_BAT wired together and AGND and DGND have a solder jumper. With power to the board, the next step was to gain access to the UART. The UART has CMOS input/outputs, so a MAX3232 line driver chip was required for interfacing to my PC serial port. With the UART connected, I confirmed the basics were working by Photo 1a—A WT32 module without its cover. The heart of the WT32 is a Cambridge Silicon running HyperTerminal on my PC Radio BlueCore 5 Multimedia chip. b—The underside of the WT32 module. Don’t place bare copper on your board underneath the WT32! See the WT32 datasheet for board layout recand connecting at 115,200 bps, 8N1 to ommendations. c—The SparkFun WT32 breakout board with the cover intact on its WT32. I the WT32 UART interface. When I added the legs on the breakout board in order to facilitate easy breadboard experimentation. applied power to the WT32, HyperTerd—This is the breadboard with the breakout board on the left. minal displayed the iWRAP boot screen (see Figure 2). Success! Now, with a live connection to the Only one, however, the Bluegiga WT32, build a complete Bluetooth applicaWT32’s iWRAP firmware, the fun supported anything more than simple tion using nothing more than the really began. The next logical step was WT32 and its UART or USB inter“serial cable replacement.” to create an hands-free profile (HFP) face. It appeared that the Bluegiga Further investigation revealed that link between the WT32 and my smart WT32 was an almost-perfect candithe WT32 was quite a find. Per the phone. With this link, I could explore date for my project. datasheet, it has one of just about the basics of Bluetooth link setup and Figure 1 and Photo 1 show the everything. On the analog audio side, how the iWRAP firmware operated. WT32 module’s details. Photo 1c it supports stereo input and output The iWRAP user guide was a bit light with differential signal levels. On the shows the SparkFun breakout board. on how to actually set up an HFP link, digital audio side, it has an integratso I went over to the Bluegiga website ed DSP with stereo codec and supGETTING STARTED and signed up for their tech support port for multiple digital audio forMy initial goal for working with the forum. This move turned out to be mats (PCM, I2S, and SPDIF). The digWT32 was to breadboard the simplest excellent, as the tech support forum possible configuration and validate ital I/O interface has support for had not only firmware updates and PC that I could indeed make a Bluetooth USB, RS-232, and SPI—and on top of tools, but also WT32 application notes connection to my phone. I also felt that, 10 individually programmable like the “Hands-Free and Headset Prothat I needed to gain some experience I/O pins. Most importantly, in the files” iWRAP application note. From with how the WT32, iWRAP, and area of Bluetooth, it supports multithis, there were two main things ple Bluetooth profiles (A2DP, AVRCP, phone interact. I started by reviewing the documenHFP, HFP-AG, SPP, OPP, and HID) required to configure an HFP link. The tation that SparkFun had available on and has an integrated antenna, giving first was to enable the required Blueits website. This information consisted tooth profile. The second was to define the device a 30-m range. And if all that wasn’t enough, throw in a the Class-of-Device (CoD). built-in LiPo battery charger! Enabling and disabling profiles WRAP THOR AI (3.0.0 build 165) On top of this massive hardwas straightforward. The Copyright (c) 2003-2008 Bluegiga Technologies Inc. ware feature list, Bluegiga iWRAP command was SET READY. loaded the WT32 with its PROFILE {profile_name} iWRAP firmware. The program[SDP_name]. Note that leaving Figure 2—When I applied power to the WT32, HyperTermiming language provided by this out the SDP_name disables the nal displayed the iWRAP boot screen. Success! (Source: Bluegiga Technologies) firmware makes it possible to specified profile. For my simple www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 b) a) 37 WRAP THOR AI (3.0.0 build 165) Copyright (c) 2003-2008 Bluegiga Technologies Inc. READY. HFP 1 CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= Initial Autocall connect <phone moves out of range> NO CARRIER 0 ERROR 305 SDC_OPEN_SEARCH_FAILED_PAGE_TIMEOUT NO CARRIER 0 ERROR 305 SDC_OPEN_SEARCH_FAILED_PAGE_TIMEOUT <phone moves into range> CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= Autocall reconnect July 2010 – Issue 240 Figure 3—After rebooting the WT32 or phone, I saw the connection automatically reestablished. (Source: Bluegiga Technologies) 38 would need to use a different CoD. For HFP test, it appeared a “SET PROFILE that configuration, I used the generaHFP ON” would work nicely. I knew tor to produce the CoD 200418 {Major that later I’d need to enable multiple Service: Audio, Major Device: profiles in order to complete my projAudio/Video, Minor Device: Handsect; but for the time being, I only free and Headphones}. needed to enable the HFP profile. With the basic HFP profile configThe more cryptic part of the appliured and put into the iWRAP cation note was setting the WT32’s firmware, I cycled the power on the CoD attribute. The application note WT32 and initiated a pairing from my said to use 200408 with no explanaphone. During the pairing process, I tion what the number actually meant. noticed that changing the CoD altered I took a trip to www.bluetooth.com how the WT32 appeared to the phone. and the official specification docuDepending on the CoD, the phone ments hosted there to turn up inforwould use different icons to represent mation. CoD is used during the Bluethe WT32 device. Once the phone and tooth device discovery process and is WT32 were paired, I called my phone how the queried device responds with from another number and was able to its device type and available services. In the Bluetooth “Assigned Numbers – see the incoming call information through the iWRAP interface. At this Baseband” document, CoD is defined point I believed I had confirmed that as three octets consisting of Major everything was working properly. That Service class (11 bits), Major Device was, until I power cycled the WT32. I class (5 bits), and Minor Device class could still see that the devices were (6 bits). Even the various bit definipaired, but they were not connected. tions for the fields were included in this document. Another clue came from the iWRAP user manual. It referenced a ATtiny26L Bluetooth CoD generator webpage. The CoD generator let me simply PC PBTNS check boxes for services and classes Term and then it displayed the resulting Mic CoD number. From this informaWT32 Car tion, I determined the CoD in the stereo application note—200408—actually Differential maps to Major Service: Audio; Major Device: Audio/Video; and Op-amp AUX-IN Minor Device: Hands-Free device. Single-ended Armed with this knowledge, I could now issue the required “SET Figure 4—A more complex solution required using BT CLASS 200408” command and an AVR processor to control the WT32 through the at least understand what it was iWRAP interface. The PC can still be connected to doing. the system for troubleshooting. The op-amp is For my final configuration using used to convert the audio-out signal from differential to single-ended mode. both the HFP and A2DP profiles, I The phone didn’t show an active headset icon, and incoming calls no longer displayed information in iWRAP. After more digging in the iWRAP user guide, it became apparent that there had to be a CALL command to open the Bluetooth link between the phone and the WT32. Evidently, the act of pairing just happened to also make the HFP link active, but it was not a permanently active link. In fact, even after a CALL was issued, if either the phone or the WT32 was rebooted or moved out of range, the Bluetooth link dropped and was not automatically reestablished. I finally found a solution in the iWRAP user guide: the iWRAP AUTOCALL command. Per the documentation, AUTOCALL will automatically open the specified link to the first paired device it finds and will even attempt to reopen the link if the link is dropped. This sounded like just what I needed. The format of the AUTOCALL command was SET CONTROL AUTOCALL {target} {timeout} {profile}, which was all relatively obvious, except for the {target} field that was specified as “the UUID of the target channel.” Both the iWRAP user guide and the Bluetooth “Assigned Numbers – Service Discovery” document stated that the UUID for the HFP-AG channel was 111F hex. The HFP-AG channel UUID must be used rather than the HFP channel UUID since it’s the handset making the call to the gateway. Thus, a “SET CONTROL AUTOCALL 111F 5000 HFP” appeared to be the answer. Sure enough, after rebooting either the WT32 or the phone, I could see the connection being automatically re-established (see Figure 3). As a side note, it turned out that the AUTOCALL function was a bit of a double-edged sword. It provided the connect/reconnect functionality; however, it always tried to connect. When working manually with iWRAP, if the phone was unavailable, the reconnect attempts disrupted any typing into the iWRAP interface. I found that it was sometimes easier to quickly key in a “SET CONTROL AUTOCALL” CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com 24th International Trade Fair New Munich Trade Fair Centre 09–12 November 2010 erolpxe the possibilities of tomorrow. Automotive e-Mobility Displays / e-Signage Embedded systems / software Medical / MEMS Photovoltaics Time for electronics. Time for the future. Key topics, trends and technologies. The latest components, systems and applications. Visit electronica 2010, the international trade fair that will show you today what is important tomorrow and generate momentum for real growth. Parallel event: hybridica. Trade fair for hybrid-component production. www.hybridica.de get the whole picture electronica 2010 components | systems | applications www.electronica.de/en Personal Download for [email protected] I © Circuit Cellar Fi gure 5—What do you think of this solution? An ATtiny26 AVR controls the WT32. immediately after the WT32 booted in order to disable the AUTOCALL function. At this point, I had verified that I could successfully connect the WT32 to my phone. However, the ultimate goal of one-upping the Prius required establishing A2DP and AVRCP links in addition to the HFP link. The need for multiple links quickly became another problem. The AUTOCALL function only supported making one CALL, and I needed to make three. The only way to establish the additional links was to manually issue the multiple CALL commands. July 2010 – Issue 240 THE SIMPLEST OPTION 40 After digging through the documentation and on-line forums, it appeared there were potentially several solutions to the multicall problem. The simplest solution relied on a “trick” using the programmable GPIO pins and the iWRAP firmware command SET CONTROL BIND. Together, these functions would allow me to automatically trigger additional iWRAP commands based on GPIO pin state transitions. Better still, by specifying different priorities, multiple BIND commands could be made for the same pin transition. The other critical iWRAP command to make this option work was the SET CONTROL CD command, which ties a specified GPIO pin to the WT32’s Carrier Detect state. So, in theory, this solution would work thusly: AUTOCALL would make (and maintain) the State Powerup Call Setup In Call Idle Streaming Button #1 Reset Answer Mute Play Pause initial HFP link. When this link was made, the WT32 Carrier Detect state changes and the SET CONTROL CD raises a GPIO pin. This action then triggers multiple SET CONTROL BIND commands, one for each required CALL. Even if the link was broken, the CD signal would be deasserted. When AUTOCALL reestablished the HFP link, the CD pin would be reasserted and the BIND commands would then (re)CALL the other links as well. It seemed like a simple, elegant solution until I actually tried to implement it. Several Button #1 held Button #2 Button #3 Reject Hangup Voice Cmd Voice Cmd Prev Track Next Track Table 1—This is how I mapped the push button functions to the various states. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com WRAP THOR AI (3.0.0 build 165) <= iWRAP begins booting Copyright (c) 2003-2008 Bluegiga Technologies Inc. READY. <= iWRAP completes boot HFP 1 <= iWRAP invokes the autocall CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= iWRAP connect event call 00:17:e8:3f:d9:e2 17 a2dp <= AVR placing the AVRCP call CALL 1 CONNECT 1 A2DP 23 00:17:e8:3f:d9:e2 <= iWRAP connect event HFP 0 STATUS "service" 1 <= iWRAP continuation HFP 0 STATUS "call" 0 <= of the Hands Free HFP 0 STATUS "callsetup" 0 <= profile startup HFP 0 STATUS "callheld" 0 HFP 0 STATUS "signal" 5 HFP 0 STATUS "roam" 0 HFP 0 STATUS "battchg" 5 call 00:17:e8:3f:d9:e2 19 a2dp <= AVR placing the A2DP call CALL 2 HFP 0 READY <= iWRAP HFP status continues HFP 0 UNKNOWN (7): \r\n+COPS: 0,0,"AT&T"\r\n CONNECT 2 A2DP 25 00:17:e8:3f:d9:e2 <= iWRAP connect for left CONNECT 3 A2DP 25 00:17:e8:3f:d9:e2 <= and right channel Figure 7—The exchange looked like this from the iWRAP interface. (Source: Bluegiga Technologies) www.circuitcellar.com • so in the end I could not guarantee which link ID would end up going with which profile. As the final nail in the coffin, on the simple option, with a marginal signal, some links would drop while the others remained active. If the HFP link wasn’t the one that dropped, the other links never would be reestablished. BETTER, BUT COMPLEX, OPTION While the SET CONTROL BIND command could be extremely useful for a single-profile device, in my case it was not enough. I needed to investigate other solutions. Thus, the second solution (see Figure 4) was born, which consisted of using an Atmel ATtiny26 AVR processor to control the WT32 directly through the iWRAP interface (see Figure 5). The concept was that the AVR would monitor the WT32 state through event messages displayed in the iWRAP interface and it would monitor the state of several push buttons. The AVR could then issue the necessary iWRAP commands to manage the links and issue the commands to activate the various profile functions such as ANSWER, HANGUP, and PLAY. There were several advantages to this solution. For one, it would be easy to simulate and troubleshoot the system by using HyperTerminal on the PC connected to the iWRAP UART interface. The AVR could remap push-button functions based on the current WT32 state, which would have been impossible to do using the simple option. There were three main things the AVR needed to track in this option. The first was tracking and managing the state of the links. The second was tracking the phone state (the HFP profile). The third was tracking the streaming audio state (the A2DP profile). With knowledge of the states, the AVR could map the push buttons to the iWRAP commands necessary to control the HFP and the A2DP functions. Refer to Table 1 to see how I mapped the push-button functions to the various states. I started with building a simple state diagram to outline what the AVR CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 course change any time a different Link state management Power-up phone was paired I: “READY” with the WT32, and changing the Button#1 held Ready address would Ready not connected connected require using the I: “CONNECT 0 HFP 2” iWRAP interface to Pending reset update the address I: “PAIR” string stored in the I: “READY” I: “CONNECT 3” CALL command Call A VRCP Issue that was in each reset SET CONTROL BIND statement. I: “CONNECT 1” I: “ERROR 409” While this might I: “SYNTAX ERROR” have been fine for a one-off device, I *Any* Call A2DP wanted to produce a more general-purpose solution. Figure 6—The AVR manages the state of the HFP, A2DP, and Second, once mulAVRCP links. After the HFP Autocall, the AVR makes the other two tiple links are active, calls. Error-handling is brute-force at this point and just resets the device. I:“<string>” represents the iWRAP text that the AVR watches profile commands for to drive the state transitions. like ANSWER, HANGUP, or additional problems arose during AVRCP PLAY need to specify which implementation. link ID should receive the command. First, unlike the AUTOCALL comThe problem resulted in the link ID mand, the CALL command required appearing to be nondeterministic. It that I specify the Bluetooth address of depended on the order in which the the destination. The address would of CALL commands actually completed, 41 July 2010 – Issue 240 42 would need to do. Using HyperTerminal and the iWRAP interface, I watched the WT32 as it responded to the various iWRAP events, link states, and phone actions. From this information, I was able to produce a state diagram (see Figure 6). For managing the link state, I determined that I would still use the iWRAP AUTOCALL function to control the HFP link, and then the AVR could daisy chain off the event messages coming from the AUTOCALL. From the iWRAP event resulting from the successful AUTOCALL, the AVR could also find the necessary Bluetooth address. The AVR could then issue the two CALL commands, inserting the Bluetooth address where necessary, to make the A2DP and AVRCP links. The exchange looked like Figure 7 from the iWRAP interface. Managing the phone call state was relatively simple. An incoming phone call that was answered and then disconnected looked like Figure 8 in iWRAP. Managing the streaming audio was even easier. The same AVR push button would control both the PLAY and STOP commands. The AVR would monitor the streaming state to determine which iWRAP command to issue. From iWRAP, hitting the Play and then Stop button looked like Figure 9. The voice command was simple as well. Since it’s done completely by the phone, all the WT32 has to do is send audio of the voice command to the phone. The phone does the heavy lifting of recognizing and acting on the voice command. Refer Figure 10 for the iWRAP exchange for voice command. At this stage, I had completed the design of my “2700 lb Bluetooth Headset” that would even beat the Prius by providing streaming audio in addition to regular phone headset capability. I had also learned some Bluetooth basics and I found a Bluetooth module, the Bluegiga WT32, which I could use in my future Bluetooth projects. Even though I only brushed the surface of the WT32 module’s capabilities in this article, I hope this whetted your appetite to investigate further. With a little work, you too can easily add a Bluetooth interface to HFP 0 STATUS "callsetup" 1 <= incoming call, iWRAP start call setup HFP 0 RING <= iWRAP, the phone rings HFP 0 CALLERID "5551111234" "" 80 <= iWRAP, caller ID HFP 0 RING HFP 0 CALLERID "5551111234" "" 80 HFP 0 RING HFP 0 CALLERID "5551111234" "" 80 < AVR Answer button pressed> set 0 select <= the AVR selecting the HFP link answer <= the AVR issues answer command HFP 0 OK HFP 0 STATUS "call" 1 <= iWRAP, successful answer, the call is made HFP 0 STATUS "callsetup" 0 <= iWRAP, end call setup RING 4 00:17:e8:3f:d9:e2 SCO <= iWRAP, incoming Audio link to support the call < AVR Hang-up button pressed> set 0 select <= AVR selects the HFP link hangup <= AVR issues hang-up command HFP 0 OK HFP 0 STATUS "call" 0 <= iWRAP ends calls NO CARRIER 4 ERROR 113 HCI_ERROR_OETC_USER <= iWRAP says phone dropped sco link Fi gure 8—An incoming phone call which was answered and then disconnected looked like this in iWRAP. (Source: Bluegiga Technologies) your next project. ADDITIONAL NOTES Don’t worry if your WT32 from SparkFun initially comes up with a warning that the firmware is “evaluation only.” You just need to upgrade the firmware. You can find the latest firmware on the Bluegiga technical forum. Just sign up to get access to the firmware, documentation, PC software, and application notes. set 1 select avrcp play A2DP STREAMING START set 1 select avrcp stop A2DP STREAMING STOP cable. The circuit diagram for the SPI interface cable and the necessary software drivers can be found on the Bluegiga forum. One word of caution: it is entirely possible to configure non-standard data rates with the iWRAP SET CONTROL BAUD command. Verify your SET CONTROL BAUD command before you hit the Return key. Make doubly sure you have not mistyped the data rate parameter! <AVR Play/Pause button pressed> <= AVR selects the AVRCP link <= and issues the play command <= iWRAP sees streaming start < AVR Play/Pause button pressed> <= AVR selects the AVRCP link <= and issues the stop command <= iWRAP sees streaming stop F igure 9 —This is what it looks like when you hit the Play button and then the Stop button. (Source: Bluegiga Technologies) The support staff at Bluegiga was helpful when I had questions or problems that weren’t covered in the FAQs or forums. The WT32 firmware can be upgraded over UART or SPI. However, to use SPI you need the necessary interface The normal PC serial port won’t do non-standard data rates. If you misconfigure the WT32, you won’t able to communicate with iWRAP via the serial port. However, it is still possible to use the SPI and the PSTOOLS program (also available on the Bluegiga <AVR Voice Cmd button pressed> set 0 select <= AVR selects the HFP link AT+BVRA=1 <= AVR issues voice dial command RING 4 00:17:e8:3f:d9:e2 SCO <= iWRAP incoming audio link (for voice cmd) HFP 0 OK < voice command processing happens on phone> NO CARRIER 4 ERROR 113 HCI_ERROR_OETC_USER <= iWRAP sees audio link close Fi gure 1 0—The iWRAP exchange for voice command (Source: Bluegiga Technologies) CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com forum) to reset the iWRAP data rate. Your only other alternative is to find a serial terminal that will perform non-standard data rates. Or you can do as I did and use a USBee SX signal generator to manually produce the non-standard RS-232 signals! I Author’s note: I thank Bluegiga Technologies for granting me permission to show the header with its copyright statement in some of this article’s figures. Tom Struzik ([email protected]) has been building and taking things apart from an early age. He built his first Heathkit project at age 12 and sold his first computer program at age 16. Tom has a BSEE from Purdue University. He works for a Fortune100 chemical company in its engineering organization as an IT systems architect. Tom continues to write software and build hardware projects at home to “keep his hands dirty.” He is currently in a state of wonder over his young daughter. The bets are on to see if she gets Tom’s engineering gene, her mother’s music gene, or some combination thereof. Visit Tom at www.JenRathbun.com/Electronics/. PROJECT FILES To download a circuit diagram and code, go to ftp://ftp.circuitcellar.com/ pub/Circuit_Cellar/2010/240. RESOURCES WT32 User Guides, Application Notes, and More, Bluegiga Tech Forum, www.bluegiga.com/support. SOURCES ATtiny26 Microcontroller and AVR assembler Atmel Corp. | www.atmel.com WT32 Bluetooth module Bluegiga Technologies | www.bluegiga.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 Tom Struzik’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — Wireless Sensor Network Design by Diego Méndez Chaves, et al. Circuit Cellar 211, 2008 A group of designers presents a wireless sensor network platform. It’s a testbed for the evaluation of different algorithms related to the communications stack of a network (e.g., routing policies and medium access control). Topics: Wireless, Network, Mote, Kernel, Sensors Go to: www.circuitcellar.com/magazine/211.html — Wireless Thermostat System by Darryl Uchitil Circuit Cellar 207, 2007 Darryl designed a wireless zone thermostat system that can remotely read temperature, calculate the dew point, and force a setback. Topics: Wireless, Thermostat, ZigBee Go to: www.circuitcellar.com/magazine/207.html www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar F EATURE ARTICLE by Matt Bunting & John Rogers (USA) Hexapod Kinematics Motor Communication, Motion Planning, and Image Processing This article covers advanced topics in robotics applied to a completely autonomous hexapod design. The concepts of gait dynamics, feedback control, and optical flow for motion depiction are covered. I n this article, we’ll demonstrate advanced topics in robotics applied to a uniquely designed hexapod robot that is a 2-kg completely autonomous unit using an Intel Atom z530, which is a low-power processor capable of powerful computation (see Photo 1). The hexapod has the ability to be completely self-contained while simultaneously combine walking and balancing algorithms, together with sophisticated optical image-recognition processing. We’ll describe advanced robotic concepts—such as inverse kinematics and optic flow—in terms of foot placement with path optimization and gait dynamics, feedback control for behavior modification, and optical flow for motion depiction, all of which are all essential to robotic operation. PRECISION CONTROL Hexapods are six-legged walking creatures commonly found in nature. Having six legs eliminates many of the complexities involved with maintaining physical balance; however, the relatively large number of extremities requires intricate control during movement. But what about a hexapod robot? With the capabilities of contemporary a) July 2010 – Issue 240 b) 44 microprocessors, complex floating-point calculations involving inverse trigonometric functions can be performed with an unnoticeable effect on the system’s speed. As such, inverse kinematic functions that model a hexapod’s legs provide precision control that enables fluidic movement. The hexapod robot design involves mechanical engineering, electrical engineering, and computer science. We created the mechanical design with 3-D CAD software and a 3-D printer at the Robotics and Neural Systems Laboratory (RNSL) at the University of Arizona. The electronics were designed purely to pipe control and sensory information to a computer, utilizing USB for connectivity. The computer utilizes hyper-threading, a method of simultaneous computational capability to increase application performance. Machine vision is included as the fundamental sensor for the future integration of various behaviors. A system model using forward kinematics was fabricated to predict the end effector locations based on the set angles of the motors. Inverse kinematics were then derived to set the angles of the motors based on desired end effector locations. Using inverse kinematics, trajectories for each foot were created to generate walking gaits. A dynamic system was then employed to place the feet of the hexapod based on the body location. Various walking gaits were possible using the dynamic walking techniques. Photo 1a—The assembled hexapod features an Intel Atom processor and Robotis AX-12, RX-10, and RX28 servomotors. b—The Atom processor performs kinematics calculations together with complex vision-processing at nearly 900 Hz. A Point Grey Chameleon machine vision camera is used for its compactness. An inexpensive lens is used to get a 150° field of view. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Instead of placing all apply the greatest torque, the RX-28 six legs circularly symmotors are used. The last motor is metric about the center the tibia motor, using the AX-12, of the body, we used a with the angle denoted as θt and simple ellipse. The 3-D length denoted as dt. rendering and printing The Robotis motors offer a mountprocess is shown in ing point on the same axis of the Photo 2. output shaft, which can be used for Each leg was designed rigid joints. Bearings are fixed on this with three degrees of mounting point. Each link, for the freedom (3DOF). In a 3coxa, femur and tibia, was designed D space, 3DOF are to wrap around the motor. needed to position the foot at an arbitrary COMPUTATION Photo 2 —This is a 3-D printer creating pieces. The white point. Legs with only The main computational element material is support material used to create overhanging two motors, or 2DOF, that performs inverse kinematics and objects. The printer is currently creating a femur, body plate, do not have the flexibil- other control processes needs to and coxa brackets. ity of operating the end employ little electrical power and effector in three dimensions. The must be compact enough to fit on Finally, balance gestures were includonly possible space for the end effecthe hexapod, all while having powered to avoid any mechanical limitation tor of a 2DOF leg is topologically ful computational capabilities. While within the individual legs. equivalent to a torus. The first motor many microcontrollers and FPGAs operates the leg’s horizontal motion offer what is needed, they also can be MECHANICS and is denoted as the coxa. The coxa incredibly difficult for performing The mechanical portion of the applies the least amount of torque more complex computations such as design process involved the physical while the hexapod walks, and thereimage processing. The easy-to-use design and the use of servomotors. fore the RX-10 servomotor is used Atom z530 processor can implement Numerous companies distribute and for each coxa joint. a variety of available operating sysmanufacture servomotors. Hobby The coxa angle is denoted as θc. tems. A Fit-PC2 available from Commotors are commonly used and inexpulab sports the z530 processor in a pensive, but they offer very little in The second motor operates the first compact form. terms of feedback to the main conmain link of the leg, called the trol system. Robotis offers the femur. Since there is a physical disThe computer consumes around 5 W Dynamixel series of servomotors that tance from the coxa motor axis of of power at 1.6-GHz clock. Ubuntu enables you to read various paramerotation to the femur motor axis of 9.04 is the preferred operating systers of the motor, including current rotation, the distance needs to be tem since C++ is the chosen proposition, applied torque, input volttaken into account for kinematics. gramming language. OpenCV age, and motor temperature. It also This distance will be denoted as dc. libraries are installed to implement features an emergency shutdown easy machine vision processing. The femur rotates upward from the operation in case one of the paramecoxa. The angle of the femur is ters exceeds a settable threshold. We denoted as θf, and the length of the ELECTRICAL & VISION used Robotis RX-28, RX-10, and AXfemur is denoted as df. Since this is In order to communicate with the 12 motors, with 28, 10, and 12 kg-cm the joint that generally needs to motors, we built a simple circuit to pipe of torque, which are more than strong enough for each joint in the hexapod. We used a Dimension BST-1200es 3-D printer for the mechanical construction. The 3-D printer is a rapid prototyping machine that can create parts in ABSplus plastic. Solidworks was used for the design. We used dimensional drawings of the motors to model mechanical components to fit with extreme precision. The layout of each leg was inspired by biological features; however, the exact physical positioning was completely Figure 1—Sending and receiving data from both a half-duplex TTL serial bus and RS-485 bus arbitrary. 45 Photo 3—This is a simulation built with forward kinematics. The simulation was created using OpenCV by drawing individual lines from point to point using the described equations. motor control protocol to the motors from the computer. A Microchip Technology PIC18F4550 microcontroller includes a USB hardware peripheral, which can be used to connect directly to the Fit-PC2. Microchip offers a CDC library to allow ease of integration of USB for embedded projects. The PIC transmits motor protocol through both a half-duplex TTL-level serial bus and a bidirectional RS-485 bus for the AX and RX series motors, respectively. All Robotis motors use the same motor protocol, so a simple circuit was designed to integrate their serial buses together (see Figure 1). Also, contact sensors on the foot can be easily integrated through direct connection to the PIC. With the computational capability and hyper-threading ability, the Atom processor performs kinematics calculations together with complex vision processing at nearly 900 Hz. A Point Grey Chameleon machine vision camera is used for the compactness. An inexpensive lens is used to get a 150° field of view. July 2010 – Issue 240 MOTOR CONTROL 46 The simple servomotor operates by providing either a signal or protocol specific to the motor which translates to the output shaft position. Typical hobby-style servomotors have a single-input pin that senses the high part of a PWM signal. If the PWM’s high time changes, the mechanical output angle of the motor changes accordingly. The servomotors used for the hexapod require a slightly more complex protocol, involving an RS-485 bidirectional communication bus. The Robotis motors have a few advantages over the standard PWM controlled servomotors. When a position is sent to a Robotis motor, the motor stores the position in memory and attempts to move the output shaft to the set angle. A standard hobby motor operates differently in that it needs a constantly fed PWM signal for it to maintain a position. Also, each hobby motor needs a separate connection with a unique position signal, whereas the Robotis motors are daisy-chained on the same bus. This makes wiring much easier, and the position protocol can be sent to all motors simultaneously. Many low-quality motors on the market work well for human-controlled applications, but their linearity for precise positioning in terms of robotics can be poor. Poor linearity results in inaccurate expectations of forward kinematics. For example, if a motor is calibrated to positions at 0° and 90°, and if we send a signal based on the calibration to set the motor to 180°, then a motor with good linearity should result in an output position very near to 180°. Motors with sufficient linearity have a tolerance of ±2°, while a motor with poor linearity will vary from ±5° to ±45°. With any servomotor, calibration is needed due to small manufacturing differences. Calibration is essential to the hexapod’s smooth operation. Given two measurement points of desired output position—θd1 and θd2—and the motor commands required to move the motors to the desired positions—L1 and L2, respectively—then any output command L to move the output shaft as a function of desired angle θ is: L (θ) = (θ − θ d1 ) L1 − L2 + L1 θ d1 − θd2 [1] KINEMATICS Kinematics involves connections of links and their respective angles. It is possible to compute the position of each link from the connections and the angles, and most importantly, the end of the final link is called the end effector. In the case of the hexapod, if the three motor angles of a given leg are known, then the position of the foot can be determined through simple trigonometry. The method of calculating the end effector position as a function of the angles is called forward kinematics. Usually, it is more desirable to set a desired foot position and determine the angles required to set the foot at the given position. This is particularly useful when planning a path or trajectory for the foot. The process of computing the angles as a function of desired position is called inverse kinematics. FORWARD KINEMATICS Although not particularly useful for direct control of the hexapod, performing the forward kinematics can be useful for understanding inverse kinematics and for creating simulations. Refer to Photo 3 for a simulation created with OpenCV using forward kinematics. Figure 2 depicts the mechanical configuration of one of the hexapod’s legs. When performing the derivation of forward kinematics, it is easiest to break the system into smaller sections. First, consider dc and θc, the angle and distance of the coxa. The position of the femur joint xF and yF can be computed as in Equation 2 and Equation 3, respectively. x F = d C cos (θC ) + x L = d C cos (θC ) y F = d C sin (θ C ) + y L = d C sin (θ C ) z F = zL = 0 [2] [3] [4] By knowing the projection of the first link and the corresponding angle, it’s possible to project the next point based on the femur angle θf femur length df to find the location of the tibia joint, T. x T = x F + d f cos (θf ) cos (θC ) y T = y F + d f cos (θf ) sin (θ C ) z T = z F + d f sin (θ f ) [5] [6] [7] Finally, the coordinates of the end effector E (or foot) are the last projection, CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com which is determined from the tibia angle θt and the tibia length dt. x E = x T + d t cos (θ t + θ f − π ) cos (θ C ) y E = y T + d t cos (θ t + θf − π ) sin (θ C ) z E = z T + d t sin (θ t + θf − π ) θt [8] df z y θf INVERSE KINEMATICS When you use your arm to reach for an object, you easily operate your muscles to angle your joints so as to place your hand at the object’s location. Such a case involves inverse kinematics, which is an inverse operation to forward kinematics. Similar to forward kinematics, the easiest method to inverse kinematics derivation is by simplification. With desired end effector coordinates—xE, yE, and zE—trigonometry can be used to solve for θc, θf, and θt. Again, consider the simple case with the leg at the origin. First, from an overhead view and the constraints of the system, it becomes clear that the only angle that affects the horizontal movement is θc. Thus, θc can be solved first. [11] Note that atan2 is used instead of tan–1 because it can return the full possible range of an angle (–π ≤ θ ≤ π). Knowing the angle and the distance of the coxa link dc, Equations 2 and 3 may be applied to get the known location of the femur joint. It is now possible to construct a triangle with the femur, tibia, and an (xE, yE, zE) dc The abovementioned equations only apply when the leg is at the origin; however, this can be generalized when leg locations L (not equal to zero) are applied. θc x imaginary distance from the end effector to the femur joint. This distance will be denoted at di. di = (xE − x F ) + ( y E − y F ) + (z E − z F ) 2 2 2 [12] Knowing all lengths of the triangle, the law of cosines may be applied to solve for the tibia angle θt. ⎛ − d 2 + d 2f + d 2t ⎞ θ t = cos−1 ⎜ i ⎟⎠ 2d f d t ⎝ [13] A similar process can be performed to solve for θf. ⎛ d 2 + d f2 − d i2 ⎞ −1 ⎛ z E ⎞ θ f = cos −1 ⎜ i ⎟⎠ + sin ⎜⎝ d ⎟⎠ 2d f d i ⎝ i [14] Even though the simple case has been shown for the leg starting at the origin, it’s easy to expand to legs not located at the origin—and perhaps rotated about the z-axis. MOTION PLANNING With the ability to decide the end effector location of each leg, it is easily possible to create any arbitrary trajectory for the end effector to follow. z θ = b + 2π n For example, if the hexapod were to walk straight forward, then a possible trajectory would involve a backward motion of the foot, followed by a lift-and-forward motion. The body will move in space based on the motion of each end effector relative to the body. The desired path when the hexapod walks forward is a straight line, followed by a lift and a return to the original position. Since the trajectory needs to be continuous and oscillatory, the function will mimic some properties of a sinusoidal function. If a semicircle is desired for the lift, then a characteristic equation for the trajectory where Z is the lift and Y is translational movement as a function of θ and a set break or lifting point b may be synthesized, as in Equation 15, under the definition and constraint of Equation 16. The trajectory is graphed in Figure 3. ⎡ y⎤ ⎢ z ⎥ = f (θ, b) = ⎣ ⎦ 2θ′ ⎤ ⎧⎡ ⎪ ⎢1 − b ⎥ 0 ≤ θ′ < b ⎪⎢ ⎥ ⎦ ⎪ ⎣0 ⎪ ⎡ − 2π ) π ⎞ ⎤ b ≤ θ ′ < 2π θ ⎛ ′ ( ⎨ cos ⎪ ⎢ ⎜⎝ b − 2π ⎟⎠ ⎥ ⎥ ⎪⎢ ⎪ ⎢ ⎛ (θ′ − 2π ) π ⎞ ⎥ ⎪ ⎢sin ⎜ b − 2π ⎟ ⎥ ⎠ ⎥⎦ ⎩ ⎢⎣ ⎝ [15] 0 < b < 2π, θ ′ = θ ( mod 2π) y -1 • 1 Figure 3—An example of a trajectory for simple forward motion where n is any integer [16] The function may be implemented into walking forward with a maximum lift height gain h and travel distance gain dT, and a frequency ω CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 1 θ = 2π n www.circuitcellar.com dt [9] [10] θC = atan2 ( y E , x E ) Figure 2—Kinematics of a single hexapod leg. The black, blue and red lines represent the coxa, femur, and tibia, respectively. Servomotors change the angles θc, θf, and θt. 47 and arbitrary phase φ to set the end effector distances. The resting or pivot positions xP, yP, and zP are constant and translate the trajectory in space. ⎡ yp ⎤ ⎡ y E ⎤ ⎡d T 0 ⎤ ⎢ z ⎥ = ⎢0 h ⎥ f (ωt + φ, b) + ⎢ z ⎥ ⎢⎣ p ⎦⎥ ⎣ E⎦ ⎣ ⎦ July 2010 – Issue 240 xE = x P 48 [17] [18] zero. The initial resting position of the foot with respect to the body will be denoted as xr and yr. When the hexapod begins to move, the resting position moves as well. The current resting position in space, called the pivot positions, is denoted as xP and y P. ⎡ x p ⎤ ⎡cos (θb ) − sin (θb ) ⎤ ⎡ x r ⎤ ⎡ xb ⎤ ⎥⎢ ⎥ + ⎢ ⎥ ⎢ ⎥= ⎢ cos (θb )⎦⎥ ⎣ y r ⎦ ⎢⎣ y p ⎥⎦ ⎢⎣sin (θ b ) ⎣ yb ⎦ filter. If α is close to zero, then the foot takes a step closer to the current pivot point. If α nears one, then the feet take a much longer time before they settle into the current walking motion. A visualization of the described dynamic walking mechanism is shown in Figure 4. ( ) ( ) x DEST = x p + α x p − x OLD y DEST = y p + α y p − y OLD [20] [21] [19] Different phases may be applied to each leg so that the legs will lift at 0 ≤ α<1 [22] different times. Various walking gaits The foot is stationary as the body may be generated by simply choosing moves. It begins repositioning at a different phases φ and breakaway or The trajectory function in Equation specific time. Before the foot lifts, lifting points b. the previous position is recorded into 15 without any applied gain results in As for dynamic walking, it’s easy –1 ≤ y ≤ 1 and 0 ≤ z ≤ 1. Using the xOLD and yOLD. A simple trajectory to mathematically fabricate specialvalue of y, a smooth motion can be can be created to move the foot to created from the old position to the the current resting position. Indecase end effector trajectories to perdestination position. If the leg is at the pendent of the initial foot location, form a specific body movement. In time to lift, then y = –1 and y increasthe foot returns to a stable position. the aforementioned example, walking es until the foot reaches the destinaThus, the foot control is dynamic. forward is accomplished by moving tion position at y = 1. all feet in a similar oscillatory motion Returning to the pivot is, however, not the most natural way for a creafrom front to back. All of these cases 1+ y 1 − y⎤ ⎡ ture to walk. A more natural way have a relatively constrained way of ⎢ x DEST 2 + x OLD 2 ⎥ ⎡xE ⎤ ⎢ ⎥ would be to project the foot beyond motion; however, as they are not 1+y 1 − y⎥ ⎢ ⎥ ⎢ y y = + y the pivot point. The possible destinaadaptable to changes in motion. DEST E O LD ⎢ ⎥ ⎢ 2 2 ⎥ ⎢⎣ z E ⎥⎦ ⎢ ⎥ tion of the foot, xDEST and yDEST, is Instead, a dynamic way of generating hz ⎢ ⎥ trajectories would be more adaptable shown in Equations 20 and 21, ⎢⎣ ⎥⎦ in terms of different motion controls. which looks similar to an α tracker [23] A simple way to have the hexapod move would be to WALKING GAITS move the body in space and A walking gait is the have the legs take care of sequence in which various themselves. This way any legs oscillate to move the complex movement could be body. Gaits vary with a creadest applied to the body with ture’s number of legs. A ease. biped is limited in its possi( d) The dynamic walking ble gaits. As exemplified, a method will be dynamic in gait can be picking up one p space but not in time. Thus, foot while the other is down, d each leg will have a known and vice versa. Also, both lifting time. When the hexalegs can hop at the same pod is first initialized, the time, but that defeats the old legs slowly lift the hexapod definition of walking. A body upward to a standing quadruped is again limited position. The position of by which leg can be lifted each foot relative to the body while remaining stable. before the body translates in Hexapods have the advantage space is called the resting, or of being stable over a wide initial, position. The six variety of gaits. We’ll cover Figure 4—Visualization of dynamic walking. The blue outline is locations are stored in memthree such gaits. With the the previous hexapod position and foot locations, designated as ory for the duration of the ability to set the phase and old. The gray body is the current body position. The dotted lines program. The body location lifting point of each leg, we represent the current resting or pivot position, denoted as p. and orientation in space are can easily implement differThe gray circles represent the destination position for the feet denoted as xb, yb, and θb, denoted as dest. The feet are projected a total of αd beyond the ent gaits. Figure 5 shows the current pivot position, where d is the distance from old to p. various walking gaits with which are all initialized to CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com arm and hope to reach it. Instead, you move Tripod gait 1 4 and angle your body 2 4 1 1 accordingly to help 4 1 2 5 3 extend your reach. In 4 2 5 other words, you bal3 6 5 5 6 3 6 ance your body with 2 respect to your limbs. 1 4 1 3 2 1 4 6 These balance gestures 2 5 are also applied the 4 2 5 3 hexapod, which helps 4 6 6 3 1 5 the hexapod avoid 3 6 2 reaching mechanical 5 1 1 2 4 limits. Balance gestures 4 1 6 are especially useful 3 2 5 3 2 5 4 with the application of 6 3 terrain adaptation 6 6 3 5 behaviors, when the exact terrain is unknown. When the Figure 5—Various hexapod walking gaits. A colored circle signifies a leg in the lifting state. Notice the differhexapod is traversing ence in leg indexing for the ripple gait. over rugged terrain, the body always remains centered with respect to each foot corresponding leg indexing. of the gait allows for good stability; location. The tripod gait gets its name from but with two wave gaits, the refresh Imaginary springs with identical having three legs supporting the body rate can be double that of the wave spring constants k have been at one time while the other three gait, thus making it much faster than attached from each foot to the correreposition themselves. Once the the wave gait. sponding coxa joint (see Figure 6). three legs have been repositioned, When the springs have the least posthe three previously supporting legs π 4π φi = 2π − i, b = sible amount of tension, the position lift and reposition. This is similar to 3 3 and orientation of the body is considhow a biped walks. Under the appli[26] ered to be in balance with respect to cation of the trajectory function BALANCE GESTURES the foot positions. It is assumed that above, the phases and lifting point When you see a coin on the the hexapod to which the balance can be set as in Equation 24. The triground, you don’t stretch out your pod walking gait has the advantage of being the fastest gait, but it does y not look natural. Wave gait Ripple gait E4 [24] E1 The wave gait gets the name from the wavelike motion of the leg lift order. Here, only one leg is lifted at a time. This gait is the slowest possible gait, but it is very stable and looks fairly natural. π 5π φi = 2π − i, b = 3 3 • E5 c5 c1 Өb yb b yc6 c2 c6 [25] The ripple gait has a balance between speed and stability, and it has the most natural look. This gait is a variation on the wave gait, where there is an individual wave gait on both sides of the hexapod. The wave nature www.circuitcellar.com c4 yE5 c3 E2 Xc6 E6 E3 x Xb XE5 Figure 6—Spring model for balance gestures. Black lines represent ideal springs, with arbitrary spring constant k. Body center and orientation are represented by b and θb. Coxa locations with respect to body center represented by c. End effector locations represented by E. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 φ1, φ3, φ5 = 0, φ2, φ 4, φ5 = π, b = π 49 gestures are being applied is fairly symmetric. Due to symmetry, the summation of all six coxa locations with respect to the body is shown in Equation 27. 6 ∑x i=1 6 = 0, ci ∑y i=1 =0 ci [27] The tension due to each spring Fi, as shown in Figure 6, is determined through observation of the orthogonal components, as in Equation 30. ( Fxi = x Ei − x ci cos (θb ) + y cisin (θb ) − x b ( ) Fyi = y Ei − x cisin (θb ) − y ci cos (θ b ) − y b [28] ) [29] ∧ ∧ Fi = Fxi i + Fyi j [30] Under the assumption of symmetric coxa locations, the sum of the orthogonal components of spring tension should be zero, as there otherwise would be translational accelerations. 6 ∑ (x i =1 Ei ) − x ci cos (θb ) + y ci sin (θ b ) − x b k = 0 [31] 6 ∑ (x i =1 6 Ei 6 ∑ (x i =1 Ei ( ) − x b ) + ∑ − x ci cos (θ b ) + y cisin (θ b ) = 0 i =1 [32] − xb ) = 0 ⇒ xb = 6 1 ∑ x Ei 6 i =1 [33] The resulting location results in the simple average location of the feet. A similar process is done for yb, the body location in y. yb = 1 6 ∑ yEi 6 i =1 [34] The remaining parameter to be solved is the angle of the body, θb. Since the position has been solved, it is possible to find the total tension of the springs as a function of the body angle. By taking the derivative of the magnitude of the tensions with respect to the body angle, and setting the value equal to zero, the minimum or maximum tension can be solved. The resulting angle can then be solved using Equation 36. ∂ ∂θ b 6 ∑ F (θ ) = 0 i =1 i b [35] July 2010 – Issue 240 6 50 θb = π − tan −1 ∑ ⎡⎣ x ( y ci b i=1 6 ∑ ⎡⎣ y ( y ci i=1 b − y Ei ) − yci ( x b − x Ei )⎤⎦ − y Ei ) + x ci ( x b − x Ei )⎤⎦ [36] The described balance gesture equations only apply to a two dimensional case, but the same principles are used in the expansion to three dimensional balance gestures. RESULTS The ABS plastic body and leg components from the 3-D printer are rigid, thus enabling accurate kinematic predictions. The Atom z530 processor calculates the control algorithms with ease at nearly 200 Hz without code optimization. The PIC18F4550 pipes motor control protocol from the computer through USB 1.1 to the Robotis motors through two different serial interfaces at 1-Mbps data rate. Through the implementations of the described algorithms, the hexapod is able to traverse smoothly in a simple flat environment. The implementations of inverse kinematics enable the effortless control of the end effector’s Cartesian placement for each leg. The simple trajectories enables the hexapod to walk forward. The inclusion of dynamic foot placement enables facile operation of the body placement in space, where the feet are automatically projected to a stable location. Mechanical limits are rarely encountered due to the inclusion of balance gestures. The various walking gaits are easily implemented by simply assigning different lifting points and leg phase shifts. The only unsatisfactory element of the hexapod is contained within the servomotors. Unfortunately, the motors implement only programmable nonlinear proportional (P) controllers, with a limited resolution of 10 bits per 300°. The hexapod is capable of performing much better with PID controller-based motors, preferably with a higher resolution at a minimum of 12 bits per 300°. LOOKING FORWARD You’re now familiar with how we designed and constructed a hexapod robot. The biologically inspired body and leg design was modeled in Solidworks and created with a 3-D printer. In this article, we described equations for both forward and inverse kinematics. We also presented a simulation created with forward kinematic methods, and we explained how controlling the hexapod involves inverse kinematic methods. We built simple trajectories for the end effectors of each leg to synthesize a simple walking motion. In addition, we explained how to implement dynamic foot placement techniques for complex body motion. Using simple phase and lifting point selection, it’s possible to generate various walking gaits. Balance gestures were included using a spring model to help avoid legs reaching mechanical limits. The hexapod provides a good foundation to perform higherlevel control algorithms. We included a machine camera in the mechanical design, although we haven’t implemented it at this stage. In the future, we plan to implement various behaviors based on vision. One such behavior is machine learning, specifically Q-learning using optic flow to sense movement. Force-sensing resistors (FSRs) are also included in the foot design, but they are not connected at this time. We’ll explore terrain adaptation based on vision and foot contact, in addition to machine learning, in the future. I Authors’ note: We want to acknowledge Dr. M. Anthony Lewis of the Robotics and Neural Systems Laboratory (RNSL) at the CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com University of Arizona for his invaluable assistance with the project. We also thank Stewart Christie and the Embedded Design Center (EDC) team at Intel Corp. for their gracious support and assistance to bring the project to its current level. Matt Bunting ([email protected]) earned a degree in Electrical Engineering at the University of Arizona. His interests include robotics, specifically in the areas of cognitive and neural systems. John Rogers ([email protected]) earned a degree in Computer Engineering at the University of Arizona. His interests include robotics and computer engineering. REFERENCE [1] H. Kopka and P. W. Daly, A Guide to LATEX, 3rd Edition, Addison-Wesley, 1999. SOURCES Atom z530 processor Intel Corp. | www.intel.com PIC18F4550 Microcontroller Microchip Technology | www.microchip.com Chameleon camera Point Grey | www.ptgrey.com AX-12, RX-10, and RX-28 servomotors Robotis | www.robotis.com/zbxe/main 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 Matt Bunting and John Rogers’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — Robot Navigation and Control by Guido Ottaviani Circuit Cellar 224, 2009 Build a navigation control subsystem for an autonomous explorer robot. Here you learn about a robotic platform that drives motors and controls an Hbridge. Topics: Robot, Navigation, Motor, Telemetry Go to: www.circuitcellar.com/magazine/224.html — Vision-Guided Robotics by Hanno Sander Circuit Cellar 224, 2009 Want to build a vision-guided, balancing robot that interacts with its environment? You can tackle this project with a Parallax Propeller, a handy design kit, and an inexpensive camera. Topics: Robot, PID, Fuzzy Logic, Vision, Frame Grabber Go to: www.circuitcellar.com/magazine/224.html microOBD 200 www.microOBD.com OBD-II interpreter module in a DIP-24 package. UART interface, bootloader, 100% compatible with the ELM327 command set. $49 OBDLink www.OBDLink.com $99 #1 PC based OBD-II scan tool. USB, RS232, Bluetooth, and WiFi options. Free OBDwizTM software included. ECUsim 5100 www.ECUsim.com Professional multiprotocol OBD-II ECU simulator. Functional and physical addressing, three virtual ECUs, software configurable. Full support of all OBD-II protocols Free regular firmware updates Discount code for free shipping: CC1006FS Questions? Email [email protected] www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 $549 51 BOARDS, BOOKS, DVDs AND MORE AT WWW.ELEKTOR.COM/SHOP Elektor Shop The world of electronics at your fingertips! ! EW 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 Books ore This book and m are available at m/books www.elektor.co Microsoft approved! Learn more about C# programming and .NET A laser alarm, USB teasing mouse, soundswitch and much more C# 2008 and .NET programming 50 PIC Microcontroller projects for Electronic Engineers This book contains 50 fun and exciting projects for PIC microcontrollers such as a laser alarm, This book is aimed at Engineers and Scientists USB teasing mouse, eggtimer, youth repellent, soundswitch, capacitive liquid level gauge, “finger who want to learn about the .NET environment in the water” sensor, guarding a room using a camera, mains light dimmer (110-240 volts), talking and C# programming or who have an interest in microcontroller and much more. Several different techniques are discussed such as relay, alternating interfacing hardware to a PC. The book covers the current control including mains, I2C, SPI, RS232, USB, pulse width modulation, rotary Visual Studio 2008 development environment, encoder, interrupts, infrared, analog-digital conversion (and the other way around), 7-segment the .NET framework and C# programming lan- display and even CAN bus. Three PIC microcontrollers are used in this book, the 16f877A, 18f4455 guage from data types and program flow to more and 18f4685. It is also discussed how you can migrate your project from one microcontroller advanced concepts including object oriented to another - 15 types are supported - including two example projects. programming. 440 pages • ISBN 978-0-905705-88-0 • $58.10 240 pages • ISBN 978-0-905705-81-1• $47.60 Prices and item descriptions subject to change. E. & O.E Personal Download for [email protected] I © Circuit Cellar CD/DVD-ROMs Bestseller! See the light on Solid State Lighting DVD LED Toolbox New! Reign with the Sceptre dsPIC Control Board This open-source & open-hardware project This control board has been designed for in- This DVD-ROM contains carefully-sorted com- aims to be more than just a little board with a corporation into typical industrial electronics prehensive technical documentation about big microcontroller and a few useful peripherals applications like controlling motors or ad- and around LEDs. For standard models, and for — it seeks to be a 32-bit ARM7 fast prototyping justment of static up- or down-converters.The a selection of LED modules, this Toolbox gath- system. To justify this title, in addition to a very objectives were to obtain a board with a large ers together data sheets from all the manufac- useful little board, we also need user-friendly number of pulsewidth modulation (PWM) turers, application notes, design guides, white development tools and libraries that allow fast generators, which enables us to control several papers and so on. It offers several hundred dri- implementation of the board’s peripherals. Am- motors and static converters at the same time. vers for powering and controlling LEDs in dif- bitious? Maybe, but nothing should deter you The cost of the control board needed to be ferent configurations, along with ready-to-use from becoming Master of Embedded Systems as low as possible too. In addition, it must be modules (power supply units, DMX controllers, Universe with the help of the Elektor Sceptre. possible to construct the board using a dimmers, etc.). In addition to optical systems, light detectors, hardware, etc., this DVD also addresses the main shortcoming of power LEDs: heating. This DVD contains more than 100 Ele- 0#"POPULATEDANDTESTED TESTSOFTWARELOADED Art.# 090559-91• $143.60 ktor articles on the subject of LEDs. soldering iron, without requiring use of a reflow oven. 0#"POPULATEDANDTESTED Art.# 090073-91 • $225.90 ISBN 978-90-5381-245-7 • $46.00 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! DVD Elektor 1990 www.elektor.com/shop ment of every electronics lab. However, the increased complexity of a switch-mode design This DVD-ROM contains the full range of scares away many potential builders, even 1990-1999 volumes (all 110 issues) of Elektor though it actually isn’t all that complicated if Electronics magazine (PDF). The more than you use a suitable combination of well-known 2,100 separate articles have been classified (month/year), but are also listed alphabetically by topic. A comprehensive index enables you to search the entire DVD. ISBN 978-0-905705-76-7 • $111.30 A power supply with adjustable output voltage and current limiting is part of the basic equip- through 1999 chronologically by their dates of publication UniLab technologies. This circuit is suitable for building Elektor US PO Box 180 Vernon, CT 06066 USA Phone: 860-875-2199 Fax: 860-871-0411 E-mail: [email protected] a single or dual power supply. 0#"ANDALLCOMPONENTSLESSPOWER TRANSFORMER Art.# 090786-71 • $103.30 Personal Download for [email protected] I © Circuit Cellar Kits & Modules 110 issues, more than 2,100 articles L ESSONS FROM THE TRENCHES by George Martin (USA) Put C Language to the Test (Part 3) Rules and Assignments In this third part of the Sudoku problem-solving exercise, you learn about a rules package and then receive some assignments. You’ve put C language to the test. Now a solution is within reach. July 2010 – Issue 240 L 54 et’s begin with a lesson. I’ve introduced some new (to us) C language operators—for example, all the file I/O. But we’re not doing enough work with files to make much of a point by focusing on all you can do with the file operations. I’ll save file I/O for a later date. I would like to talk about the % and / operators. The modulus operator (%) computes the remainder that results from performing integer division. So, 11 % 3 = 2. If you were to just divide x = 11/3, you would get the 3 as an answer. That’s the integer portion and the remainder is lost. If you want the remainder, you need to use the % operator. So, what’s the big deal? I’ll show you what. Remember that our database was organized as Puzzle.Block[b].Cell[c].Numb[n], where b, c, and n represented a specific block, cell, and number, respectively. But as humans, we want to talk about the rows and columns of a puzzle. We need a routine that takes a row number and column numbers and returns a block, cell, or number. And to do that, we’ll use the % operator. Consider a 16 × 16 grid. Start in the top left and fill in the grid with the following: 0123, 0123, 0123, 0123 for the first row; 4567, 4567, 4567, 4567 for the second row; 89AB, 89AB, 89AB, 89AB for the third row; and then CDEF, CDEF, CDEF, CDEF for the fourth row. You need to repeat this three more times to fill in the grid. Doing so numbers each of the cells in the puzzle. In the routine INT16 RowCol2iCell(INT16 Row, INT16 Col);, you find the statement return (4*(Row%4) + (Col%4));. This routine is passed the row and column that interests you. Using the % operator, it returns a number representing the cell. Look at the test values in Table 1. If you take another 4 × 4 grid and fill in this routine’s results, you’ll see that the table describes the cells of the puzzle. Another routine takes row and column numbers and returns a block number. That routine is INT16 RowCol2iBlock(INT16 Row, INT16 Col);. In that routine, you’ll find the statement return((Row/4) + 4*(Col/4));. This routine is passed the row and column that you are interested in. Using the / operator, it returns a number representing the block. I won’t build another test table, but you should. Remember: the / operator returns the dividend but not the remainder. Isn’t it better to see these operators in action that just remembering the rules by rote? RULES Now it’s time to implement the rules package. I started the rule design by assigning numbers to the rules starting with 1. (Brilliant!) CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Rules 1, 2, and 3 require that there only be one hex digit in each row, column, and block, respectively. Let’s take a look at the logic for Rule 3 in Listing 1. This rule is implemented by first looking at each of the blocks and then in a specific block looking at all the cells. If in one of the cells a number is found to be CCI_YES (that number is the valid number for the entire cell), mark all the numbers in the cell and CCI_NO (meaning it’s not this number) and then restore the original cell to CCI_YES. I implemented it in this manner because the code was most straightforward. And since the puzzle is held in RAM, doing all the writes to memory is not a time or performance penalty. This design would be much different if the RAM were slow and expensive (such as flash). We would apply more code to minimize the RAM usage. Rules 1 and 2 are the same, but they are applied to the rows and columns. In those routines, you will find that we start the searching by all the rows and then all the columns. But then you need to change from the Row Column notation to the Row 0 0 0 0 1 1 Column 0 3 4 7 0 3 Cell 0 3 0 3 4 7 Table 1—These are the test results for the RowCol2ICell() routine. Block Cell notation. Calls to simple routines convert from Row Column to Block Cell. You should look this over carefully. In your designs, I bet there will come a day you need to access a database you’ve created using several points of view. This is a very common situation you’ll encounter as your problems get more and more complicated. Great. We’re all done. SOLUTION GENERATION With the three basic rules running, puzzle solutions will just fall out. Well, I started running the code with inputs from a file. I ran the puzzle against Rules 1, 2, and 3 and then sent the output in SHOW format to the screen. The output of the puzzle in the SHOW format filled the screen and it was very difficult to see if anything was changing. So, my first addition was to keep a running total of all the numbers printed on the SHOW screen. This seemed to make sense. As numbers were eliminated, the sum was reduced. I found that numbers stopped being eliminated as I kept applying the rules, but the puzzle was not solved. “Oh, no! This won’t work,” I thought. “I can’t solve the problem!” I needed to look at the database in another format to see what was going on. I came up with the LIST command to print out the database in text format. Again, there was a lot of data. (I have since reduced the command’s output by eliminating all the CCI_NO responses.) I found that after applying Rules 1 through 3 some of the cells had all the numbers but one tagged as CCI_NO. The other number was tagged as CCI_MAYBE. Common sense tells you that whenever you come across this situation you should mark the lone CCI_MAYBE as CCI_YES. And Rule 4 does just that. The logjam was broken. Li sting 1—Rule 3 with only one number per block for (Block = 0; Block < 16; Block++) { for (Cell = 0; Cell < 16; Cell++) { for (Numb = 0; Numb < MAX_CANDIDATES; Numb++) { // for all numbers if (puzzle.block[Block].cell[Cell].numb[Numb] == CCI_YES) { Changed = 1; for (iCell = 0; iCell < 16; iCell++) { puzzle.block[Block].cell[iCell].numb[Numb] = CCI_NO; // Mark all as NO } puzzle.block[Block].cell[Cell].numb[Numb] = CCI_YES; // Restore original } } // end of for (Numb = 0; Numb < MAX_CANDIDATES; Numb++) { } // end of for (Cell = 0;iCell < 16;iCell++) { } // end of for (Block = 0; Block < 16; Block++) { return(Changed); } // end of INT16 RunRule3(void) { Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 //********************************************[ Public ]******* // // Rule 3 Only one number per Block. // //************************************************************* INT16 RunRule3(void) { INT16 Block, Cell, Numb; // variables for loop counters INT16 iBlock, iCell, iNumb; // variables for loop counters INT16 Changed = 0; 55 rules until none of the rules report any changes. What a great situation. If you are going to use this program, I suggest you get the rules reporting to work. I see a “challenge” here. Get the rules properly reporting the changed status and I’ll mention your name in a future article. If you plan to participate, please tell me if you’re a C beginner or a black belt. I’ll include that information. Listing 2—The “ideal” rules package Changed = 1; while (Changed) { Changed = 0; printf("Rule 1"); Changed += RunRule1(); printf(" 2"); Changed += RunRule2(); printf(" 3"); Changed += RunRule3(); printf("\n\r"); } MISSING RULES I believe there will be more rules for complicated (difficult) problems. Consider the following in a block: Now, running Rule 4 reduced the SHOW command’s output further. Rerunning Rules 1, 2, and 3 again produced lower results when running the SHOW command. In fact, running all the rules over and over generates a solution to the puzzle. Ta-da! A little bit of a back step. My intention was to have each rule return a value indicating if running that rule caused anything to be changed (1 = a change, 0 = no change). Well, I was trying to get the rules working, deal with my Rule 4 issue, and meet production deadlines. I never got the changed Y/N return for the rules to work reliably. Just think: if that had worked, I could have run the code fragment in Listing 2. The code fragment in Listing 2 will keep applying the READER FEEDBACK I recently received some interesting feedback from readers about this article series. Two examples follow. July 2010 – Issue 240 Ivey Cole wrote: “In the March issue of Circuit Cellar, you mention looking at a variety of C compilers. Was wondering if you’ve looked at Open Watcom, which is the ‘old’ Watcom compiler that went open many years ago. In my opinion it and the Borland packages were fairly comparable in the ‘good old days,’ with each having different features.” For more information about Open Watcom, go to www.openwatcom.org/index.php/Main_Page. 56 Dave Brown wrote: “I have been following your Circuit Cellar articles on the C language with interest. The Sudoku puzzle-solving Program looks like fun. I think I will join in. FYI, here is another free C compiler that may interest you. My son who is a grad student in chemistry needed a C compiler for a project. I pointed him to the Visual C++ Express Edition, which is free: www.microsoft.com/express/vc/.” Cell A has 1, 2, and 3 as candidates (CCI_MAYBE) Cell B has 2 and 3 as candidates Cell C has 2 and 3 as candidates I could make up a rule that would set Cell A to 1 since it’s the only place the number can be used in the block. And similar rules would apply for the rows and columns. I’ve seen this for solving very difficult 3 × 3 puzzles. I’ll leave it up to you to design this rule set and any other that comes along. If any come my way, I’ll see they get published. REVIEW Let’s review the steps we took to solve this problem. We had our initial design approach described using UML diagrams (Part 1, Circuit Cellar 236). These diagrams contained the routines gathered into modules and database design described in the notes. As work progressed, we discovered new routines and better methods for solving the problem (Part 2, Circuit Cellar 238). We also reorganized the code as work progressed. And now, with this article, we have a final solution with rules for solving the problem. Some of the rules were anticipated and one of the rules was a surprise. Think about how we worked our way through the problem. The most important thing to take away from this project is that conditions change and you should be flexible enough to address those changes. We didn’t even include any changes from a marketing department or a customer. Expect changes in the real world. As the design now stands, would you change it in anyway? I did not make the code universal for 2 × 2, 3 × 3, and 4 × 4 puzzle sizes. Would you change the database design, I/O features, or reorganize the routines in any way? Think about this and perhaps your next design will start off better. SUCCESS WITH C Well, did we just destroy Elektor’s Hexaduko puzzle challenge? Perhaps I should be looking for an alternative career. Just kidding. Hopefully, we just increased participation. On a more serious note, let me know what you think about this article series. I’ve already heard from some readers. (Refer to the sidebar.) Did you learn anything about writing C programs and UML? Are you now more CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com confident about attempting such a design? Do you think this series has helped you read and understand C programs? I Author’s note: There are many C-like languages and many procedural-type languages. For instance, Joachim Schueth of Bonn has published a Hexadoku solver written in Ada (www.schlaupelz.de/hexadokusolve.adb). No comments are shown as part of the code. But I’m mentioning this to show you that other solutions exist. Also, think about commenting your code if you intend to describe what’s going on and give others insight into what you are doing. I’m not criticizing Joachim Schueth; it looks well-written. Just think about commenting yours. Think about my comments. Are they sufficient to document the design? George Martin ([email protected]) began his career in the aerospace industry in 1969. After five years at a real job, he set out on his own and co-founded a design and manufacturing firm (www.embedded-designer.com). His designs typically include servomotion control, graphical input and output, data acquisition, and remote control systems. George is a charter member of the Ciarcia Design Works Team. He is currently working on a mobile communications system that announces highway info. He is also a nationally ranked revolver shooter. SOURCES CC386 C Compiler LadSoft | http://ladsoft.tripod.com/cc386.htm MagicDraw Modeling tool (v.9.5) No Magic, Inc. | www.magicdraw.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 George Martin’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — Put C Language to the Test (Part 1) A Sudoku Puzzle-Solving Program by George Martin Circuit Cellar 236, 2010 Ready to write a program in C language? Here you learn about starting a program for solving a Sudoku puzzle. Topics: C Language, Program, Sudoku, IDE, UML, database Go to: www.circuitcellar.com/magazine/236.html Text Adventure Gaming by Chris Cantrell Circuit Cellar 205, 2007 Do you like learning new languages? Try using a chip and the Cog Coordination language (CCL) for an interesting gaming application. Topics: Language, Programming, CCL, RISC, SD Card, FAT Go to: www.circuitcellar.com/magazine/205.html www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 — 57 F ROM THE BENCH by Jeff Bachiochi (USA) Application Communication with USB (Part 2) The Importance of Descriptors You know how a USB device goes through a number of states as it progresses during the enumeration process. The next topic to understand is the standard device descriptor, which is the first item in a device’s datasheet. July 2010 – Issue 240 I 58 must be the reincarnation of a cat. I’m curious about many things. In fact, I’ve used a number of my “nine lives” by letting my curiosity take precedence over the self-preservation instinct. Do you know anyone who can say they’ve never performed an act of stupidity at some point in their life? Somewhere along the line, we learn how fragile our bodies are and that tempting fate should not be an everyday experience. At this point, curiosity takes a backseat to personal safely. We are more apt, say, to learn about aerodynamics through references and modeling, rather than jumping off a cliff with a hang glider. I’ve been interested in USB since it was forced upon us years ago. Even though many manufacturers have given us the tools to use it, without having to know how it really works, I just can’t leave it at that. I want to know more about its operation. For those of you who might have similar feelings, I hope I can shed a little light on this by going through a simple USB project that will enumerate and transfer application data using assembly language. This project began last month. I encourage you to start there and get up to speed on the USB hardware peripheral—the serial interface engine (SIE) built into many of Microchip Technology PIC microcontrollers. While each manufacturer may arrange things differently, they all must obey the same rules. Thus, you should be able to take what you learn here and apply it to any micro. We left off looking at the start of the enumeration process as seen from the Beagle USB 480 protocol analyzer I use to display the bus activity between the USB host (my PC) and the project’s device circuitry. After forcing a USB reset, the host has requested a descriptor. Through the SETUP packet received by the SIE, I discovered that the host was requesting a standard device descriptor (SDD) via a GetDescriptor transfer. We know that the purpose of designing the USB interface was to make it user-friendly yet universal. That means that the host must be able to figure out how to access a device automatically when a user plugs it into the bus. To do this, a device must be able to answer all the questions the host will ask it. These questions have been predetermined by the USB specifications. So, as a device, we need to be ready to respond with the answers. The answers come from USB descriptors, a collection of information describing the device. Each descriptor uses an identical format to simplify the exchange of information. A descriptor begins with a length byte followed by a type byte. Let’s begin with the descriptors, as defined in this project, to describe its configuration to the host, the CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com the index of any string descriptor describing this Offset Field Size Format Description Project Value interface. The last 2 bytes 0 bLength 1 Number Descriptor length in bytes 0x12 define the attributes of the 1 bDescriptorType 1 Constant DEVICE 0x01 configuration (self-powered 2 bcdUSB 2 BCD USB Specification revision 0x0200 or supports remote wakeup) 4 bDeviceClass 2 Class Class Code 0x02 and the maximum power 5 bDeviceSubClass 2 SubClass Sub Class Code 0x00 consumption (if it were to 6 bDeviceProtocol 1 Protocol Protocol Code 0x00 require power through the 7 bMaxPacketSize0 1 Number Maximum packet size EP0 0x08 USB connector). 8 idVendor 1 ID Vendor ID 0x04D8 In this project, the host 10 idProduct 1 ID Product ID 0xFE96 discovers that this configu12 bcdDevice 1 BCD Device Revision 0x0000 ration (1) has two interfaces 14 iManufacturer 1 Index Manufacturer String Index 0x01 associated with it. It also finds that the device is self15 iProduct 2 Index Product String Index 0x02 powered and supports 16 iSerialNumber 1 Index Serial Number String Index 0x00 remote wakeup. If its local 17 bNumConfigurations 1 Number Maximum Device Configurations 0x01 power is removed, it would Table 1—The standard device descriptor describes general information about the device. It indicates to require 100 mA. While the the host how many configurations it should look for that are associated with the device. host discovered this configuration descriptor’s length your device supports. In this project, is only 9 bytes, it knew to look for a device descriptor, the configuration we have just one. total length value within this descripdescriptor, and the string descriptor. My SDD is 0x12 bytes long, so how tor. It can continue to read in addican the host get this if I’m using a tional transactions (using the “in” SDD maximum packet size of eight? If you token) until it has all of this informaA USB device has only one SDD as refer back to the first part of this tion. The host can then break down it is a global description of the device series, you’ll see that the host follows this data into additional descriptors and all its configurations. Table 1 its GetDescriptor set-up transaction looking for more information on each shows that this descriptor contains of the two interfaces. the version number of the USB specifi- with additional “in” token requests until it has received all it requires. But Appended to, and as part of, the cations that it conforms to, so the hold on to that thought; we haven’t total SCD are any additional descriphost will understand the rules it can discussed the “in” and “out” token tors that are required to fully define play by. yet. the device’s configuration. Here we Next are the device’s class and subhave two interfaces to define, and class. These define the kind of each will have its own interface device—in our case, it is the commuSCD descriptor. The first interface (internications device class, covering Unlike the SDD, there may be more face descriptor 0) has no alternative telecommunications and networking than one standard configuration setting—so its value is zero (the first devices. The communication device descriptor (SCD). Remember, the and only)—and the number of endclass has no subclass or device protonumber of configurations was defined points used for the interface is one. col, so these bytes are zero. The packback in the last byte of the SDD. In Also within the interface descriptor et size byte tells the host a packet’s this case, we’re just dealing with a are communication interface class (2), maximum size. For EndPoint0, that’s single configuration; therefore, we subclass (2), and protocol (1) values. In 8, 16, 32, or 64 bytes. need only one configuration descripNext, the device descriptor lists the tor. The configuration descriptor is very this descriptor, the host learns that interface 0 is of the communication vendor ID (that’s Microchip Technolocomplex. It is a container, if you will, class using the abstract control model gy), the product ID (that’s mine), and a for all the interface descriptors associathaving one endpoint. release or version number for my ed with this configuration. It uses the application. Because all this is kind of standard descriptor format so the host We know that USB devices require cryptic, the descriptor includes a num- knows the descriptor’s type and size by specific device drivers to be loaded on ber of bytes that can point to string the first 2 bytes (see the table posted on the PC. To support all possible USB descriptors that will describe the man- the Circuit Cellar FTP site). devices, this driver would be mamufacturer, the product, and the serial The SCD’s next 2 bytes define the moth. So, the driver that gets loaded for number using ASCII text. These may total size of all the descriptors associeach device contains only the subset show up in various places on your PC ated with this configuration. Follownecessary for its associated device. The when installing drivers or viewing sys- ing this is the actual number of interdriver gives the host the ability to tem information. Finally, one last byte faces supported by this configuration, know what descriptors to find for that indicates the number of configurations the number of this configuration, and particular device. The subclass 2 www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Standard Device Descriptor 59 Standard String Descriptor0 Offset Field Size Format Description Project Value 0 bLength 1 Number Descriptor length in bytes 0x04 1 bDesriptorType 1 Constant STRING 0x03 2 wLANGID 2 Number Country Code 0x0409 Standard String Descriptor1 Offset Field Size Format Description Project Value 0 bLength 1 Number Descriptor length in bytes 0x36 1 bDesriptorType 1 Constant STRING 0x03 2 bString N Number Text “Microchip Technology, Inc.” Standard String Descriptor2 Offset Field Size Format Description Project Value 0 bLength 1 Number Descriptor length in bytes 0x4C 1 bDesriptorType 1 Constant STRING 0x03 2 bString N Number Text “Imagine That (www.imaginethatnow.com)” July 2010 – Issue 240 Table 2—The standard string descriptors have two formats. String0 defines the language used by the host to talk to the user. The remaining strings contain ASCII text presented in a UNICODE presented string. 60 (abstract control model) has its own set of descriptors that are used to help describe its functions through an interface. There are 25 subtype descriptors for the communications class. We will be using four for this project: header, call management (CM), abstract control management (ACM), and the union functional descriptor. You can read about all of them in the communication class specifications. The header descriptor indicates the version of the specifications that the interface is adhering to. CM defines the call-handling capabilities—and there are none, in this case. The ACM identifies the capabilities of the interface. These include: network connection support; sending break, line, and serial states; and COMM features. Finally, the union descriptor defines the master interface (interface 0 in this case) and the subordinate interfaces. In this instance, there is only one other interface—interface 1. Following the subclass descriptors for this interface, you must include the endpoint descriptors for this interface. One endpoint is for this interface and its descriptor identifies the actual endpoint (EP1In) using an interrupt transfer type. This short descriptor also includes the packet size (64 bytes) and how often the host will poll for data (2 ms). The second interface (interface descriptor 1) has no alternative setting, so its value is zero (the first and only) and the number of endpoints used for the interface (two endpoints here). The data interface class (10) has no subclass and uses no protocol, so these values are zero. In this descriptor, the host learns that interface 1 is of the data class using no specific protocol and having two endpoints. This interface has no additional descriptors other than the two specified endpoint descriptors. One endpoint is defined as using endpoint (EP2Out) using a bulk transfer type. The second endpoint is defined as using endpoint (EP2In) using a bulk transfer type. Both endpoints will use a packet size of 64 bytes and request polls whenever there is bandwidth. SSD If any optional standard string descriptors (SSD) are used, the first descriptor must identify the language or languages (see Table 2). The 16-bit LANGIDs2 defines how the host should present text to user (i.e., “Hit a key to continue”). The remaining strings can give the user an ASCII text description of some cryptic value within the associated descriptor. In this project, the second SSD (1) is associated with the Manufacturer ID in the SDD and the text reads “Microchip Technology, Inc.” The third SSD (2) is associated with the product ID in the SDD and the text reads “Imagine That (www.imaginethatnow.com).” RETRIEVE DESCRIPTORS I reprinted the first page of transactions as captured by the USB 480 Protocol Analyzer in Photo 1 because it demonstrates how the host interacts with this device when plugged into the USB and enumeration begins. We left off last month with the SIE setting the transaction complete interrupt after receiving the set-up token via EP0. The buffer descriptor (BD0) associated with default endpoint (EP0Out) pointed us to the 8-byte EP0Out buffer that held the packet data received by the SIE. Upon moving and interrogating the data, it was found to be requesting 64 characters via a GetDescriptor request (0x80). The descriptor data we discussed above has been placed at the top of the program memory space by the assembler, so we know where it can be found. You must prepare an 8-byte packet response for the SIE before clearing the interrupt. Once you clear the interrupt, the SIE will acknowledge the SETUP packet and the host will send an IN packet to get our data. You best be ready. To get the requested information, USB_desc_ptr is preloaded with the offset address of the character we want from the descriptor table. A call to the Descriptor routine loads the address of the beginning of the descriptor table into a table pointer that will fetch characters CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Personal Download for [email protected] I © Circuit Cellar from the program memory space. The offset is added to the table pointer, a character is fetched from that address, and returned. The character can be then transferred to the EP0In buffer and the next character sought. When EpoIn buffer is filled we can leave the interrupt routine and clear the interrupt, the SIE acknowledges the host. Refer to Photo 1a. The host has continued with an IN token. The SIE will again set the transaction complete interrupt after sending the data we preloaded into EP0In buffer. Note that the 8-byte DATA1 packet of the IN token has the first eight characters of the SDD. This time the interrupt routine will discover an IN token request from the USTAT and branch to the ProcessInToken routine. Since I stored the SETUP token’s GetDescriptor request in USB_dev_req, I know how I got here and must continue to preload 8-byte packets of data into the EP0In buffer until all the requested data has been sent, I run out of data to send, or the request is cancelled by a new SETUP token. As you can see in Photo 1a, notice that after the host acknowledged the receipt of the first IN data, it sent an OUT token. This is an acknowledgment that the transfer request is complete. It July 2010 – Issue 240 a) 62 decided it has what it wants. Not only did it find out what the maximum packet size was (0x08), but also that the SDD is 0x12 bytes in length (no sense asking for more than that). Note that this GetDeviceDescriptor transfer contained three stages: a setup transaction (in this case one), a data transaction, and a status transaction. Each transaction stage has a token phase, a data phase, and a handshake phase (see Figure 1). ADDRESS STATE Up to this point, the communication has taken place on the default address UADDR=0. The host is now ready to assign the device a real address. The host sends a SETUP token. The receipt of the token by the device’s SIE causes another transaction complete interrupt. USTAT reveals it was via EP0Out. By processing the EP0Out Buffer, we find the 8-byte packet contains a SET_ADDRESS request (0x00) and the new address is 0x06. While you might be tempted to change UADDR immediately, hold on. Since this is only the SETUP stage of this transfer, we must continue using the old address until the transfer is complete. This is the only time when you need to finish things before making use of the data received. Since this request has no DATA stage, we just preload a zero-length packet into the EP0In Buffer and it is used as the HANDSHAKE stage. We exit the interrupt routine, clearing the interrupt and the SIE ACK is the SETUP token. The host sends an IN token (the beginning of the HANDSHAKE stage), the SIE receives the request and sends the EP0IN Buffer, and sets the transaction complete interrupt. USTAT reveals it was via EP0In. Since we stored the SETUP token’s SET_ADDRESS request in USB_dev_req, we know how we got here. There is nothing expected as this is the end of the SetAddress request and all transactions are complete. We are now clear to change UADDR to 0x06. And, don’t forget to reset our USB_dev_req to 0xFF (NO_REQUEST). Once we leave the interrupt routine, clearing the interrupt flag, we have transitioned into the ADDRESS_STATE. CONFIGURE STATE Note that the next SETUP token (and all subsequent tokens) are sent to the new address 0x06. Now the device pays attention only to those tokens containing the new address. This new SETUP token is again requesting the b) Photo 1a—The Beagle protocol analyzer’s capture of the USB traffic clearly shows the transfer requests of a device beginning the enumeration process. Every device begins with a default address of 0 and is reassigned a new address by the SetAddress request seen here. b—The enumeration process ends when the host requests that a device be configured to one of its declared configurations. This project has a single configuration. Once configured, the host will begin polling for information according to the Endpoint Descriptors, as seen at the bottom here as IN_NAKs to EP2 and EP1. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com Personal Download for [email protected] I © Circuit Cellar Figure 1—This is a potential sequence of three transactions that will complete a control transfer. Each transaction or stage consists of a Token, Data, and Acknowledgement Phase or Packet. USB Reset URSTIF Start-of-frame SOFIF From host From host To host SETUP Token Data ACK From host To host From host IN Token Data ACK From host From host To host OUT Token Empty data ACK Set TRNIF Set TRNIF Set TRNIF Transaction Transaction complete RESET SOF SETUP DATA SOF STATUS Differential data Control transfer* 1-ms frame July 2010 – Issue 240 * The control transfer shown here is only an example showing events that can occur for every transaction. Typical control transfers will spread across multiple frames 64 GetDeviceDescriptor. This time it is only asking for 0x12 bytes. The host will continue to gain knowledge about the device by sending GetConfigurationDescriptor and GetStringDescriptor requests. Once it knows everything, the host will request a SetConfiguration and finally GetLineCoding and SetControlLineState via the class-specific requests. The SetConfiguration request gives the device permission to use a specific configuration. In this case, we have defined only one. The configuration uses two interfaces and now we set them up using EP1In as an ACM interface using interrupt transfers (the control interface) and EP2In and EP2Out as the data interface using bulk transfers. The class-specific GetLineCoding request informs the host that our (virtual) UART is set to receive 8 data bits, with 1 stop bit, and no parity at a data rate of 115,200 bps. These are values I chose and stored in initialized variables so that they can be recalled and changed if necessary. I could set up the microcontroller’s (physical) UART and this project would be a USB-to-UART interface, but that is an application left up to you. The SetControlLineState request presents the device with RTS and DTR states, which are controlled by the host. The device is now in the CONFIGURE_STATE. It will be listed as a (virtual) COMM port in any application running on the PC that can use a serial port for data communication. The host starts to poll both interfaces of the device. It is polling EP1In looking for any control information that the device might want to convey to the host. It is also looking for any data on EP2In that the device may want to transfer to the host. The device is happy with the status quo and has no information to pass on, so the SIE has not been given control over any of the IN endpoints. It will NAK all polls, which tells the host that it’s busy and to try again later. By “later” I mean (as defined in the standard endpoint descriptor) every two frames (2 ms) for the interrupt endpoint and whenever there is room for the bulk endpoint. When an application on the PC selects this COMM port for use, things begin to happen once again. In my next article, I’ll look at the two conversations that take place through the configured device’s newly established endpoints, EP1 and EP2. 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. PROJECT FILES To download the descriptor table, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2010/240. SOURCES PIC18F4450 Microcontroller Microchip Technology, Inc. | www.microchip.com Beagle USB 480 Protocol analyzer Total Phase, Inc. | www.totalphase.com NEED-TO-KNOW INFO Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Jeff Bachiochi’s Issue 240 article, the Circuit Cellar staff recommends the following content: — Create a Hybrid Hub by Jeff Bachiochi Circuit Cellar 170, 2004 Jeff shows you how to build a four-port USB hub with a TPS2071 power controller, a data controller, and a few other simple parts. Topics: USB, Hub, Power Go to: www.circuitcellar.com/magazine/170toc.htm — Get Started with PIC USB Connectivity by Jeff Bachiochi Circuit Cellar 219, 2008 Get started with USB. Jeff presents MCUs with USB peripheral support, embedded hosting, and more. Topics: USB, OTG, HNP Protocol, TPL Go to: www.circuitcellar.com/magazine/219.html CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com 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. 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. 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. Personal Download for [email protected] I © Circuit Cellar S ILICON UPDATE by Tom Cantrell (USA) Wall Whisperer A Fresh Take on Powerline Communication Powerline communication isn’t a new concept, but as the Rodney Dangerfield of networks, it just can’t get respect. So, maybe your experience with early versions was less than satisfying. Now Cypress is ready to give it another go. How about you? July 2010 – Issue 240 “H 66 ome Automation” is seemingly an oxymoron, one of those “Tomorrow’s Technology of Tomorrow” that just can’t get off the starting block. I’ve got a relatively new home, and it’s about as “smart” as a rock with just a few brain cells (e.g., a thermostat and a garage door opener). Half the battle is the skeletons in the closet. Like a lot of you, I had my fling with X10 many years ago. And no doubt, like a lot of you, it didn’t last long. The performance and reliability was just too iffy for me to convince myself to put a lot of work into trying to do something meaningful. The concept of powerline communication (PLC for short) took another hit with the misguided premise of turning your power company into an ISP. The concept of “Broadband over Power Line” (aka BPL) may have sounded good at the time, but as a practical matter, the idea it can compete with DSL and cable is fading away.[1] With its dubious track record, I haven’t really Photo 1—Powerline communications is bothered to keep track of making a comeback with a new generation PLC. But taking off the of high-speed units such as the 200-Mbps Powerline 200 AV+ from Netgear. blinders, I can see that there are some interesting developments afoot. You’ll see what I mean if you Google acronyms like “P1901,” “G.hn,” and “UPA.”[2] Or toddle over to your nearest BUY MORE big box and check out the latest PLC offerings from networking heavyweights like Linksys and Netgear (see Photo 1). Their newest powerline gadgets claim to deliver up to 200 Mbps, with 500 Mbps and even 1 G on the drawing board. While it’s generally understood these claims greatly overstate actual throughput, it’s still fast by any measure. Beyond some metering and “smart grid” applications, BPL may be dead as far as your power company is concerned, but the concept would seem to have much better prospects in smaller scale applications. This is where Cypress Semiconductor steps in with three new PLC-capable chips. Let’s take a closer look and see how they let embedded applications hitch a ride on the power line. Heck, the wires are already there, so why not use them? The Cypress lineup comprises three different part numbers—the CY8CPLC10, CY8CPLC20, and CY8CLED16P01—that target somewhat different applications. As an interesting aside, the silicon under the hood is the same for the trio—namely, a standard PSoC, with differentiation provided using its programmable hardware and software capabilities. Let’s start with the CY8CPLC20 (see Figure 1), which is the most general-purpose of the trio. The PLC20 is simple enough to describe: it’s a PSoC flash memory MCU—specifically, a CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com static applications, returned and you can configure the but if the network stack for up to four automatic retries. FSK_IN RSVD 2 27 configuration is large After the address is a “Command” PO[4], A, IO FSK_OUT 3 26 and dynamic (i.e., byte. Sixteen commands are defined RSVD A, I, P0[1] 4 25 number of nodes (Table 1) with another 32 reserved and RSVD TX_ SHUTDOWN 5 24 the rest available for application use. unknown and changP2[5] 6 23 P2[6], EXTERNAL VREF ing), consider using After the command are “Payload AGND A, I, P2[3] 7 22 SSOP RXCOMP_IN A, I, P2[1] 8 21 Length” (0 to 31 bytes), a sequence the “PLT + network RXCOMP_OUT RSVD 9 20 stack” option. number (to detect lost/duplicate packXRES 12C SCL, P1[7] 10 19 ets) and a header CRC. These are folBehind the Cypress P1[6] 12C SDA, P1[5] 11 18 lowed by the payload itself and an network stack is the P1[4], EXTCLK P1[3] 12 17 overall packet CRC. fairly sophisticated P1[2] 12C SCL, XTALIN, P1[1] 13 16 P1[0], XTALOUT I2C SDA VSS 14 15 The media access strategy implepacket structure mented by the stack features “carrier shown in Figure 3. sense” and “collision avoidance. Each Let’s go through it to Figure 1—With the same silicon under the hood, the new Cypress powerline communication chips have a similar pinout node waits until the line is idle, but see some of the and are available in 28-pin (shown here) and 48-pin versions. then further waits a random amount embellishments the of time (between 85 and 115 ms) stack provides, startbefore initiating transmission. WithPSoC-1 (i.e., M8C core)—whose program- ing with addressing. You can see the out this “random backoff,” every node network has plenty of elbow room mable hardware is configured with a would try to jump in as soon as the power-line modem (see Figure 2), option- with 8-, 16- and 64-bit address options, line goes idle and the network would the latter taking advantage of the ally fronted with a bit of software impleunique 64-bit ID each chip comes with get paralyzed by collisions. menting a simple network protocol. Of course, there’s no free lunch. The from the factory. There are also Now before you get too excited price for the network stack’s reliabili“group” and “broadcast” options that thinking about hooking up your ty and ease of use may be worth it, support one-to-many and many-to-one HDTV, realize this modem is a simple but there is a price to pay—namely, associations. half-duplex 2,400-bps unit with perthroughput. You can see that in the The “Service Type” bit up front is formance that harkens back to the worst case (64-bit addresses) transferan innocuous name for a key feature dial-up days. It’s speedy enough for a ring a single byte payload would of the protocol, namely acknowledgelot of simple and useful applications. require sending a 22-byte packet (i.e., a ment. When enabled, receivers will Just be careful not to bite off more 22:1 packet/payload ratio). Fortunateautomatically acknowledge receipt, bandwidth than the chip can chew. ly, many applications will be able to transmitters will timeout in half a When you checkout the power line use shorter addresses and/or longer second if the acknowledgment isn’t transceiver (PLT) object from the PSoC payloads to reduce the Designer library, there are overhead. For instance, three options to choose Network protocol with 8-bit addresses and from: basic PLT, PLT + net31-byte payloads, the work software, and PLT + packet/payload ratio network software + I2C. Digital would approach 1:1 (e.g., The basic PLT option receiver Digital 1.2 for a 38-byte packet gives you raw byte-at-aHysteresis transmitter comparator carrying a 31 byte paytime access to the data Logic ‘1’ or Low-pass load). On the other hand, link, much like a UART. Logic ‘0’ Local filter External oscillator keep in mind that interThe automatically generatlow-pass filter Modulator Correlator mittent interference will ed API allows configuring Square wave be more likely to disrupt the modem (e.g., bit rate, at FSK IF Band a longer packet than a gain, noise threshold), frequencies pass filter Local oscillator shorter one. checking if the line is busy Mixer Programmable That brings us to the (i.e., voltage higher than gain amplifier HF Band PLC10 chip, which uticonfigured threshold), and pass filter lizes the final “PLT + nettransmitting and receiving RX work stack + I2C” option. bytes by interrupt or amplifier In this case, access to the polling. With this option PLT and network stack is you’ll have to handle all Coupling circuit rerouted via the external the network administraI2C interface. You don’t tion and error handling yourself. It’s probably OK have any direct access to Fi gure 2 —Cypress takes advantage of the PSoC’s programmable hardware to implement a 2,400-bps, half-duplex FSK powerline modem. for simple and relatively the on-chip processor. A, I, P0[7] VDD 28 www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Receiver Transmitter Powerline modem PHY 1 67 Introducing Pololu’s new Maestro USB Servo Controllers Conduct a symphony of servos. Bit offset 7 0 6 0 5 0 #1354 Mini Maestro 18-Channel $39.95 #1356 Mini Maestro 24-Channel $49.95 Pololu's 6-channel Micro Maestro and new 12-, 18-, and 24-channel Mini Maestros take serial servo controllers to the next level by incorporating native USB control for easy connection to a PC and programmability via a simple scripting language for self-contained, host controller-free applications. Whether you want the best servo controller available or a versatile, general-purpose I/O control board, these compact devices will deliver. Three control methods: USB, TTL serial, and internal scripting Free configuration and control application with motion sequencer Channels can be used for digital I/O or up to 12 analog inputs Individual servo speed and acceleration control for each channel Up to 8 KB of internal scripting memory (~3000 servo positions) July 2010 – Issue 240 0.25 us servo pulse resolution with pulse rate up to 333 Hz 68 more information at www.pololu.com/maestro 0 3 x 2 1 x X 0 Byte offset 0 X 0x02 1 0x01 2 0x09 xx #1350 Micro Maestro 6-Channel $19.95 #1352 Mini Maestro 12-Channel $29.95 4 3 4 0x03 xx Xx 5 0xA1 6 0xA2 7 0xA3 8 Xx 9 SA Type Command ID DA Type Payload length Destination address Payload Source address Service type Figure 3—The Cypress powerline communicaton stack raises the level of network abstraction utilizing the packet structure shown here. Rather the chip acts a self-contained powerline “coprocessor” working under the direction of an external MCU of your own choosing. Although most PLC headlines revolve around 120/240-VAC, the Cypress solution is just as well-suited for lower voltage AC and DC powerline designs. Enter the CY8CLED16P01, which targets LED lighting applications, drawing from a library of hardware and software functions such as dimming, temperature compensation, color mixing and closed loop optical feedback. Another low voltage application that comes to mind would be vehicles where data would ride on the 12-VDC power bus. Just the thing for moving some bits bumper-to-bumper and everywhere inbetween (e.g., using lighting and accessory power connections) without stringing a bunch of extra wire. AC/DC “Eavesdropping aliens and the industrial archaeologists of the future may well wonder why we built a phased array across the north of England to beam credit card numbers and digital images of naked ladies into the atmosphere.”—Nick Long of the Low Power Radio Association (www.lpra.org). These days, silicon is so advanced that most designs Command ID Command Name involve little more than slapping 0x01 SetRemote_TXEnable down a few Wunderchips like Lego 0x03 SetRemote_ExtendedAddr blocks. And so it is with the 0x04 SetRemote_LogicalAddr Cypress chips which handle all 0x05 GetRemote_LogicalAddr manner of applications with 0x06 GetRemote_PhysicalAddr aplomb. But when it comes to 0x07 GetRemote_State actually getting the data on and off 0x08 GetRemote_Version a high-voltage powerline, there’s 0x09 SendRemote_Data 0x0A RequestRemote_Data still a need for some old-school 0x0B ResponseRemote_Data circuitry to deal with unique safe0x0C SetRemote_BIU ty and regulatory issues. Fortu0x0D SetRemote_ThresholdValue nately, Cypress has an excellent 0x0E SetRemote_GroupMembership app note that addresses the subject 0x0F GetRemote_GroupMembership in great detail.[3] Here are some of the highlights. Tabl e 1 —The network stack option eases applicaMaking “The last inch” contion software development by providing a number of high-level commands. nection involves three functions: CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com the Cypress high-voltage CY3274 development kit. More on the kit in a moment; but for now, just note the nontrivial collection of transformers, op-amps, resistors, capacitors, diodes and such (more under the board) required to power-up your data. Before moving on, I should say a few words about one controversial aspect of PLC alluded to in the quote above—namely, potential pollution of Accuracy Sensitivity transmit filtering and amplification, receive filtering, and electrical coupling. And, of course, there’s also the usual power supply circuits (e.g., 120/240 VAC to 5-V DC switcher) to power the Cypress chip itself along with any other digital logic. Put it altogether and the powerline interface turns out to be the tail wagging the chip. A picture is worth a thousand words and Photo 2 shows Great Value in Test & Measurement Photo 2—A pair of CY3274 kits makes it easy (if not cheap at $624 each) to evaluate the new Cypress powerline communication chips. The kit includes a programmer for downloading code and an I 2C “wiggler” (attached to the board on the right) for exercising the chip’s PLC10 I 2C co-processor mode. from $4,422 250MHz/350 MHz 2/4 Channel Oscilloscope HMO Series DSO/MSO with 8/16 logic channels (Mixed Signal Opt. HO3508) Serial Bus Trigger and decode I2C, SPI, UART/RS-232 (Option) Pass Fail Test based on Masks Low noise fan from $1,419 Programmable 2/3/4 Channel Power Supply HMP Series HMP2020: 1x 0…32V/0…10A 1x 0…5.5V/0…5A HMP2030: 2x 0…32V/0…5A 1x 0…5.5V/0…5A HMP4030: 3x 0…32V/0…10A HMP4040: 4x 0…32V/0…10A from $3,581 1GHz/3GHz Spectrum Analyzer HMS Series with and without TG Frequency Range 100kHz…3GHz Measurement Range -114…+20dBm DANL -125dBm/-135dBm (Preamp.) Resolution Bandwitdh 100Hz…1MHz Standard EMI RBWs (-6dB) included 6.5“ TFT VGA Display, DVI Output Quality $2,011 20Hz…200kHz Basic Accuracy 0.05% Functions: L, C, R, |Z|, X, |Y|, G, B, D, Q, , Δ Programmable U & I Bias HAPRO Electronics Photo 3—The Cypress chips aren’t really “new.” They’re standard PSoCs upgraded with powerline communication features using the chip’s programmable hardware and software capability, all under the purview of the familiar PSoC Designer tool. www.circuitcellar.com • Tel: +1-516-794-4080 · Fax: +1-516-794-1855 [email protected] www.haproelectronics.com · www.hameg.com CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Simplicity LCR-Bridge HM8118 69 Photo 4—Configured as a PLC10, access to the powerline is via an I2C interface. The kit includes “PLC Console” software that utilizes the included I2C “wiggler” to evaluate that capability. July 2010 – Issue 240 the radio spectrum. Amateur radio operators have been raising the red flag for years and have kept regulatory agencies’ (e.g., FCC) feet to the fire. Presumably, the demise of the fullfledged BPL concept (i.e., power company as ISP) will provide some solace for those concerned. Hopefully, limiting the reach (i.e., between walls vs. overhead lines) will mitigate the spectrum pollution concerns as well. Cypress is quick to point out their design is compliant with a variety of emission, immunity, and safety regulations and the fact they’ve incorporated specific features (e.g., transmit filtering) to try to be a good neighbor. Now, as we’ve seen on Wall Street, the fact something “meets regulations” doesn’t mean it’s not going to cause problems if the regulations and/or regulators are inept. But that’s not a “technical issue,” it’s a political one. Those who are concerned are fully entitled to stand up for their rights, but the place to hold the protest rally is Washington, DC, not Silicon Valley. 70 SHOCK IT TO ME Hopefully, the clever phrase you just read will get your attention. Needless to say, if you’re going to be playing around PLC, don’t! “Playing around” isn’t something you do with a mains voltage. It’s OK to poke willy-nilly at digital logic, because if something goes wrong, the chips lose. Make a mistake with 120/240 VAC and you lose. Turning our attention back to the Cypress CY3274 development kit, another “shocking” aspect becomes apparent, namely sticker shock. These puppies (mains- and low-voltage versions are available) are a whopping $642 each not to mention that you need at least two of them to do anything. Bracketing the CY3274 kit are some simpler, and less costly ($299) demo boards and at the top end ($951) a CY8CLED16P01 kit with LED daughter card. The price is high, but at least the CY3274 kit is replete with features. The built-in breadboard and LCD make for instant out-of-the-box gratification and easy prototyping. Recalling the difference between the PLC20 and PLC10 chips is a matter of programmability, the kit can support development for both. For developing PLC20 apps you utilize the popular and well-proven PSoC Designer tool, with hardware and software libraries updated to support the powerline transceiver module (see Photo 3). The kit includes a USB plugin programmer to burn your own code into the PSoC, noting that a fullfledged debugger is an extra cost item. Using the programmer, you can download the aforementioned “PLT + network stack + I2C” configuration to make the PLC20 on the board act like a PLC10 co-processor under the direction of an external host via an I2C connector on the edge of the board. A very nice touch is that the kit also includes a USB-to-I2C wiggler and powerline control panel software for the PC. With two kits and their wigglers you can plug into two power outlets, two USB ports and run two copies of the control panel to exercise the network from the comfort of your PC (see Photo 4). The quick-start guide has you wire up the LCD and then program each board with a simple PLC20 application, one board as a transmitter and one as a receiver. When you push a button on the transmitter it reads the on-board DIP switch and sends the data to the receiver, which in turn displays the received data on its LCD. I’m all for keeping it simple, but Cypress could have made this demo a little more useful. As an initial experiment, I wanted to do a quick site survey of my house wiring. Exercise is a good thing, but the prospect of running up and down stairs pushing the switch on the transmitter and then checking the receiver, for each outlet no less, wasn’t appealing. Fortunately the CD in the kit has all the demo projects and software (see Listing 1). It’s testimony to PSoC Designer that even though I haven’t used the tool in awhile, it was a nobrainer to tweak the demo code to have the transmitter repeatedly send a unique message without having to push the switch. Now I could make just make one pass through the house with the receiver in hand to check reception at each outlet. Next, I reprogrammed the boards to act like PLC10s and used the two I2C wigglers with two copies of the control panel software to get a little deeper under the hood. Notably, the control panel allows you to tweak key parameters, such as gain and noise threshold, to see their effect. So how’d it all work out? Quite well, I’d say. But note that an exhaustive and authoritative test would be a much bigger job. So let me just tell you what CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com I saw, but as well what I didn’t see (i.e., issues a real-world designer would have to question, test and design around). Right off the bat, you’ll have to deal with the reality that there’s good chance that two particular outlets won’t be able to talk to each other. At least that’s true for locales that use “split phase” distribution, which brings, for example, 240 V to the panel and then splits it into separate 120-V legs. Sure enough, my simple walk-around “Can you hear me now?” test confirmed some half the outlets were inaccessible from the other half. Interestingly, and a bit of good news, was the fact that the legs seemed rather well intermixed—for example, between floors and side-to-side in my two story house. There are a lot of AC outlets in a modern house—maybe four to six per room (which is a big advantage over the alternative of piggybacking on phone wires and coax)—and it generally seemed that if one outlet was dead a nearby one worked. But your mileage may vary, and unless you’ve got a wiring diagram, your safest option is to try before you buy. A related gotcha is that all outlets aren’t created equal, the irony being a “better” outlet in terms of power delivery may be worse for communication. Sure enough, plugging my test setup into a UPS with surge protector confirmed it was real good at killing ones and zeros as well as surges. That’s something to consider if a particular installation is prone to lightning or otherwise destructive power spikes. And what about power failures? Interestingly, I don’t see any reason communication couldn’t continue which isn’t the case for schemes, such as X10, that rely on zero crossing. Of course, there’s the catch-22 that since you can’t use a UPS each gadget would need a battery, a dubious solution counter to the fundamental premise. Better just figure if the power goes off, so does you application. Presuming you’ve got plain-vanilla outlets that can see each other, the next question is how well the link works. Show typical house wiring, with its ad hoc layout, un-terminated stubs, power strips, extension cords, etc. to a network guru and they would laugh out loud. The topology is very inhospitable and things only get worse when you consider all the sources of noise such as motors, fluorescent lights, dimmers, and so on. While the Cypress network stack brings a lot of features to the table, it doesn’t do everything. There is one API call that automatically tests the line noise level and sets the noise threshold for determining if the line is “busy.” But beyond that your own software will have to handle features such as adaptive gain settings. Another embellishment would be security with the understanding that signals may leak between properties that share a transformer. Next I used PSoC Designer to further tweak the demo software to track packet errors and display the count on the LCD. I set up the units at opposite corners of the house (bottom floor left, top floor right) and let it run overnight. Checking next morning I discovered the unit had detected a grand total of 10 errors, about one per hour. That’s quite impressive considering I was sending an 8-byte packet (8bit addressing, 1-byte payload) about once per second, making for an overall packet error rate of less than 0.01%. Switching back to the PLC Console mode (i.e., using the I2C wigglers) confirmed similarly good results, at least with a simple one-way test, but digging a little deeper revealed some issues. On the receiver side, somewhere along the line between the I2C connection, USB and the PLC Console void main() { BYTE bTemp; LCD_Start(); // Start the LCD Module PLT_Start(); // Start the Powerline Transceiver TX_LED_Start();RX_LED_Start();BIU_LED_Start(); // Start the powerline comm. LEDs // Set the baud rate to 2400 bps with a 3 kHz deviation PLT_Memory_Array[Modem_Config] = (Modem_TXDelay_7ms|Modem_FSKBW_3M|Modem_BPS_2400); PLT_Memory_Array[TX_Gain] = 0x0b; // Set the TX Gain to 0.375x PLT_Memory_Array[RX_Gain] = 0x00; // Set the logical address of the PLC20 Receiver board to 0x01 PLT_Memory_Array[Local_LA_LSB] = 0x01; // Enable the TX and RX and allow the RX buffer to be overwritten PLT_Memory_Array[PLC_Mode] = (TX_Enable|RX_Enable|RX_Override); LCD_Position(0,0); LCD_PrCString("PLC20 RX"); while (1) { PLT_Poll(); // Run the network protocol to update memory array bTemp = PLT_Memory_Array[INT_Status]; if ((bTemp & Status_RX_Data_Available) && (PLT_Memory_Array[RX_CommandID] == CMD_SENDMSG) && (PLT_Memory_Array[RX_SA] == 0x02)) // Process the next block of code only after a new message is received { LCD_Position(1,0); LCD_PrCString("RX Data = 0x"); LCD_PrHexByte(PLT_Memory_Array[RX_Data]); // Display the data received on the LCD PLT_Memory_Array[RX_Message_INFO] = 0x00; // Reset the RX Message Info variable } } } www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 Listi ng 1 —Taking advantage of the Cypress network stack API makes it easy to send and receive data via the powerline. Shown here is the receive routine utilized by the demo software that comes with the CY3274 kit. 71 Edition A S U r o t k Ele usa / m o c . r o t k www.ele “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 ] January 2010 US $ 7.95 - Canada $ 7.95 [Analog Digital Micro controllers & Embedded December 2009 Audio Test & Measurement ] US $ 7.95 - Canada $ 7.95 [Analog Digital Micro controllers & Embedded www.elektor.com January 2010 Audio Test & Measurement ] US $ 7.95 - Canada $ 7.95 www.elektorusa.com There’s More Preselector forthan just USB! Life Elektoto r SD R ded Audio ollers & Embed l Microcontr [Analog Digita February 2010 ent ] Test & Measurem $ 7.95 US $ 7.95 - Canada Her e’s the USB Magic Eye automat ic tuning upgrade ! Put a Stop to Throwawayism! www.elektor.c om Buses USB and I2C Energybeyond Sav om www.elektor.c Subscribe to Elektor now! ings from Home Autom ation Fourier Analysis using Standards com pared LTspice & Excel Tech ATM18 There’s Mor nolo gy to Life than just USB!e Proj N ACKDOW Dimmer with a Micro a Sto PFCPutCR ects Logic Analyzer USB Magic Eye Throw led! eayism Christmas Hol p toto awa rev facs Cirrcuit Buses mp riday we po 13 pag yo s esnd La be of beg US Br’san inne andd I2C junk box projects My First AVR-USB ER olsPOW ing [ Fou TAwTH S rieerToE An ign aly des VEingGO ,NEW DIY U’18 lingsis usi The YO ngPROJECT ATM rc , coo ling ard trol 7 u con 0 follo , w LTs o picthe S e story ds on test l Analogue Digita Embedded controllers & Audio Micro nt ] Test & Measureme Join the fascinating world of electronics worldwide! February 2010 2pen Han Lo gic AnalOyz TS 6 NEW PROJerEC ty paci ery Ca Batt ker Chec & Excel oth ueto TTL Blgle Don ain ke Ch orbi Mot elektor.com stem PA Sy LET THE SCEPTER RULE! 7 A 32-bit ARM g fast prototypin system Creative & fresh articles since 1961 applications design for AVR Low power e h DMX Interfac LED Mixer wit Chip Linux on a ar Parking Rad ... Ultra-compact ULO D MOD amplifier fledged stereo $ 7.95 US $ 7.95 - Canada A full- PUZZLE H ELECTRONICS WIN $100 WIT Electronics projects to delight and educate in diverse areas of electronics ues 11 Iss the ing includ e doubl r e m t sum or jus f e u s is 5* $39.9 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 Personal Download for [email protected] I © Circuit Cellar electronics worldwide electronics worldwide GUI things were getting bogged down to the point that the receiver couldn’t keep up with even a few incoming messages per second. I noticed the little “CPU tachometer” widget on my PC screen was redlining, something that almost never happens. Without turning on the software option that allows received packets to be overwritten—or, alternatively, the option to insert a delay between packets on the transmitter side—the receiver couldn’t keep up. Finally, I performed a pseudo-full-duplex stress test by having the nodes send and receive messages to each other simultaneously, a scenario which caused the number of errors to skyrocket. One explanation might be that the collision avoidance scheme isn’t sophisticated enough to deal with such blatant abuse. But it just as well could be issues with the PC/I2C/GUI lash-up as described above. Clearly, a real evaluation of performance and reliability will be better served with a dedicated test configuration. For a PLC20, that would be native code test routines running on the internal PSoC, while for the PLC10 it would be diagnostic software on an external MCU. Bottom line, my experience is a reminder to keep your expectations in check understanding performance is limited, the link isn’t perfect, and errors will occur. closed loop acknowledgement capability at least you’ll know when a packet is lost. Detected errors are a chore, but undetected ones are a showstopper. Although less obvious, I’m thinking the sleeper opportunity is non-mains applications such as low-voltage lighting, vehicles, and indeed anything with a power cord. Power, and data, to the people! I 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]. REFERENCES [1] J. Leydon, “Powerline Networking Firm Suffers Brownout,” The Register, 2002, www.theregister.co.uk/ 2002/03/28/power_line_networking_firm_suffers/. [2] V. Oksman and S. Galli, “G.hn: The New ITU-T Home Networking Standard,” IEEE Communications Magazine, 2009. [3] J. Hushley, “Cypress Powerline Communications Board Design Analysis,” 001-55427, Cypress Semiconductor, 2009, www.cypress.com/?docID=18145. SOURCE ONE WIRE WORLD When it comes to mains powerline communication, the Cypress solution is definitely a step up from something like X10. Yes, it isn’t perfect, but thanks to the CY8CPLC10, CY8CPLC20, and CY8CLED16P01 Powerline communication chips Cypress Semiconductor | www.cypress.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. Go to: www.circuitcellar.com/magazine/229.html — Power Line Modems Meet Home Control by Brian Millier Circuit Cellar 142, 2002 A poorly designed control system prevented Brian’s heat recovery ventilators from being effective. So, he tried powerline tech. Topics: Powerline, FSK, Control Go to: www.circuitcellar.com/magazine/142toc.htm www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 For more need-to-know information about topics covered in Tom Cantrell’s Issue 240 article, the Circuit Cellar editorial staff highly recommends the following content: — Power Analysis Primer From Powerline Measurements to PFC by Robert Lacoste Circuit Cellar 229, 2009 Familiarize yourself with PFC. Robert explains how to measure the power consumption of linepowered devices. Topics: Powerline, PFC, Load, Power Measurement 73 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 July 2010 – Issue 240 Across 74 3. 8. 9. 11. 13. 16. 17. 18. 19. 20. 21. MIPS means millions of these per second Brightness QAM, FM, AM .MI A lux is what per square meter? Mega binary Java app for your server Valueless character 1 billion FLOP MIT, 186 Code parse Down 1. 2. 4. 5. 6. 7. 10. 12. 14. 15. 8-GB USB flash drive holding every issue if Circuit Cellar VM [two words] EQ Off the motherboard, but connected Tera binary Bps [two words] Ground pi Group larger than a sector IEEE 139 Unavailable, outdated The answers will be available in the next issue and at www.circuitcellar.com/crossword. CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com 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 PDQ Board with The PDQ Board Ethernet module a low cost 2.5x4 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 July 2010 – Issue 240 www.mosaic-industries.com www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar 75 Rowley CrossWorks C/C++ Compiler, IDE, Debugger, and JTAG programming tools in a single professional package Board and CPU support for NXP, STMicroelectronics, Atmel, TI, and many other microcontrollers Includes royalty-free tasking library July 2010 – Issue 240 Come and see what we have! 76 Mention Circuit Cellar when you buy and well gladly send you a JTAG adapterfor free! RowleyAssociates.com CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com XL- MaxSonar Ultrasonic Ranging is EZ XL-MaxSonar Products • High acoustic power • Low cost • Low power, 3V-5.5V, (< 4mA avg.) • 1 cm resolution • Serial, pulse width, & analog voltage outputs • Real-time auto calibration with noise rejection • No dead zone XL-MaxSonar-EZ • Choice of beam patterns • Tiny size (<1 cubic inch) • Light weight (<6 grams) XL-MaxSonar-WR (IP67) • Industrial packaging • Weather resistant • Standard ¾” fitting • Quality narrow beam July 2010 – Issue 240 www.maxbotix.com www.circuitcellar.com • CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar 77 ! " )! " % ) $ "* # $%$ Tools for Embedded Development CROSSWARE ® $& ' ($! " ( $ %! ® ARM 8051 COLDFIRE ® Three quality tool suites C/C++* G Code Wizards G Debugging G Simulation G Support G * Embedded C++ for ARM and ColdFire only Advanced software tools since 1984 www.crossware.com [email protected] July 2010 – Issue 240 CROSSWORD ANSWERS from Issue 239 78 Across 1. OBFUSCATE—Purposely obscure your code to protect it 4. UNPLUG—Disconnect, both literally and figuratively 5. POSITIVE—Cation charge 6. HEATSINK—Prevents overheating 10.FIELDPROGRAMMABLE—Can be tweaked post-manufacture [two words] 12.PORT—Point of I/O 13.RELAY—Closes and opens contacts 15.LEGACY—Old equipment 16.TESLA—Flowing water, Niagara Falls 19.SERVICEPACKAGE—A bundle of software updates [two words] 20.TESTMODESELECT—TMS pin [three words] Down 2. SANJOSE—Embedded Systems Conference, April 2010 [two words] 3. OXIDE—Flux removes 7. IMPURITY—Dopant 8. DUKE—Java’s character 9. TAPE—Plastic strip for data 11. EXTRINSIC—Semiconductor with impurities 14.ANEMOMETER—For wind velocity 17.ACIDIC—pH < 7 18.VOLT—Common EMF Unit 1 2 O B F U S A 4 U N J 5 P O S 6 H E 10 F 12 P O 16 T 19 S E R V 20 T 3 C A T E O X P L U G I D S I T I V E 7 A T S I N K M P U 11 I E L D P R O G R A M M X I 13 R T T R 15 R L E G A C Y I N E S L A 17 I A I C E P A C K A G E I E S T M O D E S E L E C I C CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • 8 D U 9 T K A B L E P 14 E L A Y N E M O 18 V M O E L T T E R www.circuitcellar.com Page The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue. Page Page Page 76 AAG Electronica, LLC 31 EMAC, Inc. 13, 32 JK microsystems, Inc. 51 PCB-Pool 31 AP Circuits 39 Electronica 2010 75, 78 JK microsystems, Inc. C4 Parallax, Inc. 75 All Electronics Corp. 77 76 52, 53 Elektor 23 Jameco 10 PoLabs Apex Embedded Systems 72 Elektor 30 Jeffrey Kerr, LLC 68 Pololu Corp. ATRIA Technologies, Inc. 65 Embedded Developer 11 Keil Software 76 Rowley Associates CC Gold 25 ExpressPCB 77 Lawicel AB 35 Saelig 33 CWAV 75 FlexiPanel Ltd. 13 Lemos International Co. Inc. 51 ScanTool.net, LLC 12 Cleverscope 32 Grid Connect, Inc. 77 MCC (Micro Computer Control) 21 Comfile Technology, Inc. 69 HAMEG 77 Maxbotix, Inc. 78 Crossware Products, Inc. 30 HobbyLab, LLC 77 Mental Automation 77 Tern, Inc. 76 Custom Computer Services, Inc. ICbank, Inc. 76 microEngineering Labs, Inc. 57 Total Phase, Inc. 75 Decade Engineering Imagineering, Inc. 75 Mosaic Industries, Inc. 76 Trace Systems, Inc. 77 DesignNotes 30 Intuitive Circuits LLC 19 Mouser Electronics 43 Triangle Research Int’l, Inc. C3 Digi International 75 Ironwood Electronics C2 NetBurner 73 V-Module 7 P 61, 63 1 REVIEW of August Issue 241 2, 3 Technologic Systems The 4-to-20-mA Current Loop Build an X10 Controller (Part 2): The Controller Program and Utility THE CONSUMMATE ENGINEER Embedded Safety THE DARKER SIDE A Tour of the Lab (Part 1): Time Domain Measurement Equipment ABOVE THE GROUND PLANE Crystal Properties: Circuit Models, Measurement, & Conversion FROM THE BENCH Application Communication with USB (Part 3): Assembly Code Finale SILICON UPDATE MIPS and More September Issue 242 Deadlines Space Close: July 14 Material Close: July 21 Advanced USB Design Debugging • SparkFun Electronics A TTENTION A DVERTISERS Theme: Embedded Development www.circuitcellar.com 5 Theme Data Acquisition Bonus Distribution PCB West; Embedded Systems Conference East Call Peter Wostrel now to reserve your space! 800.454.3741 or 978.281.7708 e-mail: [email protected] CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar July 2010 – Issue 240 I NDEX OF ADVERTISERS 79 PINTERRUPT RIORITY by Steve Ciarcia, Founder and Editorial Director July 2010 – Issue 240 I 80 72 Flavors and More don’t wish to be overly critical all the time—well, actually, I’m not losing any sleep over being a curmudgeon ;-)—but have you tried to figure out what the heck they are doing over at Intel these days? Certainly, the people in the marketing department who came up with their latest processor numbering system must be smoking something stronger than tobacco. I’m sure I’m not the first who thinks that selecting a new Intel chip is a very daunting process. I’ve been sitting on the fence for a long time when it comes to an operating system. I’ve been using XP Pro for years and saw no logical reason to “downgrade” performance to Vista when Microsoft tossed that lemon in the ring a few years ago. Instead, I continued upgrading hardware, even going so far as having a quad-core laptop, but still using XP Pro as my OS. Now, however, I think Windows 7 may be a reasonable next step even without Microsoft’s continued threats of XP abandonment. But, unlike the cars that I tend to purchase with no more than 10 minutes of procrastination, I find myself researching computer selection to the point that it might take months. It must be the difference between a purely emotional decision and overly intellectual analysis. The first consideration in buying a new computer these days is deciding whether to choose Core i3, i5, or i7 (and I heard there is an i9 in the pipe someplace). The logical assumption is that the higher the family number the more overall performance it has and that the numbers following the family designation indicate a capability increment in that family (such as a Core i5 670 benchmarking faster than an i5 650). The answer is: Well, sorta, but not necessarily. It turns out that many of the processors within the same family have different features and, in the end, what you get for performance depends a lot on what kind of software you are trying to run! What might have been three simple family designations is confusing the heck out of me since the numbering scheme incorporates three different design processes, dual, quad, and hex cores, hyper-threading or not, turbo-boost or not, on-die graphics or not, and various cache quantities and memory bandwidths. Figuring out all the players is a game in itself. The Core i3 5xx series dual-core (32-nm Clarkdale) processors are considered “basic level” but aren’t slouches. They incorporate on-die graphics and hyper-threading, and they’re considered equivalent in processing power to the then top-of-the-line quad-core Q6600 I bought a few years ago. The Core i5 6xx series dual core (32-nm Clarkdale) processors seem a bit faster. They have on-die graphics and hyperthreading, but they also include something called turbo-boost. This is a process that automatically runs the cores faster than the base operating frequency if the die operating power, current, and temperature are below specification limits. These processors appear equivalent to current midrange Core 2 quads and high-end Phenom II processors. From then on, it is straight downhill. You’d think that the Core i5 7xx series should be an incremental upgrade—but, no, it’s a different animal. The Core i5 7xx series is a quad-core (45-nm Lynnfield) processor with turbo-boost but no hyper-threading and no on-die graphics. Not enough features? Go to the 8xx series and you add turbo-boost and hyper-threading back in the mix. If you weren’t confused enough, there is the Core i7 8xx and 9xx series quad-core processors (45-nm Bloomfield). They have similar attributes as the other families with the addition of an unlocked multiplier that allows over-clocking for the power gamers in the crowd. To make the nomenclature even more confusing, the 9xx series isn’t even consistent within its own designation series. A Core i7 975 is a quad-core, but an i7 980X is six cores. Atta boy, Intel! CPU benchmarks, worshipped by fringe elements who think a liquid nitrogen tank next to the desktop is a necessary part of life, are limited. Nonetheless, they are still useful enough to give us some peace of mind in performance/dollar comparisons. For example, here are the Passmark CPU scores for some that I’ve mentioned: Core 2 Duo T5500 (911), Q6600 (2959), Core i3 540 (2851), Core i5 750 (4207), Core i7 950 (6288), Core i7 975 (7011), and Core i7 980X (9955). There can be a lot of architectural overlap, so be very careful of the hype in prepackaged computers. So, where does that leave me? Better informed, but not any closer to making my next computer acquisition. The last time I bought a new computer, I approached it the way I buy cars—get something fast and then negotiate driving it slower. The result was a 12-lb, quad-core laptop with a 300-W power supply! Certainly, I only think of it as a “transportable,” but perhaps the idea of stuffing 10 lb of processor in a 5-lb laptop has exceeded trendy effectiveness. After quoting benchmarks to you, I have to admit that they are meaningless for most of the stuff I do anyway. It sounds wonderful to simply toss in an i7 980X—but at $1,000 each, I’d have to be nuts. Buying a computer with any one of these new processors will instantly upgrade me to Windows 7, but that certainly isn’t going to result in a 3× or 5× speed boost over my present system, regardless of the benchmarks. I doubt it will do a lot for the same old non-threaded application software I’ve been running for years. I guess that means I have to think about the road ahead a bit longer. [email protected] CIRCUIT CELLAR® Personal Download for [email protected] I © Circuit Cellar • www.circuitcellar.com XBee ® 7KH0RVW)OH[LEOH=LJ%HH3ODWIRUP : ZigBee PRO interoperability : Out-of-the-box RF communications : Common XBee footprint makes substituting modules easy NEW! Programmable ZigBee modules : Optimized for ZigBee application profiles including Smart Energy : iDigi™ Energy solution bundle : Complete solution: Modules, adapters, gateways, services The industry’s first ZigBee Smart Energy modules 'LJLVMMLYZ[OLPUK\Z[Y`»ZTVZ[JVTWSL[LZL[VMOHYK^HYLHUKZLY]PJLZMVY`V\YAPN)LLLUHISLK ZVS\[PVU?)LLWYVK\J[ZZ\WWVY[H^PKLYHUNLVMHWWSPJH[PVUZPUJS\KPUN:THY[,ULYN`/VTLHUK )\PSKPUN(\[VTH[PVU9LTV[L+L]PJL4HUHNLTLU[HUKTVYL>P[OHOVZ[VMTVK\SLZZ[HUKHSVUL Gateways HKHW[LYZ07LUHISLKNH[L^H`ZHUKP+PNPKH[HZLY]PJLZ+PNPOHZ[OL[VVSZ[VZLL`V\YWYVQLJ[ [OYV\NOMYVTILNPUUPUN[VLUK Modules Get started today with an XBee Development Kit Digi International Tel. 1-877-912-3444 Adapters www.digi.com/getXBee Personal Download for [email protected] I © Circuit Cellar Personal Download for [email protected] I © Circuit Cellar