Cover.qxp 2/5/2008 12:17 PM Page 1

EMBEDDED CONTROL DESIGN CONTEST RESULTS P. 26 • MCU MATHEMATICS P. 60 • TACKLE A TOUGH DESIGN PROJECT P. 76 w w w . c i r c u i t c e l l a r . c o m CIRCUITTHE MAGAZINE FOR COMPUTER CELLAR APPLICATIONS #212 March 2008 ROBOTICS A Peripheral Chip for Robotics Apps Robot Software Safety with Ada95 In-Flight Communications Made Easy A DIY Motion-Sensing System -Powered Stargazing A Look at New-Age MCUs Build a Vertical Plotter

03>

7925274 75349 $4.95 U.S. ($5.95 Canada) C2.qxp 10/1/2007 10:27 AM Page 1 5

C 5 25 50 75 95M 5 25507595 Y 5 25 50 75 95 K 5 25 50 75 95 MY CY CM 1.qxp 10 $29.95 Buy Now / 1 / 2007 3:50PMPage1 All other trademarks are properties of their respective owners. ©2007 Corporation. All rights reserved. * oftheir respectiveowners.©2007 CypressSemiconductorCorporation. Allrightsreserved. All othertrademarks areproperties It’s showtime. embedded designsyoucanevaluaterightoutofthebox.Getyoursandstepintospotlighttoday. embedded applicationdevelopment.GetaCypressPSoC Fixed-function microcontrollershadtheirshareofthespotlight.It’s simplified—approachto timeforarevolutionary—and Get Your Kit. TickettotheUltimateEmbeddedDesignStarter your time-to-market.Thiskitincludestheeasy-to-usePSoCExpress andafastMCU—shorten programmableanalog anddigitalblocks,embeddedmemory mixed-signal arrays—powerful, * Cypress, theCypress logoandPSoCareregistered trademarks,andProgrammable System-on-Chip, PSoCExpress,andFirstTouch are

www.cypress.com/go/FirstTouch Buy yourPSoCFirstTouch Kitnowat: UltimateStarter CAPSENSE TOUCH SENSING TEMPERATURE SENSING

® LIGHT SENSING FirstTouch ™ visualembeddedsystemdesigntool,andgivesyou Does notinclude anyapplicablesalestax, shippingandhandlingcosts. CPFAP001E PROXIMITY CAPSENSE ™ SENSING Starter KitnowanddiscoverhowmuchPSoC Starter applications onasingleplatform. Includes fourready-to-usemixed-signal trademarksof CypressSemiconductorCorporation. 5 81.qxp 1/4/2008 3:04 PM Page 1

What’s the difference?

Price!

You’re correct, the one on the right costs less because should find a lower print-advertised price for it’s from Jameco! When you’re looking to purchase a product Jameco offers, just let them know and major name brand passives or semiconductors, be they’ll offer that product for 10% less than the other sure to check out Jameco first. They also offer company’s price, right down to Jameco’s cost! money-saving generic equivalents at about Wouldn’t it be worth your time to check out Jameco 20% less, so you’ll save even more! And if you today at www.Jameco.com? • Both Major Name Brands and Generic Products for Additional Savings • Over 99% of Catalog Products are in Stock for Immediate Delivery • Only Jameco Guarantees the Lowest Prices

Click or call today for a FREE Jameco Catalog Visit www.Jameco.com/CCX and start benefiting from Jameco’s Awesome Prices! Call 1-800-831-4242 3.qxp 1/30/2008 12:00 PM Page 1

ent Disp sc la e y r s o u l

F

m

u

u

c a

vfdV Graphic Display Value Approaching Character Display Prices A Display You Can Read From Any Angle

RoHS Compliant ISO 9001 Certified 9001 140001 TS16949

Noritake 7000 Series MORE BUILT-IN FEATURES THAN YOU MAY EVER NEED...

Up to 4 Independent Windows with Individual Control 8 Levels of Brightness Control Many Int’l Font Sets with 16 User-Defined Characters Built-in Screen Savers Easily Combine Text & Graphics on One Screen Many Filters Available to Match Application Horizontal & Vertical Scrolling Development Kit Available Proportional Fonts & Font Magnification

DON’T COMPROMISE. Your application deserves VFD quality ...

Noritake VFD Backlit LCD

www.noritake-elec.com/51m Noritake Co., Inc. 2635 Clearbrook Dr., Arlington Heights, IL 60005 phone 1-800-779-5846 e-mail [email protected] Over 100 Years in Business Task_Masthead_212.qxp 2/5/2008 12:35 PM Page 4

TASK MANAGER

Design, Program, & Prosper FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia MANAGING EDITOR MEDIA CONSULTANT C. J. Abate Dan Rodrigues This isn’t your average Robotics issue. When we began planning this edition of Circuit Cellar several months ago, we set out to put together WEST COAST EDITOR CUSTOMER SERVICE Tom Cantrell Debbie Lavoie an issue that would feature a diverse set of articles that would touch on CONTRIBUTING EDITORS CONTROLLER the topics of both hardware design and software development. We could Jeff Bachiochi Jeff Yanco have easily packed the issue with six or seven feature articles about Ingo Cyliax ART DIRECTOR projects like simple motor control applications and line-following robots, Robert Lacoste George Martin KC Prescott but what good would that have done for engineers who are hungry for Ed Nisley GRAPHIC DESIGNER information about designing and programming interesting real-world NEW PRODUCTS EDITOR Carey Penney applications? John Gorsky STAFF ENGINEER This month, we deliver articles about useful projects that you can PROJECT EDITORS John Gorsky easily design and program at your workbench. If you start now, you can Gary Bodley have one or two of them up and running by early April. Ken Davidson Want your next robotics project to run smoothly? First, check out why David Tweed Daniel Ramirez uses the Ada95 programming language for many of his ASSOCIATE EDITOR robotics applications (p. 14). Next, jump to page 52, where Monte Jesse Smolin Dalrymple describes a peripheral chip for low-level functions. He makes a strong case for using the Rabbit Semiconductor I/O (RIO) device in ADVERTISING robotics and motion-control projects. 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise I first introduced you to Miguel Sanchez’s innovative vertical plotting PUBLISHER system back in September 2007 (Issue 206). Remember the video posted Sean Donnelly Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] at www.youtube.com/watch?v=VmB14M78CWU? Not long after Miguel ADVERTISING REPRESENTATIVE showed me the video, we began planning an article about the design. Shannon Barraclough This month, you can learn how it was built and programmed (p. 30). You Direct: 860.872.3064, E-mail: [email protected] can build a similar plotter to work in private or industrial settings. ADVERTISING COORDINATOR On page 36, a team of designers from Camosun College describes Valerie Luster its recent contribution to a flight control system for an RC helicopter. In E-mail: [email protected] this article, the team explains how it designed a functional communica- tions system that can be tweaked to work efficiently in a variety of aircraft Cover photography by Chris Rakoczy—Rakoczy Photography systems. The team covers the hardware, software, and firmware. www.rakoczyphoto.com PRINTED IN THE UNITED STATES On page 43, Chris Coulston describes the exciting new motion con- trol design that he calls the “Do-It-Yourself Wii.” The system enables him CONTACTS SUBSCRIPTIONS to interact with graphics programs on a PC in the same way that gam- Information: www.circuitcellar.com/subscribe, E-mail: [email protected] ing enthusiasts use a Wii controller to play video games. In this series Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 of articles, Chris describes how he developed the hardware and soft- Address Changes/Problems: E-mail: [email protected] ware for the system. GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] In the issue’s last feature article, Kripasagar Venkat describes effi- 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] cient multiplication and division techniques for with no AUTHORIZED REPRINTS INFORMATION hardware multiplier (p. 60). Although the article is aptly titled “Efficient 860.875.2199, E-mail: [email protected] AUTHORS Micro Mathematics,” it could have been called “MCU Math Made Easy.” Authors’ e-mail addresses (when available) are included at the end of each article. Our columnists Jeff Bachiochi, George Martin, and Tom Cantrell

round off the issue with interesting articles about using ARM processor 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) power to monitor the heavens (p. 69), working with C language when subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- troubleshooting a real design problem (p. 76), and finding the right 32- scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders bit chips for next-generation applications (p. 80). and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call Finally, note that the winners of the Microchip 16-Bit Embedded 800.269.6301. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. Control 2007 Design Contest are listed on page 26. Congratulations to Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the all of the winners! consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-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 © 2008 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. [email protected] Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 55.qxp 12/31/2007 12:21 PM Page 1

Microcontroller 100

95 Development

75 Tools

25 ARM Solution 5 5

® 0 ARM Powered Microcontrollers – available from many silicon Cx51 0 vendors; offer high computing performance along with rich peripherals. TurnARM Microcontrollers into your solution for cost-sensitive Keil Cx51 is the de-facto industry standard for all classic and extended 8051 device variants. powerful applications– with Keil DevelopmentTools . C51Version 8.5 includes the latest devices such as XC800,ADE7169, and C8051F4xx - F6xx. More information: www.keil.com/c51 C/C++ Development Kit JTAG Debugger The RealView Microcontroller Development ULINK2® connects to Kit (MDK) is the complete software development the JTAG or 2-wire debug environment for ARM7/9 and Cortex-M1/M3. interface and supports MDK is easy to learn and use, yet powerful on-the-fly debugging and enough for the most demanding embedded ARM Flash programming. C166 application.The integrated Device Database® simplifies tool configuration and includes more Keil C166 is the complete software development environment for Infineon C166, XC166, XC2000 than 250 ARM Powered Microcontroller and ST Microelectronics ST10 with debug and variants for your embedded project. programming support via ULINK2. More information: www.keil.com/c166 RealView® Microcontroller Development Kit

RealView C/C++ Compiler

RTX RTOS Kernel Library A/D Converter I/O Ports Debug Run-Control ARM μVision Debug Timer/Counter Interrupt System Device Database & IDE Channel RealView MDK combines the best-in-class ARM C/C++ Compiler, the genuine Keil μVision μVision PWM Flash ROM Debugger & AnalysisTools IDE/Debugger/Simulator, and the royalty-free

Examples andTemplates RTX RTOS Kernel.

Complete Device Simulation UART CPU RAM More information: www.keil.com/arm

2 Real-Time I C/SPI Clock DMA

SD/MMC ® Ethernet USB CAN RealView Interface Real-Time Library

RTX RTOS Source Code RTOS and Middleware TCPnet Networking Suite 100 The RealViewReal-Time Library (RL-ARM) 95 Flash File System solves the real-time and communication challenges of your ARM project and expands 75 USB Device Interface MDK with essential components for

Examples andTemplates sophisticated communication and interface Keil MCB evaluation boards come with code CAN Interface peripherals. size limited tools and extensive example projects that help you get up and running 25 quickly with your own embedded application.

5 More information: www.keil.com/boards Learn more about RealViewMDK , RL-ARM , and ULINK2 . Download a free 0 evaluation version fromwww.keil.com/demo or call1-800-348-8051 . www.keil.com 212_TOC.qxp 2/5/2008 12:36 PM Page 6

March 2008: Robotics FEATURES

14 Robotics with Ada95 43 Do-It-Yourself Motion-Controlled Gaming (Part 1) Daniel Ramirez Get Started with a Simple Application Chris Coulston 26 CONTEST WINNERS Microchip 16-Bit Embedded Control 2007 Design Contest 52 Robotics Made Easy A Peripheral Chip for Low-Level Functions 30 Vertical Plotter System Monte Dalrymple Miguel Sanchez 60 Efficient Micro Mathematics 36 Flight Control Multiplication and Division Techniques for MCUs A Communications System for an RC Helicopter Kripasagar Venkat Michael Ghazi, Stefan Kaban, Scott Morken, Carl Philippsen, & Kyle Wong

Robot Programming The “DIY Wii” (p. 43) with Ada95 (p. 14)

Vertical Plotter Design (p. 30)

COLUMNS

69 FROM THE BENCH A Big Deal in a Tiny Package (p. 80) Navigating the Heavens Jeff Bachiochi 76 LESSONS FROM THE TRENCHES Do You Want to Do a Design? Linked Lists George Martin 80 SILICON UPDATE More Bits, Less Filling Tom Cantrell DEPARTMENTS

4 TASK MANAGER 93 CROSSWORD Design, Program, & Prosper C. J. Abate 94 INDEX OF ADVERTISERS April Preview 8 NEW PRODUCT NEWS edited by John Gorsky 96 PRIORITY INTERRUPT What Happened to Performance? 13 TEST YOUR EQ Steve Ciarcia

6 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 12/10/2007 12:18 PM Page 1 npn212.qxp 2/5/2008 12:37 PM Page 8

Edited by John Gorsky Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. ETHERNET CONTROLLER FOR HIGH-END SYSTEMS WIZnet has rolled out its newest chip, the W5300, which is twice as fast and offers more channels than the currently available W5100. Like its predecessor, the W5300 integrates an Ethernet MAC and PHY as well as a fully hardwired TCP/IP core into an easy-to-use chip. However, it also enables you to use an external third-party PHY rather than the internal one. The W5300 offers stable speeds up to 50 Mbps, which is enough to watch movies in real-time rather than on a buffered basis. It also supports eight independent socket channels, provides dynamic memory allocation according to channel throughput, and offers a 16- or 8-bit data bus. The W5300 has the capabilities to meet Triple Play Service (Broadband Access, VoIP, and digital broadcasting) needs. The estimated cost for the W5300 is $5.99 in 1,000-piece quantities.

WIZnet, Inc. www.wiznet.co.kr

EASY-TO-WORK-WITH UML SEQUENCE DIAGRAMS The Trace Modeler v1.0 is an easy-to-use and smart layout to any changes and guaranteeing attractive and UML sequence diagram editor that runs on any platform. It structurally correct diagrams. saves developers a tremendous amount of time by combin- The Trace Modeler is designed to optimize developer ing the immediate and automatic layout of UML sequence productivity. It can be used by any development team for diagrams with a simple drag-and-drop interface. The Trace brainstorming and prototyping the design of new comput- Modeler distinguishes itself by instantly adapting the diagram er systems or for the documentation of existing ones. At the heart of its technology lies an under- standing of the flow of control in sequence dia- grams. This domain knowledge is used not only to determine the proper diagram layout, but also to interpret user actions. This enables the user to quickly change a diagram with simple drag-and-drop gestures, while the Trace Modeler maintains its correctness and pleasing layout. As a result, ideas can be expressed almost instantly with the Trace Modeler. Diagrams are stored in a simple and readable text-based file format, ideal for versioning sys- tems and file comparison tools. This format makes it easy to generate sequence diagrams with other tools or from running code and visualize them with the Trace Modeler. Dia- grams can be exported to various popular graphics formats and the clipboard. It also offers a batch export feature that can be used from the command line for easy integration into any automated documentation process. The Trace Modeler is extremely portable: it works on all major platforms, requires no installation, and has very accommodating license terms. A single-user license costs $119 and significant academic and volume discounts are available.

Tracemodeler.com www.tracemodeler.com

8 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com npn212.qxp 2/5/2008 12:37 PM Page 9

NEW PRODUCT NEWS LINEAR BALL-SCREW STAGE The ATS165 is a rugged, value-driven linear stage that is slotless rotary motor installed. The stage can also be ideal for applications requiring debris protection, medium ordered without a motor so third-party DC brush, brush- travel, and mid-tier positioning performance. It is similar in less, or stepper motors can be used. design to the ATS115 series, providing additional load-carry- The stage is equipped with a ground 5-mm/rev ball ing capabilities with larger bearings and a wider cross-section. screw that provides 0.5-µm resolution and can be outfitted The hardcover design provides protection from debris, with English and metric bolt-hole pattern tabletops. A and the robust aluminum cover is hard-coated to provide a stage-mounted brake option is available to prevent you scratch-resistant surface. The side seals keep dirt and par- from back driving the screw when power is removed from ticulates off of the stage and protect the bearing surfaces the servomotor when the stage is in a vertical orientation. from contamination. The vertical orientation of the seals A fold-back kit is also available to easily deflects debris away from the stage. Competitive top- effectively reduce the overall stage seal designs can ingest debris in the seal, resulting in length for space-constrained appli- the eventual failure and replacement of the seal- cations. ing mechanism. The tabletop can be outfitted The cost of the ATS165 is with an optional brush assembly to dependent on the exact configura- remove any particles that collect tion ordered. You may contact on the hard cover. Aerotech for a quote. The ATS165 has a NEMA 23 motor flange-mounting interface Aerotech, Inc. and can be ordered with a standard brushless, www.aerotech.com

HIGH POWER PCB CONNECTOR NEW 8-BIT CONTROLLER SERIES The new High Power Connector and Contact series The new Rich series controllers (W79E217/W79E227/ enables high-current connections directly to the PCB. W79E225) use the Winbond 8051 core, which is capable of The High Power Connector is an ideal solution for appli- executing a single instruction in four clock cycles. The cations that require high-power connections to a PCB. cores are built-in, with 64 KB/64 KB/16 KB of flash memo- The High ry, and have highly integrated peripheral functionalities Power Connec- (e.g., 10-bit ADC, UART, I2C, SPI port interfaces, PWM, tor and Contact and internal reset). series devices Other key features are also integrated into the con- are available pre- trollers, including fast execution, high resistance to inter- assembled in ference, and industrial specifications. They are applicable one- or two-row to common embedded applications that require high per- configurations, formance and quality features. reducing assem- The series design provides a typical solution for applica- bly costs and tions that require small package sizes with sufficient I/O eliminating acci- and memory capacities. The series can be applied in a dental connector wide variety of general industrial controls, including data separation. Con- loggers, transmission systems, power controls, motor con- nectors and contacts are also available separately, allow- trols, AC controls, and treadmills. ing for the customization of connector configurations. The Rich series provides a full-featured hardware/soft- The connectors offer high durability and are rated for up ware development system such as the JTAG hardware to 1,500 cycles under no load and 250 hot plug cycles simulator, software development system, programmer, and under a 120-V load. support files. The complete system combination enables When used with the APP Powerpole 15/45 finger proof the designer to develop products in a short period of time connector housings, the High Power Connector and Con- and allows their rapid integration into the market. With tact series provides a reliable and safe wire to PCB connec- the Rich series, in-system program (ISP) functionality can tion. The connectors are RoHS-compliant, have a UL rating also be used to directly upgrade the system program of 45 A per circuit, and use contacts that are composed of online, fully realizing the flexi- copper alloy with tin plating. The connectors are available bility and expandability of in many colors and with multiple accessories that include the products. mounting wings, spacers, and board-mounting staples. Please contact Winbond The devices start at around $1.21 for 1 × 2 vertical connectors for the cost of this new in 1,000-piece quantities. series of controllers.

Anderson Power Products Winbond Electronics Corp. www.andersonpower.com www.winbond.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 9 npn212.qxp 2/5/2008 12:37 PM Page 10

NEW PRODUCT NEWS UNIVERSAL CAPSENSE CONTROLLER DEVELOPMENT KIT The Universal CapSense Controller Kit is designed for easy development and debug of any CapSense design. Its modular approach enables both custom and predefined designs to be completed quickly and easily. The development kit comes with predefined control circuitry and plug-in hard- ware, along with controller boards for the CY8C20x34 and CY8C21x34 PSoC devices. It also includes a breadboard module and a module for implementing up to five buttons and a slider with sample overlays. The kit works with both PSoC Designer and PSoC Express, and allows for monitoring and tuning of CapSense designs via an I2C-to-USB bridge that is included in the kit. Cypress Semiconductor is unique in offering real-time monitoring and tuning, which can significantly reduce development cycles. The kit supports both the CapSense Successive Approximation (CSA) and Sigma-Delta (CSD) capaci- tive sensing methods. CSA offers outstanding inter- ference immunity and low-power consumption, making it ideal for portable consumer applications. CSD delivers flawless operation in wet conditions and offers superb temperature response, ideal for white goods and other moisture-sensitive systems. The kit costs $158.

Cypress Semiconductor Corp. www.cypress.com

10 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com npn212.qxp 2/5/2008 12:37 PM Page 11

NEW PRODUCT NEWS CAPTIVE HYBRID LINEAR ACTUATOR The 28000 series (size 11) double-stack, captive hybrid linear actuator is the latest addition to a continuously growing line of hybrid motors. The compact frame size is only 1.1″ (28 mm) square. The various linear actuator options deliver unmatched capabilities, opening avenues for equipment designers who require performance and endurance in a compact package. Built for long life (several million cycles) and superior performance, the size 11 linear actuator fea- tures engineering thermoplastics in the rotor drive nut and a stainless steel Acme lead screw. With this patented design, quiet and maintenance-free operations are ensured. This captive hybrid linear actuator is available in a wide variety of resolu- tions ranging from 0.000125″ (.003175 mm) per step to 0.002″ (.0508 mm) per step and delivers thrusts of up to 30 lb (133 N) without compromising its long life. The captive linear actuator is designed with a patented integral anti-rotation mechanism and is especially well-suited for applications in which external anti- rotation methods would be difficult or impossible to employ. Captive linear travel ranges from 0.5″ (12.7 mm) to 2.5″ (63.5 mm). Applications requiring pre- cise positioning and rapid motion are best suited for this motor. Typical applications include medical equip- ment, semiconductor handling, valve control, X-Y tables, handheld instru- ments, telecommunications, and many more. Priced aggressively, this product is ideal for incorporation into your next project.

Haydon Switch & Instrument, Inc. www.hsi-inc.com

ACCURATELY MEASURE TEMPERATURE OVER AN IP NETWORK The new Q series, Temperature Module is a distributed data acquisition module that can monitor up to four digital temperature sensors. The Temperature Mod- ule provides an accurate way to measure temperature over an IP network. It can also be used for environmental temperature monitoring and simple control. The module features two internal relays that can be used to control alarm signals, heaters, or coolers. Like all of the ControlByWeb products, the Temperature Module has a built-in web server so temperatures can be viewed and relays can be controlled using a web brows- er. The module can also be monitored and controlled using simple XML-formatted text and Modbus/TCP. The unit can be configured to trigger relays when a set temperature is reached, and it can even control relays in other Con- trolByWeb products located somewhere else on the network! Configuration of the Tem- perature Module is easy because it can be fully configured in minutes using a web browser. No configuration software is required. Standard models of the Temperature Mod- ule start at $107.16 in 100-piece quantities.

Xytronix Research & Design, Inc. www.controlbyweb.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 11 npn212.qxp 2/5/2008 12:37 PM Page 12

NEW PRODUCT NEWS NEW RABBITCORE FEATURES MEGABYTE CODE SUPPORT The RCM4300 series enables a new generation of applications that use more memory for data and code. The onboard mass storage provides even more performance and easier design than any other alternative in its price range. Software design is supported by a new release of the Dynamic C tools. Dynamic C version 10.21 includes the new Megabyte Code Support (MCS), enabling designers to use over 1 MB of SRAM for shared code and data. Pin-compatible with the complete family of Rabbit 4000-based core modules, the RCM4300 supports twice as much code space compared to any other Rab- bit core module, enabling complex embedded applications such as data encryption and security-enabled web servers. The RCM4300 series also provides the capability to implement up to 1 GB of storage using an industry-standard miniSD memory card. To ease design effort and reduce development time, the RCM4300 development kit is available. The development kit has all of the essentials needed to design a -based with mass storage. The kit includes an RCM4300 with a 512-MB miniSD card, a prototyping board, accessories, and development tools to get design engineers up and running quickly. Along with the industry-proven Dynamic C integrated development software—incor- porating an editor, compiler, and in-circuit debugger— there is also the FAT file system familiar to many pro- grammers, RabbitWeb for creating HTML web pages, and Rabbit’s Secure Socket Layer utility. The RCM4300 costs $80 for 1,000 units. The RCM4310 costs $69 for 1,000 units. The RCM4300 development kit is $299.

Rabbit Semiconductor, Inc. www.rabbit.com

HIGH-OUTPUT VOLTAGE DC/DC CONTROLLER The LT3742 is a 100% duty cycle dual-output, step-down short-circuit conditions. In addition, the LT3742 has switching regulator DC/DC controller that produces out- adjustable soft-start to control the output voltage ramp put voltages of up to 30 V for applications including step- time and a good power signal for each output. per motors, industrial controls, automotive, distributed The LT3742 is offered in a 4 mm × 4 mm QFN-24 pack- power, and telecom systems. The LT3742 can also be con- age. One-thousand-piece quantities begin at $2.30 each. figured with one side as a step-down voltage regulator and the other as a Super Capacitor charger (current source) for Linear Technology Corp. capacitor values of up to several farads. This is a useful fea- www.linear.com ture in robotic applications when longer hold-up times are needed or where high peak currents are required. The LT3742’s 100% duty cycle enables the output voltage to be very close to the input volt- age, ideal for battery-powered systems. The 4- to 30-V input voltage range enables operation from a number of intermediate bus voltages. A sim- ple step-up DC/DC converter is incorporated to generate its own gate drive voltage and also eliminates the extra parts required to drive the high-side MOSFETs. The onboard gate driver powers a single external N-Channel MOSFET for each output, enabling output currents up to 5 A. A constant 500-kHz operating frequency with current mode control provides fast tran- sient response and easy compensation. Output current sensing is precisely measured by moni- toring the voltage drop across a sense resistor and protects the converter during overload and

12 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com eq-212.qxp 2/5/2008 1:11 PM Page 13

Test Your EQ CIRCUIT CELLAR Edited by David Tweed

Problem 1—The master clock on a GPS satellite Problem 2—What is the relationship, if any, is set to 10,229,999.99545 Hz. Why such an between the GPS master clock and the GPS “odd” value? microwave carrier frequencies L1 and L2? Why are two different frequencies used?

Problem 3—Both and VHDL support Problem 4—For the data structure commonly the concept of compile-time adjustments to known as a “hash” (“associative array” in the design of a particular module, in addition some scripting languages), what is the differ- to the real-time signals that pass into and out ence in overall performance (in order-of-magni- of it. What is the specific syntax in each case? tude terms) between storing items into the array and reading them out again?

Contributed by David Tweed

What’s your EQ?—The answers are posted at www.circuitcellar.com/eq/ You may contact the quizmasters at [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 13 2803020_ramirez.qxp 2/5/2008 1:13 PM Page 14

FEATURE ARTICLE by Daniel Ramirez Robotics with Ada95

Ada95 is a standardized object-oriented programming language that was developed in the late 1970s by the U.S. Department of Defense. Today, engineers like Daniel use the highly structured language to increase the safety and reliability of their new robotics applications.

What do robots in space, the Inter- if you already know similar program- tasking, and other structural and safety national Space Station, the Canadian ming languages such as Java, Pascal, features. They include: Ada95 packages, robot arm, the European Arienne rocket, Visual Basic, and Visual C++. There are generic functions that are similar to C++ the Boeing 767, the Eurobus jet, and the also many references and textbooks on templates, types, tagged types and pro- French Grand Vitesse bullet train have in Ada95. I highly recommend J. G. P. tected records that are similar to C++ common? The answer is Ada95, a com- Barnes’s Programming in Ada: Plus an classes, ranges, schedulers, tasks that are puter language used to develop life- Overview of Ada 9X and “Ada 2005 similar to C++ and Java threads, and critical embedded applications. Ada was Rationale” by Intermetrics. Like C++ Ada exceptions that are similar to the developed during the late 1970s and and Java, Ada95 supports object-oriented C++ try, catch, and throw keywords. early 1980s by the U.S. government for programming (OOP) and procedural pro- Real-time multitasking, multipro- defense applications in an effort to reduce gramming (if you don’t want to get into cessing, and parallel processing are areas the high life-cycle cost of large software OOP). that Ada95 handles well. They are also applications. It was also intended to What makes the Windows GNAT the reason it is used for the development replace older languages, such as COBOL, Ada95 good for the embedded systems of life-critical software. The Ada95 task FORTRAN, and PL/1, which were used developer are the tightly typed variables, instruction with its related delay, select, by various government agencies. Ada was developed to fill the need for highly reliable fault-tolerant soft- ware. We engineers and robot design- ers should also be concerned with our robotic inventions that use embedded software. Why? Because they are grow- ing in size and weight and could possi- bly cause harm or injury to innocent bystanders. The Robot Wars and Tet- sujin exoskeleton competitions, where teams design robotic exoskeletons capable of lifting heavy weights, are dangerous events. Just imagine an out- of-control, fire-breathing autonomous battle ’bot. Sounds like a Stephen King movie, doesn’t it? Now you can take advantage of the highly structured Ada95 language for your own purposes because it is freely available on the Internet via GNU/GNAT user-sup- ported sites. An LRM, a complete user manual, and other reference manuals are available at www.adahome.com/ Resources/Compilers/GNAT.html. It is Photo 1—The GNAT IDE is easy to learn and use. It provides menus for editing, compiling, linking, and running easy to get started with Ada95, especially your Ada applications.

14 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803020_ramirez.qxp 2/5/2008 1:13 PM Page 15

Listing 1—Here is an example of communication between your Ada95 application and a remote robot at 115,200 bps, 8 data bits, and 1 stop bit. I used the serial port to access wireless telemetry (joystick positions) from a wireless sensor controller using the XBee-PRO wireless UART.

--******************************************************************* --* Initialize_Joystick - Initialize XBEE Pro boards running the --* Joystick firmware that are connected to the PC or laptop --******************************************************************* procedure Initialize_Joystick (Com_Port : IN OUT Com_Ports.Handle_Type; Name : IN STRING; Baud_Rate: Interfaces.C.Unsigned_Long ) IS Joystick_ID : integer := 1; begin -- Initialize_Joystick

-- Open the serial ports for SARD/EVB wireless UART at 115200, N, 8, 1... Com_Ports.Open (Com_Port, Name, Baud_Rate, 'N', 8, 1);

exception when E : others => ADA.TEXT_IO.Put_Line(Ada.Exceptions.Exception_Name (E) & "---" & Ada.Exceptions.Exception_Message(E)); ada.text_io.Put_Line ("Initialize_Joystick: exception 'others' ");

end Initialize_Joystick;

and accept statements and its own deter- build more robust, safer, and fault-tolerant Unix and Linux users don’t need to be ministic scheduler make it ideal for hard robotic applications with my examples as left out from embedded robotics devel- real-time systems that require synchro- a starting point using AdaCore GNAT opment because of a lack of Windows- nization. In particular, the protected Ada95. The Ada features combined with specific software tools. record structure enables two or more embedded microcontrollers that support tasks to communicate via shared global the serial communication interface WHY USE Ada95 FOR ROBOTICS? data (critical region) without having it (SCI), the USB interface, and the Ether- Designing a robust, fault-tolerant corrupted by either task and without the net TCP/IP interface (MAC) will help robot requires detailed up-front design need for semaphores. you harness your PC or laptop’s giga- work, including modeling, simulation, Ada95 packages and tagged types hertz power for your robot applications. integration, and testing. This is true of encapsulate both data and functions in For designers like me who use Unix, NASA’s robots, including the robot arm a similar manner to C++ classes. Pack- Linux, and LynxOS, there are real- and interplanetary spacecraft, such as ages also control the visibility of time bindings to POSIX and commer- Viking, Explorer, Galileo, and more, objects so some implementation cial bindings to WindRiver’s VxWorks which bring us fantastic photos. The Mars details can be hidden from other pack- that can also use GNAT Ada95 for exploration rovers, Spirit and Opportuni- ages for information hiding. Unix to develop similar applications. ty, provided scientists with evidence Another wonderful feature of Ada95 is bindings. A binding is an interface to another language such as C or assembly using the Ada “pragma interface to C.” XBee-PRO Microchip 30-MIPS Wireless UART dsPIC30F6014 This is great because it gives your sensor controller board SCI Pots Ada95 applications access to most of UART 1 UART 1 16-bit 1 115,200 bps timers 2.4 GHz the hardware on a PC or laptop. The UART 2 2 serial bindings give you access to the Host RF 16 channels Electronics Digital I/O 12-bit ADC 3 1 serial port. Bindings to the Ethernet are D/O provided via the Winsock bindings that 2 I2C enable you to develop client and server 3 115,200 bps Switches applications. In addition, you can Host access the mouse via the mouse bind- ings and a joystick via the joystick Microchip 24LC512 bindings for those telepresense and tele- serial EEPROM Freescale Z-axis Freescale XY-axis robotic applications that you are work- accelerometer accelerometer ing on. All of the Win32 bindings and PING Sonar Flexible the DirectX graphics bindings necessary sensors resistors for real-time displays and Windows panels are also available. Figure 1—This diagram of the wireless sensor controller shows the main components and interfaces used for the The language features will help you Vex Power Glove.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 15 2803020_ramirez.qxp 2/5/2008 1:13 PM Page 16

the need for semaphores and Ada95 tagged types to provide object-oriented functionality similar to C++ and Java. Now you can map Ada tasks and pack- ages to robotic hardware, so adding new hardware and software drivers does not require a complete redesign of your cur- rent system. In addition, you also get most of the C/C++ features, including inheritance, function overloading, classes, C++ templates, and tasks. The key to using Ada95 as a new robot language is to take advantage of its abili- ty to use Win32 libraries via Ada95 bind- ings and to use its interface to other lan- guages (including C and C++) via the pragma interface function. Now hard- ware drivers written in C or assembly can be called from Ada95 applications and give them the ability to transmit and Photo 2—This shows the complete Vex Power Glove system, including the dsPIC30F6014- based wireless sensor controller and the glove with three flexible resistors and Freescale X, Y, and Z accelerome- receive data via the serial port (COM3 or ters (virtual SARD). COM4), via Ethernet TCP/IP, or via the USB interface (USB-HID) bindings. You of water on Mars. In fact, the Internation- Ada’s deterministic scheduler makes need these capabilities so you can use al Space Station’s robot arm software was it easy to schedule tasks and assign your laptop’s serial, USB, or Ethernet written in Ada. The electronic equivalent them priorities. Passing data between ports to communicate with your of an Ada package is the IC. Each IC has tasks is as easy as a procedure or func- embedded robot applications. specific inputs, outputs, and more. tion call. Simply use accept and select Features that make Ada95 ideal for constructs with Ada tasks. Using Ada GNAT Ada95 TOOLS robotics include object-oriented method- tasks can make it easier for you to The GNAT IDE is easy to learn and ology, Ada95 packages, type checking, integrate and test the software drivers use (see Photo 1). It provides menus range checking, representation clauses, because it maps well with hardware. for editing, compiling, linking, and generic functions, protected records, Ada95 protected records provide an running your Ada95 applications. Out- tasking, deterministic scheduling, and easy way for tasks to share data without put is sent to the Ada output window, exception handling. Although Java and C++ have similar features, Ada95 enforces type checking, constraint check- ing, and exceptions. It also has tasking built into the language so it doesn’t have to make external system calls or POSIX function calls to schedule threads (similar to tasks). Ada tasks make developing robotic applications—such as collecting sen- sor data, checking for objects (obstacle detection), and generating motor com- mands—easier than using a finite state machine (FSM) or a linear control loop. For example, a sensor collection task and motor control task may run in parallel, with a sensor collection task reading the latest motor positions (encoder counts), while the motor con- trol task sends new PWM motor com- mands to the motors. Your navigation task determines the next move. Using serial (linear) programming would Photo 3—My Vex Power Glove uses a wireless sensor controller connected to a ZigBee XBee-PRO wireless require a finite state machine (FSM). UART that is used to transmit the telemetry to a laptop running an Ada95 data collection application.

16 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 17.qxp 2/11/2008 12:07 PM Page 1 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 18

which is handy for testing applications Vex Robotics Power Glove design, which Five push button switches provide inside the IDE. The GNAT gdb (com- is shown in Photos 2 and 3. five digital inputs to the sensor con- mand) or gvd (visual) debugger is also The heart of the Vex Power Glove troller. A newer and equivalent conveniently accessible from the IDE. is a 16-bit Microchip Technology dsPIC33F device could be used in One nice thing about the GNAT dsPIC30F6014 sensor controller (see place of the dsPIC30F6014 that is even Ada95 tool suite is that it is absolutely Photo 2). The controller provides sen- faster (40 MIPS) and provides hardware free! Commercial versions of Ada can sor data to any laptop using the XBee- CRC that could be used to process the cost thousands of dollars. If you already PRO wireless UART. It can be used to wireless messages (telemetry), but I have the GNU shareware tools such as read sensors (voltage, temperature, have not tried it for this application. GNU C/C++ and the gdb debugger, then pressure, and humidity), potentiome- you will find the GNAT Ada95 tool suite ters, flexible resistors, and XYZ THE GLOVE IN ACTION a welcome edition. accelerometers using a sensor task. It The Vex Power Glove features of a also displays them in real time on the Microchip dsPIC30F6014-based wire- DEBUGGING Ada95 APPLICATIONS laptop’s display using a display task. less sensor controller that’s used to Ada95 provides extensive I/O support Errors are handled with Ada95 excep- digitize the finger positions (flexible using the Ada.Text_IO package (similar tion handlers. The Ada95 application resistors) and the glove’s orientation. in functionality to C’s stdio library). runs under Windows XP. The XBee-PRO wireless UART and With the package, you can add trace I use the Vex Power Glove as a wire- receiver Ada95 application are used to statements and print data values. less motion input device to teleoper- receive glove commands to control a The Ada95 IDE also provides support ate some of my Vex-based robots, such prop, which can be either a laptop or for using either the GNU gdb debugger as the Gilbert III Explorer Robot an animation prop. It uses the XBee- or the visual version VDI that is invoked shown in Photo 4. I took the photo PRO receiver and a Freescale Semicon- from the GNAT Ada95 IDE. With it, you just after a snowstorm last year. The ductor MMA1260D Z-axis accelerom- can examine code, single step, step into, glove transmits finger position and eter to digitize the glove’s current ori- watch variables, and set breakpoints. orientation information so it can be entation with three of the dsPIC’s processed remotely on a laptop using ADC pins. The glove’s orientation is Ada95 CODING STYLE an Ada95 control application. The then transmitted back to the laptop If you look at C/C++ code and the cor- application generates motion com- (see Figure 1). responding Ada95 code, you may notice mands and sends them to the Gilbert The dsPIC firmware digitizes the that Ada95 is more readable. This is due III Explorer Robot. glove’s finger positions by reading the to the extra effort the language designers Although I designed the took to make Ada95 easy to maintain. It glove for carrying out my own is self-documenting and bears some tele-presence and tele-robotics resemblance to Pascal. If you remember experiments, it can also be used the Pascal language, you will see some for a total virtual reality experi- similarities in the keywords. ence, such as a control for a Listing 1 shows an example of how to PC or laptop-based game that communicate between an Ada95 applica- supports standard IBMPC Vex tion and a remote robot at 115,200 bps, power gloves. It is based on 8 data bits, and 1 stop bit. The SCI the original Mattel Power interface on the robot’s microcontroller Glove, a controller accessory is usually labeled UART0, UART1, for the Nintendo Entertain- SCI0, or SCI1. The exception handler in ment System that was sold Listing 1 provides error handling for any during the early 1990s. runtime exceptions that occur in the routine while using the serial port. WIRELESS MESSAGES The Ada95 Vex Power WIRELESS SENSOR CONTROLLER Glove application provides I used my wireless sensor controller robust wireless message pro- board as a testbed for demonstrating cessing with CRC/Check- some of Ada95’s features, including range sum. The reader can even use checking, tasking, and exception han- the glove’s flexible resistors dling using a laptop. As you can see in to generate simulated sensor Figure 1, the controller features a Digi readings that are out of their International MaxStream XBee-PRO specified ranges and watch Photo 4—This is my Vex-based Gilbert III robot. I am upgrading the wireless UART. The UART transmits how the GNAT Ada95 appli- design so I can use the Vex Power Glove as the motion input the telemetry to a laptop running an cation handles the erroneous device. Doing so will enable me to collect data remotely by running Ada95 data collection application for my sensor readings. an Ada95 data collection application on my laptop.

18 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 29.qxp 1/25/2008 4:39 PM Page 1

Fully Loaded, Small Form Factor MCUs Silicon Laboratories’ mixed-signal MCUs combine a high-speed 8051 32 kB

CPU, and best-in-class analog peripherals in ultra-small 16 kB

packages allowing designers to reduce component count while improving Flash 8 kB system performance. These highly-integrated, feature-rich devices are

optimized for space-constrained, low-power, cost-sensitive applications. 9 mm22216 mm 25 mm Size Low-Cost, Professional Tools Complete development kits (including in- Highest Functional Density system debug and integrated development • 8–24 Bit ADC environment) make development quick and • 2–32 kB Flash Memory easy. Low-cost evaluation kits and reference • 25–100 MIPS 8051 CPU designs simplify evaluation and accelerate time-to-market.

Product details: www.silabs.com/SmallMCU

MCUs TIMING POWER BROADCAST WIRELINE WIRELESS www.silabs.com 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 20

voltages across five flexible resistors because it already uses a 5-V supply. connected to the wireless sensor con- whose resistances vary with the angle The ADC channels used for the troller. Another XBee-PRO receiver is percent each finger is bent or flexed. accelerometers are AN12/RB12, connected to a Parallax serial servo Finger movements are digitized using AN13/RB13, and AN15/RB15. controller (PSC) mounted on my Hero the dsPIC’s 12-bit ADC, and the The calibration data is saved to non- 2007 Robot, which uses four Vex firmware processes and filters them. volatile memory using Microchip motors (4-WD) for the motion subsys- The glove’s current orientation rela- Technology 24LC512 serial EEPROM. tem (see Photo 5). I used a similar tive to the gravity vector is read from It can be retrieved later when it’s configuration to control the four Vex the attached Freescale Semiconductor needed for scaling sensor readings and motors used on the motion subsystem MMA6260Q X/Y-axis accelerometer and generating motor commands. A com- of my telepod robot (see Photo 6). I the MMA1260D Z-axis accelerometer, plete schematic diagram of the wire- plan to use Ada95 to process the which are also digitized by the 12-bit less sensor controller is posted on the telemetry received from each of the ADC to obtain the orientation angles. Circuit Cellar FTP site. telepod’s sensors using an Ada95 data The 12-bit ADC is also used to read the collection application. I will remotely pressure sensor attached to the index fin- XBee-PRO WIRELESS UART control the telepod by issuing wireless ger. The 12-bit reading from the ADC for The 2.4-GHz XBee-PRO Zig- motor command messages to it. any of the sensors is a value between 0 Bee/802.15.4 RS-232 RF modem (OEM The advantage of purchasing the kit and 4,095, which can be scaled to PWM RF module) provides all the benefits of is that the serial connectors and RS- motor commands needed for animation. the ZigBee standard in a design that 232 voltage level translations along yields three times the range of tradi- with the power supply and cables are XYZ ACCELEROMETERS tional ZigBee solutions. All of this supplied, including one board that The MMA6260Q X/Y-axis and hardware is provided in a board that directly connects to the USB port on MMA1260D Z-axis accelerometers— measures only 24.38 mm × 27.61 mm, the laptop. I chose to purchase the kit which are used to obtain the glove’s which helps it fit into the enclosure instead of making the boards for the relative orientation—enable you to without taking up too much space. wireless sensor controller (see Figure 1). move associated motors or servos by The XBee-PRO wireless UART pro- turning your wrist and adding three vides telemetry to a nearby client CONTROLLER RANGE degrees of freedom (pitch, yaw, and device (e.g., a laptop, a robot, or The 100-mW XBee-PRO provides a roll) that can be mapped to servo or another animatronic device). It is con- range of up to 1 mile (1.6 km), and its motor commands. The accelerometers figured with the wireless UART appli- RS-232 connectivity makes integration are read with the 12-bit ADC. With cation using standard Hayes modem simple. The range of this controller this technology, you can use the Vex AT commands with the serial port exceeds that of a standard Vex con- Power Glove for video games, input protocol set at 115,200 bps, 8 data troller because the line-of-sight range and telerobotics, and virtual reality bits, 1 stop bit, and no parity. It is is the same as the one specified in the experiments similar to those carried connected to the dsPIC30F6014’s ZigBee protocol. The MaxStream out in research labs. UART. XBee-PRO provides the maximum An XYZ accelerometer provides the The transmitter located on each range of 300′ line of sight indoors. glove orientation (tilt) by measuring robot is an XBee-PRO wireless UART The actual range that the reader the XYZ angles relative to gets depends on many fac- the Earth’s gravity vector tors, including direct line (to ±1.5 G), which points to of sight, the antenna the center of the Earth. length, and the walls and Although the dsPIC can windows that can block run with a 3.3-V power the low-power ZigBee sig- supply, I also included a nal. The standard antenna Microchip Technology is built into the board, but MCP6S26 six-channel pro- Digi sells other options. grammable gain amplifier Additional XBee-PRO mod- (PGA) for signal condition- ules can provide greater ing in the design. The range and animation con- MCP6S26 scales the 3.3-V trol options. X/Y accelerometer readings The Digi wireless UART, to the 5 V required for the which can be easily config- dsPIC’s ADC because ured using standard AT everything else is 5-V based modem commands, and the voltage reference includes a utility to con- Photo 5—Another XBee-PRO receiver is connected to the Parallax serial servo con- for the ADC is 5 V. The Z troller (PSC) mounted on my Hero 2007 robot, which uses four Vex motors (4-WD) for figure the modem channel accelerometer is fine its motion subsystem. and data rate, as required

20 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 21

by the application. SRAM parity errors, bus errors, and voltage spikes). Antivirus USB 2.0 INTERFACE software from Norton and A Microchip Technology MacAfee act in a similar man- PIC18F4550 USB 2.0 controller ner to medicines and vaccines provides a convenient method used to treat and cure diseases. to directly connect embedded Even Unix, Linux, embedded controllers to Ada95-based Windows CE, and the Mac applications running on a laptop operating system are suscepti- or PC by using the USB inter- ble to these problems, although face with USB 2.0. This is not to the same extent because accomplished by taking advan- hackers do not target them as tage of a virtual COM port often. But for Windows, this is (VCP), as described in a major problem. Windows is Microchip’s USB application an excellent system for current- notes. It communicates with generation laptops and PCs the dsPIC30F6014 Vex Power (over 1 billion copies used Glove controller via the 8-bit worldwide), in part because of SPI bus. You can also purchase the conveniences it affords, a complete USB 2.0 develop- including Word, Excel, Power- ment kit, a PIC18F4550 USB Point, Microsoft Schedule, 2.0 controller (PICDEM full- Visual Basic, Visual C++, and speed USB demonstration board many other excellent tools that DM163025) that includes a have been continuously board and all the necessary improved over the years follow- firmware. I used this board for ing Bill Gates’s vision. some of my other USB applica- While all of this sounds tions, including a USB high-per- scary, the free version of GNAT formance DC motor controller. Ada95 runs on Windows, Unix, The Vex Power Glove can and Linux. (A commercial ver- also be directly connected to a sion sold by Aonix runs under PC or laptop as a motion-input LynxOS.) It is a good platform device. Of course, this requires for non-life-critical applica- the glove to be tethered to a PC Photo 6—I plan to use Ada95 to process telemetry received from each of tions, but don’t try to develop a or laptop with a USB cable. the telepod’s sensors. I will incorporate an Ada95 data collection application. yacht navigation system with This will enable me to remotely control the telepod by issuing wireless motor Doing so provides a convenient command messages. it. Instead, purchase the com- way to calibrate, evaluate, and mercial versions of Ada95 for test the glove with resources that purpose. Versions of such as MATLAB and Excel for visual- recent WIZnet article (“iEthernet GNAT Ada95 are also available for izing the data and analyzing it. You Bootcamp: Get Started with the LynxOS, Linux, Unix, Red Hat Unix, can use GNAT Ada95, Microsoft Visu- W5100,” Circuit Cellar 208, 2007). and other operating systems. al Basic, or Microsoft Visual C++ for The solution for developing life-critical laptop-based glove applications. THE KERNEL embedded software is to use an embed- The Windows runtime kernel ded real-time runtime operating system ETHERNET evolved from a cooperative multitask- (e.g., IBM Rational, LynxOS, Wind River Ada95 bindings are available for ing operating system to the sophisti- VxWorks, and Aonix) or use a software accessing the Internet and web-based cated preemptive multitasking and development language that includes a appliances using TCP/IP and sockets. multiprocessing operating system that runtime as part of the language (e.g., I am in the process of building new it is today. Windows is quite an amaz- Rational APEX Ada95). Today’s option Ethernet applications using the new ing system that can automatically is to use Ada95 with one of the POSIX- WIZnet W5100 TCP/IP stack for com- schedule daily, weekly, and monthly compliant runtimes mentioned above. munication and a Linksys wireless tasks such as maintenance, disk The runtime is tailored to the language router for getting wireless telemetry defragmentation, space compression, and hardware platform (e.g., Pen- using the Ada95 TCP/IP bindings to and more. Like the human body, Win- tium, PowerPC, MIPS, SPARK, ARM, receive telemetry on a laptop. I am dows can also repair itself from dam- or any popular computer architecture). also developing new Ada95 applica- age caused by hard disk bad sectors, A problem that could arise with a Java tions using the bindings and the infor- viruses, worms, and other electronic or C++ medical application is if the mation provided by Fred Eady in his maladies (e.g., controller failures, Windows kernel decides that it is time

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 21 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 22

to schedule a high-priority internal operating systems will also work for POSIX-compliant Ada95 runtimes that Windows task. In order to do so, it has other languages such as C++ and Java. work with the Ada95 rendezvous and to preempt the user’s application, Real-time operating systems and run- tasking models to provide robust fault- which could be a life-critical applica- time kernels have been around for tolerant performance over a wide variety tion used to read a patient’s heart rate many years and have been continu- of life-critical embedded applications. or EKG during a critical operation. ously improved and optimized to the New applications are being devel- That would make the application miss highest commercial standards for use oped for parallel processors and super- a scheduled system call inside a real- in embedded enterprise, military, computers used by astronomers and time task or thread while reading the space, and medical applications using physicists as a replacement for the transducers. The scenario is less likely a set of standard POSIX-compliant venerable FORTRAN language that to occur with a dedicated real-time system calls. Commercial variants of has served the scientific community operating system such as Rational Ada95 from IBM Rational, Aonix, and since the mid-1950s. Ada95 maps well APEX, LynxOS, and VxWorks. The Green Hills have been tailored to to these applications, including com- mon statements, global memory, and parallelizing expressions. Ada95 shares many of the features found in other languages including C++ and Java: data abstraction, type checking, range checking, records (C++ structs), object-oriented program- ming, tagged types (C++ classes), inheritance, generics (C++ templates), multithreading, tasks (multithreading and multitasking), interrupt handling, error handling, exception statements (catch, throw, and try), and raise statements. Although the free version of GNAT Ada95 is not POSIX-compli- ant and does not have all the opti- mizations that the commercial vari- ants provide, it may be used for non- life-critical applications and for learn- ing the safety features of the language.

Ada95 VS. OTHER LANGUAGES C and other languages allow great flex- ibility when assigning variables of any type, including automatic promotion of types (i.e., the char type can be assigned to an int type variable with no errors issued from the C compiler). But doing these kinds of operations can lead to run- time errors and system crashes usually caused by unhandled exceptions such as divisions by zero, overflow, underflow, and the square root of negative numbers. In addition, C pointers are even more troublesome when they point to invalid addresses that can cause data to be overwritten (boundary problems). Other features of Ada that make it an excellent candidate for a robotics lan- guage are the multitasking and multipro- cessing support that is directly built into it using tasks, a rendezvous mechanism, interrupts, priorities, protected records, and a deterministic scheduler. Ada tasks provide a mechanism for the parallel exe-

22 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 23

cution of applications that map well to can either process it or propagate it to features, although they are not as conven- robotics hardware (e.g., being able to read the calling routine. It will also display ient to code because variable attributes and process sensors while simultaneous- the actual error message and line may not be available in some of these lan- ly having a servo task update servo posi- number where it occurred. guages. Refer to Listing 2 for examples tions). This programming feat can be By thoughtfully specifying the mini- of Ada95 types, subtypes, and ranges. accomplished in Ada while not having to mum, maximum, and nominal values for As a BASIC and C programmer, I love resort to semaphores or unnecessary sys- each variable and giving them their own being able to assign one variable to tem calls. In my application, I can collect type or subtype and range values, the soft- another, regardless of their types and telemetry from the Gilbert III Explorer ware designer adds a level of confidence whether it makes any sense. I am guilty using a sensor collection task. I can then and increases the reliability of the embed- of this, and it can lead to severe run- display the collected data on a laptop ded Ada95 application. The techniques time errors that can cause applications using a real-time display task, while also are not limited just to Ada95, because to crash when one variable overwrites polling the joystick and keyboard for C++, Jovial, and Visual Basic have similar another’s space. Arrays are particularly operator input. Best of all, the GNAT Ada95 tool suite is free. It has already been paid for by U.S. tax payers. A new release of Ada 2005 is already going through the ISO approval process and I hope the GNAT 2005 tools will also be available at no cost to the user. The tool suite includes a graphical user interface (IDE), a GNU Ada95 compiler/translator, and GNU C++. In addition, a debugger (gvd) or (gdb) is also available and directly executes from the IDE. Even non-Windows users can take advantage of programming in Ada95 because it also runs in UNIX and LynxOS. Libraries for accessing the serial port (COM) and the graphics display are also available. There is even a TCP/IP library available that enables Ethernet programming (UDP data- grams), Windows sockets, and more. Ada95 variable attributes include ranges, types, and subtypes, which provide the basic data types used to ® increase software safety and reliabili- ProtoMat S-Series ty. Because range checking or limit PCB Milling Machines checking is performed automatically Electrical engineers agree: with a Protomat S-Series during the execution of an application prototyping machine at your side, you’ll arrive at the by the Ada95 runtime, if variables best solutions, fast. These highly accurate benchtop exceed their predefined limits or PCB milling machines eliminate bread-boarding and ranges, they will generate an Ada95 allow you to create real, repeatable test circuits— exception. The exception can be han- including plated vias—in minutes, not days. dled by the local package, procedure, • Declare your independence from board houses or function or propagated to a higher level or handled by the software • Affordable, entry-level price tag designer. Other runtime errors that • The best milling speed, resolution, and accuracy can generate Ada95 exceptions include in the industry file I/O errors, invalid user input, math overflow, math underflow, and • Single-sided, double-sided, and multilayered machining without hazardous chemicals For complete details visit: more. Each of the conditions can be www.lpkfusa.com addressed with its own error handler. • Optional vacuum table and autosearch camera or call: An example of an Ada95 exception for layer alignment 1-800-345-LPKF handler is shown in Listing 1. When the handler traps a runtime error, it

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 23 2803020_ramirez.qxp 2/5/2008 1:14 PM Page 24

Daniel Ramirez is a senior software engi- Listing 2—A range has a lower bound, L, and an upper bound, R, for a range L. R is shown in the following examples, which are used to define RC servo commands for a Parallax servo controller (PSC). If the application neer at Raytheon with over 15 years of assigns servo commands outside the specified range, it will raise a Constraint_Error. This is a experience working on real-time embed- unique Ada capability that can be simulated in other computer languages using additional limit checks. ded systems. He has a B.S. in Computer Science and an M.S. in Engineering from type WORD_TYPE is record Northeastern University. His hobbies Data_1 : Byte; include watching old movies, antiques, Data_2 : Byte; travel, golf, photography, Circuit Cellar end record; contests, and Vex robotics. for WORD_TYPE'SIZE use 16; PROJECT FILES -- Declare RC Servo subtypes with ranges here... To download code, go to ftp://ftp.circuit -- Use Channels 0..15 with only one PSC board otherwise you can cellar.com/pub/Circuit_Cellar/2008/212. -- use Channels 0..31 subtype Channel_Type is Byte range 0 .. 15; REFERENCE -- RC Servo Ramp [1] D. Ramirez, “High-Performance Motor subtype Ramp_Type is byte range 0 .. 63; Controller,” Circuit Cellar 206, 2007. -- The Servo Position range, (250-1250), corresponds to 0 to 180 -- degrees of servo rotation with each step equaling 2 uSec. RESOURCES -- AdaCore, “GNAT User’s Guide,” --Note: Not all servos are exactly alike. If your servos appear to --strain when commanded to position 250, you should increase the Florida State University Department --250 up to 260 (or so) to prevent the servo from straining itself. of Computer Science, www.cs.fsu.edu/~ subtype Parallax_Position_Type is Word range 250 .. 1250; baker/ada/gnat/html/gnat_ugn_toc.html. J. Barnes, Programming in Ada: Plus subtype number_base is integer range 2..16; -- numeric base subtype f an Overview of Ada 9X, Addison- Wesley, Boston, MA, 1994. susceptible to the errors when the array Ada95 is now provided by 32-bit micro- Intermetrics, Inc., “Ada 2005 Ratio- index exceeds the array limits. C++ and controller-based boards that can be nale,” 1995, www.adacore.com/home/ Java support typing and exception han- used with Windows, Unix, Linux, and ada_answers/ada_2005. dling (try, catch, and throw). Limit LynxOS as their embedded operating Special Interest Group on Ada, “Ada checks can be implemented in any lan- system. Virtually any robotics applica- 95 Bindings,” 2007, www.sigada.org/ guage, although they add some overhead. tion could benefit from the additional ada_95/bindings.html. In Ada95, an exception raised is equiva- safety features afforded by developing lent to the C++ throw keyword: the necessary embedded software U.S. Air Force Academy, “Ada Utili- using Ada95 (and soon Ada 2005). ties,” 2007, www.usafa.af.mil/df/dfcs/ raise SENSOR_READ_ERROR; Although other computer languages bios/mcc_html/ada_stuff.cfm. have similar features, the tasking, pro- Wikipedia, “Ada,” http://en.wikipedia. Variable types are easily converted tected records, deterministic schedul- org/wiki/Ada_programming_language. from one type to another by retyping ing, and real-time constraint checking them (X := float(I);) as long as the are unique to Ada95, which make it an retyped variable being assigned is large ideal candidate for life-critical and par- SOURCES enough to hold the information. In allel-processing applications. XBee-PRO wireless UART this case, X is a 32-bit float and I is a I provided some examples of how Digi International, Inc. 32-bit integer, so there is not a prob- you can use Ada95 with today’s www.digi.com lem with the assignment. Refer to the microcontrollers, including the MMA1260D Accelerometer Circuit Cellar FTP site for an example dsPIC30F6014 16-bit DSP in the wire- Freescale Semiconductor, Inc. of an Ada95 exception handler. less sensor controller board that I used www.freescale.com to collect data from the Vex Power FUTURE APPLICATIONS Glove. Some of my other Ada95 appli- dsPIC30F6014 DSP, MCP6S26 PGA, Ada95 is currently used to develop cations include a USB high-perform- and PIC18F4550 USB 2.0 controller life-critical embedded software used in ance DC motor controller that enables Microchip Technology, Inc. medical devices, aircraft, and aerospace me to control DC motors from a laptop www.microchip.com applications, but it can also be used in by sending its messages via the USB AdaGIDE the future to increase the safety and interface.[1] I plan to continue using U.S. Air Force Academy reliability of commercial and robotics Ada95 as I work on the robotics appli- www.usafa.af.mil/df/dfcs/bios/mcc_ht designs. The platform necessary to run cations shown in Photos 2, 4, and 6. I ml/adagide.cfm

24 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 25.qxp 2/1/2008 10:21 AM Page 1 winners.qxp 2/5/2008 1:53 PM Page 1

WINNERS ANNOUNCEMENT The Microchip 16-Bit Embedded Control 2007 Design Contest gave the world’s most talented engineers a chance to test their design skills and learn more about Microchip’s 16-bit microcontroller and digital signal controller (DSC) families. Thank you to everyone who participated in this contest.

To see the complete projects and more, www.circuitcellar.com/microchip2007/.

FIRST PLACE Variable Speed Induction Motor Controller Variable-speed drives for AC induction motors are readily available on the market. But what if you need one for a single-phase motor that operates in the 2-HP range? This innovative controller is the solution. Designed for use with a capacitor-start/capacitor-run motor, it includes active power factor correction (PFC) and inrush current limiting. The motor drive hardware is built around a dsPIC30F2020 DSC. The drive communicates via an optoisolated serial port to a PIC16F687-based interface unit.

Richard Wotiz U.S. [email protected] “My project is a variable speed drive for a 2-HP single-phase AC induction motor and includes active power factor correction. It has a control port which interfaces with a standard spa control sys- tem to control the pump speed. The motor drive hardware is built around a Microchip dsPIC30F2020 digital signal controller. At first I was overwhelmed by the number of DSC part choic- es, but was able to narrow it down to a part with the exact features I needed. I also found the ver- satility of the peripherals to be very helpful, even though it made them more challenging to use. In a high-power design such as this, it was hard to know in advance which settings would give the best per- formance or efficiency, so the many options of the PWM and ADC modules were very helpful to have for last-minute adjustments.” —Richard Wotiz

To see these projects and more, visit www.circuitcellar.com/microchip2007/. winners.qxp 2/5/2008 1:53 PM Page 2

SECOND PLACE & Connected (Communications) Applications Multifunctional Alarm Clock Unlike old-school mechanical alarm clocks that you have to set manually, this Internet-connected alarm clock provides three primary features: automatic time setting on power-up, streaming MP3 music, and remote management. The easy-to-use, PIC24FJ64-based clock is connected to an ENC28J60 Ethernet chip, an MP3 decoder chip for streaming music, an organic LED graphical display, and a 24LC512 EEPROM for storing alarm data, fonts, and images.

DJ Delorie U.S. [email protected] “My project is a streaming Internet alarm clock. It has no self-contained music ability, but instead streams MP3s off my office computer. It has the potential to be connected to streaming radio sta- tions. My old alarm clock, which I also built, was dying, and I needed a replacement that let me set the alarm from my office so I wouldn’t wake up my wife at night. This project was also an excuse to try out some new technology, like OLED displays and MP3 decoder chips, as well as learn about the PIC24 microcontroller. The PIC24 was easy to prototype with because it came in a standard DIP package. I had the entire design working on a solderless bread- board before committing it to the PCB, and adding support for ICP was trivial. The pin select feature really came in handy, as I needed a lot of peripher- als for this project. Without it, I would be forced to use a package with more physical pins.” —DJ Delorie

THIRD PLACE Full-Feature Portable LCR Meter LCR meters used to be relegated only to professional design labs. Not any more. This portable LCR meter makes it easy for you to analyze the analog performance of virtually any device under test, whether in your lab or on the job. The dsPIC30F4012- based meter uses DDS techniques and DSP methods to condition the resulting voltage and current signals. Its handy user interface and graphic LCD make it easy to operate and read.

Miguel Rusch Australia [email protected]

“I built a prototype for a portable LCR meter. This tool measures the AC impedance of passive devices at a range of frequencies (100 Hz, 1 kHz, and 10 kHz), displaying the measured parameters on an LCD screen alongside a schematic representation of the circuit. It is a tool that’s useful for identifying unmarked SMD parts and characterizing hand-wound inductors. The dsPIC processor has a rich set of periph- erals to compliment the DSP core. My project obviously required DSP filtering because of the frequency domain measurements; however, without the supporting peripherals, I would have never integrated so much circuitry with a 28-pin device. I made heavy use of the SPI module which communicates with five separate ICs. Additionally, the ADC module enabled extensive configuration, allowing the device to efficiently and simultaneously read the test waveforms and also detect user input from the resistor ladder keypad.” —Miguel Rusch

To see these projects and more, visit www.circuitcellar.com/microchip2007/. winners.qxp 2/5/2008 1:53 PM Page 3

TOP HONORS

Effective Use of SMPS Resources MiniTron Amplifier The MiniTron is a high-end vacuum tube stereo amplifier with efficiency, distortion, and power output controlled by a dsPIC30F2023. The innovative system features three main subsystems: a vacuum tube amplifier, a DSP controller, and a high-voltage switching power supply. The fully functional amplifier successfully blends its unique circuitry and specialized processing software to precisely match the radically different worlds of high-voltage analog and low-voltage microcontrollers.

George Anderson U.S. [email protected]

“The MiniTron amplifier is a high-end vacuum tube stereo amplifier with distortion, efficiency, and power output enhancements provided by some unique circuitry featur- ing a dsPIC controller. This project was an opportunity to take vacuum tube technolo- gy into the 21st century. I find that Microchip’s controllers in general are a bit easier to use than some other microcontroller ICs. I have designed circuits with PICs, but this was my first dsPIC design. The controller section of the design went together smoothly and worked correctly the first time. Microchip’s tools and evaluation boards made it possible to test out a good portion of my design before committing to it. There was enough sample code on Microchip’s web site to prove out the tracking buck converter on a Microchip evaluation board before building any hardware.” —George Anderson

Effective Use of Motor Control Resources EV Inverter Project The Electric Vehicle (EV) Inverter project is a starting point for engineers trying to convert a vehicle with a gas engine to one with an electric motor. The innovative inverter was built using a control board and software based on Microchip Technology’s MC-1 devel- opment board. It features a dsPIC30F6010A and three dual IGBT modules with gate driver boards. The finished system can power a wide range of AC induction motors.

“As the world is currently in the process of advancing alternative sources of energy, the concept of the electric vehicle (EV) conversion is becoming more and more popu- lar. However, anyone interested in this concept will discover that the process of con- Dena Ponech, Doug Krahn, Adam McIntyre, verting a gas-powered vehicle to electric power is fairly cost-prohibitive. Our inverter Tristan Kasmer, and Dan Hall was constructed using a control board and software based on Microchip’s MC-1 devel- opment board and three dual IGBT modules with gate driver boards. We chose these Canada development tools to build a basic 100-kW, three-phase inverter in an open-source [email protected] process, which can be continually improved upon. Microchip’s many on-chip resources were easy to use and were an excellent fit for our project.” —Dena Ponech

Use of Peripheral Pin Select Electronic Mini-Badge The Electronic Mini-Badge is a PIC16F64GA004-based electronic badge that displays color slideshows. Many elec- tronic badges display scrolling text using a matrix of dis- crete LEDs. This low-power system features a graphical OLED display and can be easily upgraded to handle ani- mation, video, or RF communication.

“The Electronic Badge project is an electronic version of the standard name badge. I did a simpler version of it before, but I created this ver- Jan Szymanski sion with more functionality. I like the Microchip parts. They are well Australia documented and good support is available in the form of application [email protected] notes, examples, and discussion forums.” —Jan Szymanski

To see these projects and more, visit www.circuitcellar.com/microchip2007/. winners.qxp 2/5/2008 1:53 PM Page 4

TOP HONORS

Effective Use of DSP Technology NUE-PSK Digital Modem The dsPIC33F128MC706-based NUE-PSK Digital Modem is a portable PSK31 interface. The stand-alone, battery-operated system enables PSK31 field operation without the use of a PC. The novel system includes two LCDs. LCD-1 is a 4 × 20 character display for transmitting and receiving text data. LCD-2 is a 144 × 32 pixel graphics display for showing the FFT-generated spec- trum of the audio passband.

“Our design is a compact digital communications modem for amateur radio operators. Since most digital systems used by amateurs require the use of a computer with sound card, they are not easily used for field operations (e.g., in George Heron and Milton Cram remote areas). This prompted the design of our low-power, portable modem for use with a single-sideband amateur transceiver, which itself can be quite small U.S. and portable (i.e., contained on a single 4† × 4† PC board). Low power consump- [email protected] tion, plenty of code and data memory, built-in DSP capability, and low-cost development tools were key requirements for an amateur radio project. The dsPIC33F was an excellent choice.” —George Heron & Milton Cram

Best Use of Bonus Parts Data Acquisition System for Radiation Measurement This innovative data acquisition system measures cosmic rays, natural background radiation, and emissions from other radioactive objects. The compact system features dsPIC30F4012 data acquisition processors running in parallel in a “variable time slice” manner. A dsPIC30F6014A controls the data-acquisition processors, gathers the collected data, and formats the data for display.

“I think of my project as a ‘glorified Geiger counter.’ The purpose was to build a device for the study of ionizing radiation, and at the same time experiment with data acquisition techniques using Microchip’s 16-bit micro- controllers. The system includes an analog front-end that interfaces to three types of radiation sensors, a group of parallel data acquisition proces- Peter McCollum sors, and a single supervisor processor that controls the overall operation and interfaces with the user. I enjoy working with the 16-bit family. Because U.S. of the small package sizes that are available, it is practical to use them even [email protected] in smaller, simpler applications that would previously have used an 8-bit MPU.” —Peter McCollum

Use of Smart Sensing Methodologies Braille Glove The well-designed Braille Glove system simulates the 26 Braille codes. The system features two gloves that communicate wirelessly. The main board includes a dsPIC33FJ256MC510 microcontroller, which controls four vibration motors, four accelerometers, and a 32-KB SPI serial EEPROM 25LC256. This system provides a unique method for someone to both read and speak using Braille.

Hoa Phan, Vincent Dinh, Tu-Anh Ton, and Nghia Tran U.S. [email protected]

To see these projects and more, visit www.circuitcellar.com/microchip2007/. 2803014_MSanchez.qxp 2/5/2008 3:17 PM Page 30

FEATURE ARTICLE by Miguel Sanchez Vertical Plotter System Miguel explains how to build a vertical plotter system that can draw on canvas with a pencil or charcoal stick. The compact, portable system consists of a pen holder hanging from pul- leys on two stepper motors. In this article, he describes the entire process, from hardware development to programming the system.

Throughout history, painters have machine that paints over a vertical inspired me to build this one). The used whatever technology was available wall with a spray can. A solenoid was system is easy to carry around and to help them with their art. It is believed used to press the can’s nozzle. you do not need a spare room to that Johannes Vermeer, like other Dutch Although my goal was to use a pencil, install it (see Photo 1). It also requires masters, used a dark chamber to help I liked the simplicity of a system that fewer parts than a standard XY plotter. him lay down the detailed and realistic hangs from two stepper motors on the impressions on his paintings. The bot- two upper corners of a drawing area. MECHANICAL SYSTEM DESIGN tom line is that the use of technology I liked their design, so I built my own. I The painting machine consists of is not cheating—or at least that is call it Viktor (it shares the last four let- two stepper motors (I had a couple of what my wife told me when I began ters with Hektor, the project that 1-A/5-V unipolar motors on my desk toying with the idea of building for several years) located on the

a painting machine to help her L top left and on the top right of with her paintings after spend- the drawing area (see Figure 1). ing a weekend serving as her You can change the horizontal painting machine. distance between them to The goal of this project was Left Right accommodate a wider canvas. motor motor to build a system that could The unit holding the pen hangs use a pencil (or charcoal stick) from the motors’ pulleys to form ab to draw the contour of a scene a V shape. Depending on the that you want to paint on a length of ribbon each stepper canvas (see Figure 1). Of course, motor is releasing, the location there is still a lot of work for of the pen holder changes. Gravi- the artist’s hand afterwards, but ty pulls the pen holder down- it helps to have this first step ward, so motors aren’t required done quickly. Plus, it is easily to pull down the pen holder. repeatable if you are planning a (x,y) I was naive enough to think series of the same image. that I could use just some

One problem with the sys- Pen up/down string from the stepper motors tem was that the size of the motor to the pen holder, but after a painting area was not always quick test, it became apparent the same and I did not have the that any sliding on the pulleys a2 = x2 + y2 room for a large painting sys- (0,0) ruined the result. So again, I b2 = (L – x)2 + y2 tem. My first idea was to build followed what the Hektor mak- an XY plotter with a couple of ers did and used toothed belts b stepper motors, but such a sys- a (like your car’s timing belt but tem would require a lot of y open-ended) and toothed pul- space and would have to be leys on the stepper motors. I (x,y) built for the maximum canvas x (L – x) used an MXL-sized toothed belt size. I was looking for alterna- (5.08 mm) and 10 teeth pulleys L tives when I discovered a proj- (a revolution of the stepper ect by some Swiss students Figure 1—This is the system model and its associated mathematical model. motor is 50.8 mm in belt called Hektor, a painting Several simplifying assumptions are made here. length).

30 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803014_MSanchez.qxp 2/5/2008 3:18 PM Page 31

a) b) c)

Photo 1a—Check out the system in action. b—This is a close-up shot of the output of one of the sample files. c—Here the output is “CIRCUIT CELLAR.”

A word of warning: you do not want exactly what I would call a stepper want it to stay still. to machine a steel pulley with your motor controller, but it worked well home drill, trust me. If you are buying with my two unipolar motors. The MATH the hardware, try to match the stepper software included an ActiveX compo- If you are familiar with the motor axle diameter to the pulley nent that I could include in a Visual Pythagorean theorem (Gougu’s theo- bore. Basic project. Sample code was provid- rem for Chinese readers), you can A couple of bearings press the belts ed. I hadn’t used Microsoft Visual understand how the system works. If against the pulleys to keep the teeth Basic for quite a while, but after you aren’t, trust me, it works. inside the pulley slots. This ensures downloading the free Express Edition, The two motors operating the pul- system accuracy, which is important I was up and running in no time. leys control the lengths of the two because you are going to work on an I tried to use a solenoid to lift the pen belts the pen holder hangs from (see open-loop system (no position feed- up and down, but given my lack of Figure 2). The two motors are located back). mechanical skills, the system wasn’t at a particular distance (L) from each The pen holder mechanism I used operating properly. So, I switched to a other. The left triangle is defined by involves a third stepper motor. I more elaborate mechanism, where the the left motor, the pen holder and the obtained it from an old floppy disk rotation of the motor translates into a intersection from the horizontal line drive in my employer’s storage room. I longitudinal motion that moves a from the pen holder, and the vertical noticed it was a bipolar motor (only metal lever so the pen touches (or does- line from the left motor. The four wires), so I sawed out part of the n’t) the canvas’s surface (see Photo 3). hypotenuse of such a triangle is the original PCB of the drive so I could The pen’s up/down system uses a square root of the sum of the squares keep the controller IC. (Fortunately, it floppy’s bipolar motor. But outputs of of both legs (x and y). was still in working condition.) the controller were not suited for a The other triangle is similar, but it Wires were soldered to connect the bipolar motor. I kept a small piece of is formed with the left motor and controller board to the pen holder. It the PCB from the original floppy disk with one leg being y, the same as the isn’t very elegant, but it’s effective. driver circuit (see Photo 4). This former, and the other being L-x. From made the bipolar motor easy to inter- the two triangles, it is easy to calcu- CONTROLLER BOARD face using the unipolar outputs late the respective hypotenuses to At first, I planned to use a PC to intended for a third motor. That was locate the pen holder at the desired control this device—after all, a user when I realized that full control of XY coordinate. would draw designs on a computer— each output line (as opposed to a real The stepper motors I am using are but I did not have any suitable hard- stepper motor controller) proved ware to use for this project. Fortunate- quite useful here. ly, after searching the Internet, I dis- The bipolar controller used on the covered a USB-based stepper motor floppy drive was Sanyo’s LB1656, controller from an Australian compa- which used a couple of logic signals ny. It features a Cypress Semiconduc- (D1 and D2) to control the polarity of tor microcontroller and a couple of each one of the stepper motor coils ULN2803 line drivers (see Photo 2). (see Figure 2). A third logic level The board controls three unipolar enabled the selection between Hold stepper motors up to 1 A/30 V and and Seek actions. Seek sends 12 V to includes some sample software. the coils, while Hold is only 5 V (the While working with the board, I higher the voltage, the more torque). I realized that the board had 12 open set the pin to Seek when I want the Photo 2—This is the USB stepper motor controller that collector outputs, which wasn’t motor to move. I set it to Hold when I is used in the project.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 31 56-57.qxp 7/2/2007 10:52 AM Page 1 56-57.qxp 7/2/2007 10:52 AM Page 2 2803014_MSanchez.qxp 2/5/2008 3:18 PM Page 34

a) b)

Photo 3a—This lever enables the pen to touch the canvas. b—This is the motor that raises the pen lever.

200 steps per turn. Because of the pul- set the pen holder to the home loca- line segments (also called multi-line). leys I use (10 teeth per turn) and the tion; however, you will need input Before drawing a path, the pen holder tooth distance 5.08 mm (or 0.2″), the lines to detect that the pen holder has has to be at the initial dot location. spatial resolution is 10 × 5.08 mm/200 reached a certain location. Unfortu- Next, the pen is set down and tracing steps or 0.254 mm/step (or 0.01″ per nately, my stepper motor controller starts. From the first dot towards the step). So, given the desired Cartesian does not have any input, so I manually second dot of the path, the process coordinate, it is easy to calculate the locate the pen holder at a known loca- repeats until the last dot of the path is corresponding lengths for the left and tion before starting any drawing. reached and the pen is set up. The right belts. The second problem is obtaining the aforementioned sequence is repeated sequence of commands to draw the for each path of the drawing. SOFTWARE lines you want the system to paint. I There is something counterintu- You know how to build a painting am familiar with vector drawing pro- itive about the dynamics of drawing a machine and you understand the math grams and the scalable vector graphics line in this system. Sometimes a to tell the stepper motors what to do, (SVG) file format. It happens to be an motor rotates clockwise and then but there are two more problems to XML-based format, so you can easily changes to counterclockwise while resolve. The first one is easy. You need look at it with any text editor pro- drawing the same straight line. This a way to establish the initial pen hold- gram. It is also easy to parse. happens because the relationship er position. A home position has to be I opened a new file on Inkscape soft- between the XY coordinates and the defined accurately because all of the ware. I used a tablet to draw several corresponding belt lengths is not lin- belt’s movements are relative to the lines as a test file. I then looked at the ear. From this observation, it is previous location. If that is not cor- resulting lines and realized that most apparent that a stepper motor con- rect, then you will get a pretty distort- of them were Bezier lines. I mean troller that you instruct with the ed drawing (which may be still usable curves. While I could write some code final location and the desired acceler- if you are into the abstract art scene). to turn that into a sequence of XY ation shape will not help you here. Like any other printer, you might coordinates, I thought there had to be To get a straight line, both motors need to conduct an initial routine to a better way. Fortunately, I discovered have to move little by little and not that Inkscape software has an directly to the final location. effect called “Flatten Bezier,” A great and pleasant surprise was which turns these curves into that Visual Basic includes support for a sequence of straight lines. regular expressions, which is a bless- Drawing a straight line in ing when you are parsing text lines. software is quite easy. Just (To see how this is done, refer to the use Bresenham’s algorithm. code files posted on the Circuit Cellar FTP site.) DRAWING AN IMAGE FILE Your machine’s readable POSSIBLE IMPROVEMENTS SVG file format stores each Getting the system working at an Photo 4—I saved the PCB from an old floppy drive with the bipolar path (processed as above) as a acceptable level took a lot of energy, stepper motor driver circuit. sequence of dots connected by so I left out some details. One

34 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803014_MSanchez.qxp 2/5/2008 3:18 PM Page 35

involves trying to reduce the total man problem is built using all the may be a bit of a problem for users distance covered by the pen holder for endpoints of all the paths on the who require better accuracy. a given drawing. This problem is also drawing. The cost between the end- known as the travelling salesman points of the same path is set to a DESIGN AND DRAW problem. negative value. For any other cost Despite the challenge, my vertical If you do as I did, your image file’s between endpoints, the Euclidean dis- plotting machine was fun to build. paths are stored in the file in a way tance is used. The problem can be In addition to its entertainment that might be far from optimum when solved using “Concorde” software value, it is also pretty useful. using a mechanical system like this that’s freely available from Georgia Please note that although your one. However, this is not significant if Tech University. math might tell you that you can you are drawing on a computer screen. A second improvement I have in reach the top of the drawing area, The lack of this optimization means mind is to monitor the pencil. I want you should keep a safe distance from that the pen holder might be moving the system to warn me when the tip is the top, left, and right margins. This up and down all the time instead of too dull for drawing. will ensure good accuracy when concentrating on the paths on top of Although the hanging belts are mod- drawing. If you need to draw a wider the image before starting to draw eled as straight lines, they are not. In picture, simply increase the distance those on the bottom. This will trans- fact, for those of you who are curious between the two motors (or position late into a much longer (but possibly enough, the two belts form segments your canvas in Portrait mode and entertaining) drawing time. of a curve called a catenary. A cate- rotate your image 90°). I I contacted Professor Michael Trick, nary is the shape a chain forms when an expert on Operations Research at it is hanging from two supports under Carnegie Mellon University, who its own weight. While the error of my Miguel Sanchez ([email protected]) kindly provided me with a simple and simplified mathematical model is holds a B.S., an M.S., and a PhD in elegant solution. A travelling sales- acceptable for artistic renderings, it Computer Science. He has taught com- puter networks courses at the Techni- cal University of Valencia, Spain, since 1989. Miguel’s interest in electronics and sparked his career in computer science, but his solder is always at hand. His research is cur- rently focused on vehicle energy effi- ciency. Miguel also works as a consult- ant. A video of this project is posted at www.youtube.com/watch?v=Vm B14M78CWU.

PROJECT FILES To download code, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2008/212.

RESOURCE Hektor project, http://hektor.ch.

SOURCES Visual Basic 2008 Express edition Microsoft Corp. http://msdn.microsoft.com/vstudio/ express/vb/

LB1656 Stepper motor controller Sanyo Electric www.sanyo.com

USB Stepper motor controller Figure 2—This is the wiring schematic diagram. Both unipolar stepper motors are shown. I also used a recycled Softmark bipolar stepper motor with a small hack. www.ar.com.au/~softmark

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 35 2802017philippsen.qxp 2/5/2008 3:44 PM Page 36

FEATURE ARTICLE by Michael Ghazi, Stefan Kaban, Scott Morken, Carl Philippsen, & Kyle Wong Flight Control A Communications System for an RC Helicopter

Whether you are looking to control an RC helicopter or a full-sized car, this system will work for you. By facilitating communication between a base station and a vehicle, the system enables an operator to process commands and receive data.

Anyone who lives near a model air- transmitted between a base station inspection, and more. plane club can attest to two things: the connected to a laptop computer and a annoying buzzing of nitro engines and receiving module on the helicopter. SYSTEM OVERVIEW the amazing abilities of some of the Sensor data and user commands con- The communications system is scale models. Along with planes, model trol an array of servo motors. With the designed to transfer data between the helicopters are sometimes encountered right modification of servos and sen- base station and the target device. Our at these clubs. They are more maneu- sors, this concept for control could target device is an electric RC helicop- verable than their larger brethren, capa- easily be implemented to aid in the ter. The communications system con- ble of performing aerobatic maneuvers control of other types of RC or full- sists of PC software at the base sta- and inverted flight. A characteristic that scale vehicles, including boats, planes, tion, hardware on the base station, scale-model and full-sized helicopters or cars. hardware and firmware on the heli- share is their difficulty to pilot, especial- Who can use a system like ours? A copter, and a communications proto- ly for inexperienced technology stu- search and rescue team could send out col to tie everything together. dents. So, when it came time to develop multiple autonomous helicopters The PC software consists of three our final project in our technology pro- equipped with cameras. The smaller- subsections: the communications gram at Camosun College, we chose to scale autonomous helicopters would class library, the indicator user control work on an autonomous, self-balancing have a better chance of finding people library, and the Google Maps user con- model helicopter. in distress than a single full-scale heli- trol (see Photo 1). The communications An important part of this project copter. Also, the smaller-scale library links the GUI to the helicopter. It involved developing a communications autonomous helicopter would come is built around a serial port connection system for sending commands to the hel- with a smaller price tag than the full- and it provides a simple interface for icopter and receiving status information scale version. But in return. Using simple, readily available the applications for hardware and extensive software, we suc- this communica- cessfully implemented the communica- tions system are tions system to keep the base station not limited to connected to the helicopter. search and rescue. In this article, we’ll describe our This system could communications system. It comprises be used to help firmware and a communications protocol. remove human involvement with APPLICATIONS virtually any vehi- Our communications system was cle’s operation. You originally designed to control an RC can use the system helicopter. The system uses software, to control vehicles firmware, and a communications pro- for cinematogra- tocol to send commands to the helicop- phy, aerial map- ter and receive information from it. The ping, law enforce- Photo 1—This is the graphical user interface for our system. The customizable indicators command packets and data packets are ment, surveillance, enable us to keep track of any data received by the base station.

36 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2802017philippsen.qxp 2/5/2008 3:44 PM Page 37

the GUI coder. The indicators library shows the user telemetry data from the helicopter. It can display customizable dials, a compass control, an artificial horizon, and indicator lights. The over- all indicator design mimics a helicop- ter or airplane instrument panel. The Google Maps user control defines way points for the helicopter and shows its position. For base station hardware, we used an antenna, a USB-to-Serial module, and a transceiver module mounted to a PCB. The hardware on the helicopter for the communications system con- sists of an antenna, a transceiver module, and a Microchip Technology dsPIC30F3011 microcontroller. The com- munications protocol is a rule set that governs the transmission of data between Figure 1—This is a schematic of the base station and remote unit hardware. the base station and the helicopter. We used a pair of Low Power Radio increased range and better signal quali- HARDWARE Solutions ER900 TRS 900-MHz trans- ty. Plus, we got it for free because one of We knew from the start that the most ceiver modules to send data between our instructors purchased it on the con- difficult aspect of this project would be the base station and the helicopter (see dition that we give it to him (for one of the software. For this reason, we used Figure 1). We chose the modules for their his evil schemes) when we were done. simple pieces of proven hardware to get simple serial interface, their operation in the job done so we could have more an unlicensed band, and their ability to PERFORMANCE EVALUATION time to focus on the software. The take care of error handling. The transceiv- We tested the communications sys- communications system hardware on er modules are mounted to PCBs, which tem and determined the data rate was the helicopter is virtually the same as we designed and manufactured at 517 bps. We calculated this with a meas- the hardware in the base station. Camosun College (see Photo 2). The ured time per byte of 17.4 ms, which is base station board, which close to the datasheet’s minimum spec- holds one of the transceiv- ified value of 15.978 ms. The latency of er modules, also holds a the packets varied depending on packet USB-to-serial converter. length, with an average delay of 46.75 ms. The USB-to-serial convert- We measured this delay as the time from er is the link between the when a set of outgoing data is loaded into transceiver module and the the radio’s buffer to when an acknowl- software on the PC. edgement is received. Our latency meas- The helicopter radio urement does not take into account the module is coupled to a 4″ unpredictable delay caused by the omni-directional whip non-real-time nature of Windows XP. antenna and interfaced to The message throughput can vary the USART of the onboard depending on which error rate is consid- microcontroller. This ered acceptable. We made two measure- antenna works well on the ments. At 3.03 packets per second, we helicopter because it is determined the error rate was 2.05%. At small and fairly lightweight. 4.08 packets per second, the error rate For a base station antenna, was 2.33%. The two packet rates were we started with a second 4″ used to illustrate the trade-off between omni-directional whip the packet throughput and the number of antenna. The signal was errors that occur. As packet throughput somewhat limited using increases, the error rate also increases. this antenna, so we chose to upgrade to a 12-dBm, 4′ PROTOCOL Photo 2—This is the main control board of our helicopter. Visible at the long, nine-element Yagi- The protocol we developed is a set top right of the photo are the radio module and the antenna connector. Uda antenna. This gave us of rules that enables us to maintain

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 37 2802017philippsen.qxp 2/5/2008 3:44 PM Page 38

Header Length Data Checksum Footer the base station can’t know when an 0xA5 0x5A 0x03 0x54 0x45 0x32 0x00 0xCE 0xCC 0x33 onboard error will occur. To ensure that — — — Family Command Payload Sum of data and length — — all transmissions from the base station Table 1—This is an example of a packet sent between the base station and the helicopter. This packet, when are received, each one is acknowledged received and decoded by the helicopter, will set the speed of the engine. by the helicopter in one of two ways. Command packets are acknowledged by the helicopter by transmitting the entire reliable communication between the command byte for the base station to packet, plus an ACK byte (0x06, which base station and the helicopter. Work request a preflight packet (“P” for pre- comes after the length byte). Information on the communications protocol began flight). The command group byte dif- requests are acknowledged by simply even before the official start date of our ferentiates the two. The command sending the information requested. If an project. This was a large task, which byte then tells the receiving station error is detected in the packet, the packet we needed to complete quickly so we exactly what command is sent. In is ignored and no ACK is sent. It is the could use it to test other aspects of the Table 1, 0x45 indicates an engine master’s responsibility to retransmit helicopter’s operation. The full code speed change. (Hexadecimal number any commands or information requests communications protocol is available 0x45 is an ASCII character “E,” for that are not acknowledged. on the Circuit Cellar FTP site. engine speed.) The checksum is used to Table 2 is an overview of the com- The communications protocol is fairly verify that the data received is the data plete communications protocol. For a simple in the sense that we did not that the transmitter intended to send. It detailed description of all packets and incorporate any error checking. This is defined as the two least significant payloads, refer to the Communications was possible because the radio modules bytes of the sum of all the bytes in the Protocol document posted on the we used have some good error-checking length and data portions of the packet. Circuit Cellar FTP site. routines of their own. There are several The footer simply indicates the end of bytes within the protocol that have spe- a transmission. FIRMWARE cific tasks. The header bytes are used to In our master/slave system, the base The data sent via our protocol has to “wake-up” the receiver so it can begin station is the master and the helicopter is be decoded and used once it is received recording and decoding the incoming the slave. This has a number of implica- by the helicopter. This task is per- transmission. The length byte tells the tions. The base station initiates all com- formed by our firmware program. The receiving station how many bytes are in munications, and the helicopter doesn’t firmware handling our communications the data portion of the packet and transmit unsolicited data. The only is loaded onto a dsPIC30F3011 on the includes the command group, command, exceptions are error messages, because helicopter. We chose this microcon- and payload portions. The troller because it has pow- command group byte tells Group description Group byte Command Command description erful processing abilities, the receiving station (either Testing/tuning 0x54 0x45 Engine speed adjust which we use in our heli- the helicopter or the base sta- 0x54 0x50 Pitch servo adjust copter for control calcula- tion) what type of command 0x54 0x52 Roll servo adjust tions, and because we is being sent. For example, it 0x54 0x43 Collective servo adjust happened to have a stash might be a testing/tuning 0x54 0x51 Anti-torque servo adjust available to us at school. command, in which case the 0x54 0x66 Set operations mode The firmware, which is command group byte would 0x54 0xDD General-purpose data dump essentially an onboard be 0x54. We included a Flight operations 0x46 0x45 Engage engine packet parser, comprises command group to make 0x46 0x48 Hover two separate state decoding simpler and better 0x46 0x43 GPS Correction factor machines. The first state documented. Another pro- 0x46 0x47 Go to GPS coordinates machine checks the packet grammer looking at the 0x46 0x52 Return to base header and data length, state machine can easily go 0x46 0x50 Request pre-flight packet copies the data into a to the group in question and 0x46 0x4D Discreet movement buffer, verifies that the have fewer commands to 0x46 0x49 Request for information checksum is correct, and sift through. Telemetry data 0x74 0x4C Location checks if the footer is valid. We use command bytes 0x74 0x48 Heading/speed/altitude If everything is fine, it that make sense. For exam- 0x74 0x5A Attitude sets a valid data flag. This ple, the hexadecimal num- 0x74 0x42 Battery status starts up the second state ber 0x50 is an ASCII char- 0x74 0x45 Error report machine, which parses acter “P.” This is the char- 0x74 0x50 Preflight packet the valid data packet. It acter used in the command 0x74 0x52 Rotor RPM checks the first byte to to change the pitch servo determine which com- Table 2—This is a listing of the communications protocol used in our system. The protocol is pulse width (“P” for pitch). flexible and it can expand to up to 65,535 commands, which would be broken into 256 groups. mand “family” the com- However, “P” is also the As an added bonus, the code is easily modified to accommodate the extra commands. mand belongs to and

38 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 39.qxp 1/28/2008 1:05 PM Page 1

97& 'SRRIGXIH High Speed PC Oscilloscopes ERH 7TIGXVYQ %REP]^IV

4MGS7GSTI7IVMIW 1JDP4DPQFIBOEIFMEPTDJMMPTDPQFTDPOWFSUZPVSMBQUPQPSEFTLUPQ1$JOUPBQPXFSGVMPTDJMMPTDPQF TQFDUSVNBOBMZ[FSBOE  4&3*&4

 NFUFSXJUIPVUUIFOFFEGPSBEEJUJPOBMQSPCFTPSQPXFSTVQQMJFT

1PXFSBOE1FSGPSNBODFJOZPVSIBOE 5IF  4FSJFT PG PTDJMMPTDPQFT GSPN 1JDP 5FDIOPMPHZ JODMVEF HFOFSBM QVSQPTF BOE IJHI SFTPMVUJPO NPEFMT 8JUI  CJU SFTPMVUJPO BOE  )BOEIFMEPTDJMMPTDPQFTGSPN1JDPIBWFCFFOFSHPOPNJDBMMZ BDDVSBDZ UIF .)[ 1JDP4DPQF  JT BCMF UP EFUFDU DIBOHFT BT TNBMM BT EFTJHOFEUPGJUQFSGFDUMZJOZPVSIBOE8IFUIFSZPVSFMFGUIBOEFE   QQN  NBLJOH JU UIF JEFBM DIBOOFM PTDJMMPTDPQF GPS SJHIUIBOEFE IBWFCJHPSTNBMMIBOET 1JDP4DPQFIBOEIFMETDPQFT BSFMJHIUXFJHIUBOEDPNGPSUBCMFUPVTF BOBMPH EFTJHO BOE BOBMZTJT 5IF IJHIFS TQFFE  CJU NPEFMTJOUIF1JDP4DPQFTFSJFTGFBUVSF 5IF1JDP4DPQFIBTBNFHBTBNQMFQFSTFDPOE

 4&3*&4 TBNQMJOH SBUFT VQ UP .4T BOE VQ UP SFBMUJNFTBNQMJOHSBUF'PSSFQFUJUJWFTJHOBMTUIFTBNQMJOHSBUFDBO  .4 SFDPSE MFOHUIT GPS HFOFSBM QVSQPTF CFJODSFBTFEUPHJHBTBNQMFTQFSTFDPOEVTJOHEJHJUBMFRVJWBMFOU BOE QPSUBCMF BQQMJDBUJPOT UJNFTBNQMJOH5IFTFIJHITBNQMJOHSBUFTDPNCJOFEXJUIB  TBNQMFCVGGFSNFNPSZBOE.)[BOBMPHVFCBOEXJEUINBLFUIF 1JDP4DPQFTVJUBCMFGPSBXJEFSBOHFPGUSPVCMFTIPPUJOHUBTLT POCPUIBOBMPHVFBOEEJHJUBMDJSDVJUT5IFFOUSZMFWFM1JDP4DPQF 8JUIDMBTTMFBEJOH.)[ JTBMTPBWBJMBCMFGPSVTFJOMFTTEFNBOEJOHBQQMJDBUJPOT CBOEXJEUI (4TTBNQMJOHSBUF  NFNPSZEFQUIBOEBOBSSBZPG &SHPOPNJDBMMZEFTJHOFEUPGJUJOUIFIBOE BEWBODFEIJHIFOEGFBUVSFT JODMVEJOH 6QUP.4TSFBMUJNFTBNQMFSBUF BEWBODFEUSJHHFST B.)[4QFDUSVN 6QUP(4TSFQFUJUJWFTJHOBMTBNQMFSBUF "OBMZ[FS )JHI4QFFE64#$POOFDUJPO   4&3*&4 6QUP.)[CBOEXJEUI "VUPNBUJD.FBTVSFNFOUT BO"SCJUSBSZ8BWFGPSN(FOFSBUPS BOE8BWFGPSN 6QUP TBNQMFCVGGFSNFNPSZ 1MBZCBDL5PPL UIF1JDP4DPQF1$0TDJMMPTDPQFTHJWFZPVUIFGFBUVSFTBOE QFSGPSNBODFZPVOFFEXJUIPVUBOZDPNQSPNJTF 1JDP4DPQF 1JDP4DPQF www.picotech.com/pco414 to check out our full line of pc based instruments or call 1.800.591.2796 for information 2802017philippsen.qxp 2/5/2008 3:44 PM Page 40

checks the actual command. It then size change or other events. Dial indica- determines which action is appropri- tors can be customized easily for many ate to take based on the command. different applications. The numeric Table 1 shows a complete example of range, labels, number of ticks, color an engine speed packet. ranges, and other aspects can be modified to suit any application. The left-most SOFTWARE dial in Photo 1 is an example of a tem- The PC software is designed to keep perature dial that has been set up with a you in control of the helicopter and –40° to 100°C range and warning bands informed of its status. It has three main for “under” and “over” temperature. components: the communications class We drew all of the indicators using the library, the indicators user control graphics device interface (GDI). We start- library, and the Google Maps user con- ed by making the gauge class, which trol. All parts of this software are coded inherits the basic Windows user control in C# using the .NET framework and and implements all features that are com- the Microsoft Visual Studio 2005 IDE. mon to center dial, artificial horizon, and The communications library is used to compass classes. In turn, each of the link the GUI to the helicopter. It is built classes inherits the gauge class. An around a serial port connection. The important thing we learned was the value library provides a simple interface for a of using double buffering to prevent flick- GUI coder to use the communications ering of the things drawn using GDI.[1] protocol. It enables all packets to be sent The Google Maps user control shows by a simple function call and each the position of the helicopter with GPS received packet raises an event for the coordinates received via the communi- GUI to handle. All other functionality, cations protocol. It is also used to define such as error checking and packet pars- way points for the helicopter. The user ing, is dealt with internally by the com- control requires an Internet connection. munications class library. The library is It is based on a .NET web browser con- centered on a .NET serial port object and trol that loads Power Map, a JavaScript a high-speed timer. Each time the timer page containing interface functions to event is raised, the library checks the use with Google Maps. The JavaScript serial port buffer to see if its contents are on this page forms a wrapper around the a valid packet or if there is a transmis- Google Maps API. It is what the map sion error. The serial port object raises an control interfaces to. Each time a GPS event when bytes are received, but we packet is received from the helicopter, found the event was not raised reliably we convert the packet’s contents from on every byte. Additionally, using the the standard NMEA string format event forced us to pass the event data (www.geoaps.com/NMEA.htm) to across threads. This is because the seri- floating-point degrees. The map can be al port’s events are on a separate thread easily centered on the coordinates or a from the GUI. Because the PC software marker can be placed at this point. At initiates most communications with startup, the Google Maps user control the helicopter, it is essential to receive loads the Power Maps JavaScript. If an the helicopter’s acknowledge packet to Internet connection is present, the verify that the desired data has gone Google Maps interface will load and a out. For this reason, each time a packet map will be shown. Each JavaScript is sent, a timer is started. If the timer function in Power Map is called by the expires before the expected response is method HtmlDocument.InvokeScript received, a timeout event is sent to the method.[2] GUI. The indicators library is used to show IMPROVEMENTS the user telemetry data from the helicop- If you have the time and money, we ter. It is highly customizable: we use it would recommend adding error (parity to create the indicators from a real air- and redundancy) checking to the com- craft control panel (i.e., a compass, an munications protocol. We were limited artificial horizon, and indicator lights). on time, so we skipped this aspect of All user controls are scalable in size, the project because our radio modules enabling them to be resized on a form had error checking built in. Adding

40 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2802017philippsen.qxp 2/5/2008 3:44 PM Page 41

error checking to the communications College. He discovered his new REFERENCES protocol would enable the protocol to favorite programming language while [1] G. Schmidt, “Don’t Flicker! Dou- be used on any radio module. Users of working for two co-op terms as a C# ble Buffer!,” The Code Project, the communications system would not developer. Scott has also worked on 2007, www.codeproject.com/ have to worry about finding a radio many other hobby software projects. csharp/DoubleBuffering.asp. module with error checking built in. Updated versions of some of the proj- They would be able to find any radio ect software are available on his web [2] Microsoft Developer Network, module and plug it in. site (www.red79.net/Projects.html). “HtmlDocument.InvokeScript Another important improvement Method (String),” http://msdn2. would be to modify the protocol to Carl Philippsen (carlphilippsen@hotmail. microsoft.com/en-us/library/ allow for multiple slave devices, com) is a graduate of the Electronics be9zzz62(VS.80).aspx. enabling the multiple helicopter sce- Technician Common Core program at nario described in the introduction. North Island College and the Elec- RESOURCE This would require changing the pro- tronics Engineering Technology pro- R. Scammell, Power Map, http://hob tocol packets and firmware to include gram at Camosun College. He is biton.thisside.net/advmap.html. an address byte (or bytes). interested in a career in biomedical The Google Maps control is coded engineering and plans to further his SOURCES specifically for our helicopter education at the University of Victoria. ER900 TRS 900-MHz Transceiver project, so another recommended modules improvement would be to make the Kyle Wong ([email protected]) Low Power Radio Solutions Google Maps control more general-pur- worked as an electronics technologist www.lprs.co.uk pose and extend its functionality. There for several years. He plans to attend the dsPIC30F3011 Microcontroller are several functions written in the University of Victoria and enroll in the Microchip Technology, Inc. JavaScript that are not yet implemented Electronics Engineering degree program. www.microchip.com in the .NET control. One example is importing way points from an XML PROJECT FILES Visual Studio 2005 IDE file. To download code, go to ftp://ftp.circuit Microsoft Corp. We also have some recommendations cellar.com/pub/Circuit_Cellar/2008/212. www.microsoft.com to improve the indicators class. Cur- rently, it is made to simulate an aircraft control panel. It would be beneficial to make it more general-purpose as far as how it looks. Also, adding more con- trols, such as thermometers, seven-seg- ment displays, or redline range events, would add to the functionality. I

Michael Ghazi’s ([email protected]) six years as a naval communicator in the Canadian Forces prompted him to undertake the task of designing the RF system for the helicopter. After completing his studies at Camosun College, he will be relocating to the greater Toronto area to find work in his field.

Stefan Kaban’s ([email protected]) interest in helicopters was piqued during a co-op job with the B.C. Min- istry of Forests, where he was regular- ly exposed to helicopter operations. He plans to complete his degree in Electrical Engineering at the Universi- ty of Victoria.

Scott Morken ([email protected]) is a graduate of the Computer Engineering Technology program at Camosun

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 41 73.qxp 12/4/2007 11:49 AM Page 1

CC_RCM4300_Jan_FP_08019.indd 1 11/29/07 4:04:43 PM 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 43

FEATURE ARTICLE by Chris Coulston Do-It-Yourself Motion-Controlled Gaming (Part 1) Get Started With a Simple Application

The Nintendo Wii gaming system features a motion-sensing remote that translates hand movements and gestures into actual moves in its games. In this series of articles, Chris describes how you can build your own motion-sensing controller that can interact with a variety of graphics programs running on a PC.

One of the joys of teaching an mation provided by the accelerometer used as a pointer device. embedded systems class is exploring enables the user to interact with con- The goal was to have students in new technologies and sharing the dis- sole games using physical gestures my class assemble their own DIY Wii coveries with students. To give my like punching in a boxing game or controller and build an embedded students a chance to apply what they rolling a bowling ball in a bowling application and PC applications. This have learned, they choose their own game. The sensor bar’s pair of IR LEDs would enable them to interact with final projects. Last year, one final proj- are detected by the controller’s optical graphics programs running on a PC ect team used a Microchip Technology sensor, enabling the controller to be using gestures in the same way that PIC18F452 to read acceleration gamers use the Wii controller data from an Analog Devices to interact with games run- ADXL220 and send it to a PC. ning on the Wii console. They created an OpenGL application on the PC to use REQUIREMENTS the ADXL values to change While the eventual goal of the tilt of a rendered 3-D maze the project was to have stu- containing a ball. The user dents build a device that could guided the ball through the communicate acceleration maze towards a goal. The stu- information to a PC, it also dents voted this the top project needed to be flexible enough of the year. Not one to shut to realize a variety of standard the door on opportunity, I embedded systems projects. wondered how I could incorpo- These projects would need to rate the project into class demonstrate concepts such as assignments. Not long after PWM, frequency modulation, that, Nintendo came out with parallel and serial communica- the Wii, a gaming system tion, and switch debouncing, based around a motion-sensing to name a few. Given the controller. Hence, the “Do-It- diverse backgrounds of the Yourself Wii” was born. students, the system needed to The Nintendo Wii consists be easy to assemble, the con- of a console that is plugged struction of the device could into a TV, a controller, and a not require any sophisticated sensor bar. The user controls techniques, the system had to the on-screen action with a be relatively inexpensive, the controller containing a variety software development tools of buttons, a three-axis had to be inexpensive so stu- accelerometer, and an optical Photo 1—This is the completed DIY Wii. Don’t let those tiny SMT devices dents could purchase them sensor. The acceleration infor- intimidate you. All of my 30 students got their boards to work. and work on their home PCs,

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 43 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 44

and finally the system had to be self- free student edition of its C compiler. enable the delivery of standard embed- contained (not requiring special power AAA batteries and some onboard boost ded systems labs (see Figure 1). supplies or other non-essential support converters were a perfect match for the The center piece of the board is an hardware). The device that was creat- DIY Wii’s diminutive power require- Analog Devices ADXL330. Because of ed to meet the requirements is shown ments. Before discussing its capabili- investigations by the folks at Spark- in Photo 1. ties, let’s take a brief look at the hard- Fun Electronics, I know that this is As you can see, the board comes ware that makes up the DIY Wii and the same accelerometer used in the equipped with lots of I/O devices to the motivation for these choices. Wii controller. My excitement about demonstrate embedded concepts. A com- using this part was tempered by the bination of good silk screening on the HARDWARE DESIGN knowledge that it came housed in a PCB, detailed construction instructions, During the previous year in my difficult-to-solder 16-LFCSP package. and a novel soldering technique resulted embedded systems class, we used the The bypass capacitors on the in a system that was straightforward to PIC18F452, which in the interim year ADXL330’s outputs were selected to assemble. The system was reasonably had evolved into the PIC18F4520. A give the device a bandwidth of 50 Hz, inexpensive. The unit cost of the parts quick check of the technical docu- fast enough for most human move- and PCB was $43. To keep costs down, I ments revealed some small differences ments. At the outset of this project, I jettisoned the optical sensor, foregoing in the CCP subsystem; otherwise, the knew that Microchip’s ICD2 module the ability to use the DIY Wii as a point- parts were nearly identical. Thus, was capable of programming the part, er. Students who wanted to work at using the PIC18F4520 meant that I but at $160, it was not an option the home had to purchase their own $35 could keep a large portion of my lec- students would be able to afford. At PICkit 2, a USB device that programs the ture notes unchanged—that made the $35, I thought the PICkit 2 would be a microcontroller through a six-pin header. microcontroller choice obvious. The rest great programmer, but I was not cer- Software development took place in of the DIY Wii is built around the micro- tain how it would perform in a pun- Microchip’s free MPLab IDE using the controller to support its operation and ishing laboratory environment because

Figure 1—The schematic for the DIY Wii seems very busy, but those small SMT devices mean that the design has a small overall footprint.

44 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 45

I had never used one. Instead of risk- forces up to ±3 G. It is available only in Z ing the entire project on this choice, I a 16-“pin” leadless chip carrier. Figure 2 Y put redundant programming headers shows the ADXL330 superimposed on on the board—an RJ-45 jack for the top of its three acceleration-sensing ICD2 and a six-pin header for the axes. The white dot indicates the posi- PICkit 2. As it turns out, the inexpen- tion of pin 1 on the physical package. X sive PICkit 2 worked great and I never The acceleration along each of the installed the RJ-45 jack for the ICD2. I sensing axes is converted into a volt- wanted to put a Panasonic edge drive age proportional to the acceleration. rotary encoder on the board, but at When the part is accelerated along an Figure 2—This is the ADXL330 with its axes of accel- $10, I decided that the $1 ITT Indus- axis, the associated output voltage eration sensitivity. tries four-way tactile switch with will increase. The output is ratiomet- select would give the students enough ric to the input acceleration and control over user input. Looking at depends on the supply voltage. With a avoided SMD parts because you Photo 1, you can make out the empty supply voltage of 3.3 V, the 0-G output believe that you lack soldering skills, space reserved for the Panasonic is 1.7 V and each axis has a sensitivity you don’t know how to (or don’t want EVQWK edge drive jog encoders. of 330 mV/G. Thus, the ADXL shown to) build a custom PCB, or you are put

2N3904s were used to isolate the in Figure 2 would have outputs of VX = off by the cost of expensive adapters

microcontroller from the high current 1.7V, VY = 1.7V, and VZ = 2.03V. for breadboards. Unfortunately, more requirements of the white LED and There is only one configuration detail and more cool devices, such as the piezo speaker. An optional output that must be addressed when incorpo- ADXL330, are available only in sur- driver was left open for future expan- rating the ADXL330 into a design: the face-mount packaging. I figured that if sion. The Lumex LCM-S01602DTR/M selection of the bypass capacitors. The we were going to get our toes wet, LCD is an exceptional value for the bypass capacitors determine the trade- then we might as well jump in the money and it’s very durable. The SMT off between bandwidth and noise. The deep end and go with surface-mount 10-kΩ potentiometer was a disappoint- bandwidth determines the highest fre- packaging whenever possible. ment; it proved to be easy to damage quency accelerations that can be report- With the decision made to go with mechanically and thermally. It would ed by the device. Clearly, having high surface-mount packaging, I now faced have been a far better idea to fix the con- bandwidth would be desirable. You the prospect of students without sol- trast of the LCD by putting a 100-Ω could let the unused bandwidth go to dering experience assembling the DIY

resistor between the VO input on the waste. However, bandwidth is “pur- Wii. There are two general ways to

LCD and VCC. Two separate power sup- chased” at the expense of noise. Noise solder parts to a PCB: hand soldering plies were installed because the LCD manifests itself in spurious variations at and reflow soldering. Hand soldering required 5 V and the ADXL330 required the voltage outputs. The ADXL330 is very versatile. With a good soldering 2 to 3.6 V. The MCP1252 was a great part technical documentation explains that iron, the right solder, and a bunch of and it performed well. The 3.3-V boost “the ADXL330 noise has the character- solder wick, virtually any surface- converter could have been eliminated by istics of white Gaussian noise, which mount device (SMD) can successfully noting that the anode of the green power- contributes equally at all frequencies be attached to a PCB. One technique on-indication LED sits at 5 V and its for- and is described in terms of µg/√Hz...” is to melt a little solder on one of the ward-bias voltage drop is 2.1 V. Hence, Thus, it makes sense to ask questions PCB pads and let it cool. Next, align the LED’s cathode sits at 2.9 V, which is about the probability of the noise the device on its PCB pads, hold it good enough for the ADXL330. Further- exceeding some threshold. Clearly, low down, and heat up the pin over the more, the ADXL is an electron miser, noise would be desirable because soldered pad. This will cause the sol- consuming a scant 320 μA of current, everyone likes precise measurements. der under the pin to melt. After the hardly enough to affect the brightness of Unfortunately, the device does not soldering iron is removed and the sol- the LED. A standard MAX232-level con- enable you to have both high band- der is allowed to cool, your part will verter and a female DB9 connector were width and low noise. Hence, you need be tacked down to the PCB. You can used to communicate between the PC to determine the minimum bandwidth solder the remaining pins with aban- and the DIY Wii. My only real mistake in your application and the maximum don. This will undoubtedly create sol- in the PCB design was reversing the TX tolerable noise. In the case of the DIY der bridges, chunks of solder spanning and RX lines between the DB9 and the Wii, we were primarily focused on consecutive pins. Don’t worry about level converter. This mistake provided measuring human movement. For this this. You can clean the bridges up me with the opportunity of introduc- reason, we chose a conservative 50-Hz with your solder braid, making a top- ing my students to “green wire” fixes. bandwidth and tolerated the resulting notch connection. Unfortunately, the noise. success of hand soldering depends ADXL330 heavily on the skill and patience of The ADXL330 is a three-axis SMD SOLDERING the user. accelerometer capable of measuring If you are like me, then you have The other soldering process, reflow

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 45 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 46

a) b) c)

Photo 2a—Here is a pasty PCB waiting to be cooked on the reflow skillet. b—Five minutes into the process, the paste looks baked dry. c—Eight minutes into the process, the pads are looking shiny. This is reflow!

soldering, uses a viscous form of solder reflow skillet. solder paste to all of the SMT pads on called solder paste. Reflow soldering The reflow skillet is nothing more the DIY Wii PCB and populated the has the advantage of requiring little than an electric griddle commonly board by gently laying the parts onto skill beyond putting a dab of paste on used to cook on. I bought a Rival the pasty pads. My nerves were on edge the PCB pads and dropping parts onto removable plate griddle for $30 from when I popped my first pasty PCB onto the pasty pads. This assembly is then my local big-box store. It has a 10″ × the reflow skillet and cranked the tem- “cooked,” turning the solder paste 20″ cooking area (large enough for perature knob all the way to 400°. into solder. The cooking proceeds even the largest PCBs) and an easy-to- Photo 2a shows a PCB (not the DIY according to a thermal profile that can access temperature knob. I don’t need Wii) at the start of the reflow process. be broken down into four phases: pre- to tell you that once you use the grid- If you look carefully, you can see that heating, soaking, reflow, and cooling.[1] dle to reflow a PCB with its associated the solder paste is still a little bumpy. During preheating, the assembly is heavy metals, it should never again be After 3 minutes, the PCB was start- gradually brought up to a temperature used to cook food, right? ing to warm nicely and the solder paste below the melting point of the solder. at this point was evened out across the During the soaking phase, the assem- PERFORMANCE pads as if the heat were somehow melt- bly is held at a constant temperature The biggest question before using ing it. After 5 minutes, the solder paste below the melting point of the solder the reflow skillet was whether it was dried to a baked consistency (see to ensure that all of the parts are at a would really work. I also wondered Photo 2b). At about the same time, lit- uniform temperature. The tempera- about how the skillet’s thermal profile tle whiffs of smoke started curling out ture is rapidly increased during the would compare to the recommended from under the PCB. While this initial- reflow phase, causing the now dry sol- profile for the solder paste. The ly freaked me out, I have since come to der paste to liquefy, attaching the parts answer to the first question could only the conclusion that this is normal and to the PCB. During the cooling phase, be answered by reflowing a DIY Wii does not damage the bottom-side solder the assembly is allowed to gradually board. The answer to the second ques- mask. cool to avoid thermal stress on the tion required a trip to my local tool After about 8 minutes, some of the parts. The temperatures and times for store for an infrared thermometer solder paste in the hotter regions or each of the zones characterize a ther- with a laser sight. areas with little thermal mass started to mal profile. The technical documents With everything at hand, I applied reflow. It took 10 minutes for the solder for a popular solder paste like Kester’s R276 suggest a thermal profile. If you are planning on building a million cell 550 phones, you will need a reliable high- 500 450 yield process that will justify the Skillet #1 400 expense of a sophisticated reflow oven. Skillet #2 350 However, a careful look at the Kester R7 technical documents reveals a caveat. 300 A+ “The profile shown is simply a start- 250

Temperature (F) Jack ing point recommendation. A wide 200 variety of profiles would work effec- 150 Kester tively with R276 paste.” The folks at 100 SparkFun Electronics took the chal- 50 lenge to see just how tolerant solder 0 5 10 15 Time (minutes) paste is to changes in its profile. They came up with a low-cost, effective, Figure 3—Here is the reflow profile suggested by the Kester documentation. The profile is generated by the Rival and innovative technique called the removable plate griddle at a variety of points on the skillet and PCB.

46 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 47.qxp 2/1/2008 11:51 AM Page 1 63.qxp 12/4/2007 10:30 AM Page 1

PC Oscilloscopes & Analyzers

DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

4 Channel BitScope 2 Channel BitScope Pocket Analyzer

Digital Storage Oscilloscope BitScope DSO Software for Windows and Linux Up to 4 analog channels using industry standard  probes or POD connected analog inputs. BitScope DSO is fast and intuitive multi-channel test and measurement software for your PC or notebook. Whether it's a digital scope, spectrum analyzer, mixed signal scope, Mixed Signal Oscilloscope logic analyzer, waveform generator or data recorder, BitScope DSO supports them all. Capture and display up to 4 analog and 8 logic Capture deep buffer one-shots or display waveforms live just like an analog scope.  channels with sophisticated cross-triggers. Comprehensive test instrument integration means you can view the same data in different ways simultaneously at the click of a button. Spectrum Analyzer DSO may even be used stand-alone to share data with colleagues, students or Integrated real-time spectrum analyzer for each customers. Waveforms may be exported as portable image files or live captures replayed  analog channel with concurrent waveform display. on other PCs as if a BitScope was locally connected. BitScope DSO supports all current BitScope models, auto-configures when it connects Logic Analyzer and can manage multiple BitScopes concurrently. No manual setup is normally required. 8 logic, External Trigger and special purpose Data export is available for use with third party software tools and BitScope's networked  inputs to capture digital signals down to 25nS. data acquisition capabilities are fully supported.

Data Recorder Record anything DSO can capture. Supports  live data replay and display export.

Networking Flexible network connectivity supporting  multi-scope operation, remote monitoring and data acquisition. Data Export Export data with DSO using portable CSV files or www.bitscope.com  use libraries to build custom BitScope solutions. 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 49

with the reflow skillet: its profile is 140 nowhere near as steep as what is rec- ommended by Kester and the maxi- 120 mum temperature is not as high as the ° 100 recommended 550 F. The slope of the Sample profile could be increased by preheat- 80 ° Thres+ ing the skillet to around 200 F, putting the PCB on the skillet, and then crank-

Force Thres - 60 ing up the skillet temperature to Strike 400°F. The lack of a peak temperature 40 might be addressed by some “adjust- ments” to the skillet’s thermostat. 20 Despite these shortcomings, the solder

0 paste and SMT components have 0 0.2 0.4 0.6 0.8 proved to be up to the task. In practice, Time (s) the reflow skillet has produced consis- tently excellent results for all of my Figure 4—The sample curve shows the force data from the ADXL330 when worn on a runner’s hip. students. My hats off to the folks at SparkFun Electronics for thinking out- under the big electrolytic capacitors to from five locations: two locations from side of the box and coming up with reflow and even then I had to go back the surface of the skillet, from the solder this simple and low-cost technique. and touch up two of them with an pad of a 1206 resistor, from the solder Aoyue Tongyi Electronic Equipment pad of a brown capacitor, and from the THE PEDO-SPEEDO 850A++ hot air rework tool. At 10 min- solder pad of the audio jack. The data, To demonstrate the capabilities of utes, I shut the skillet off and waited plotted in Figure 3, is compared against the DIY Wii, let’s examine one of the for the PCB to cool (see Photo 2c). the recommended profile taken from final projects from my embedded sys- While processing the PCB in the photo the Kester R276 technical documents. tems class, the pedo-speedo. The goal sequence, temperature data was gathered There are two shortcomings associated of the pedo-speedo was to use the

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 49 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 50

time-varying acceleration data the sampled data, you would 7 from a DIY Wii mounted on a normally write an algorithm, 6 runner’s hip to infer his speed which looked for a change in and distance. The starting point 5 slope of the force data. Clearly, for this project was to configure 4 Stride (m) this will not work with the 3 Speed (m/s)

the DIY Wii as a data logger to Stride (m) data in Figure 4. The data con- collect data over a fixed-length 2 tains local minima and maxi-

course to determine the rela- 1 ma. The solution to this prob-

tionship between a runner’s 0 lem was to employ hysteresis. cadence and his speed. Getting 0.3 0.4 0.5 0.6 When the sample is greater the Microchip Technology Period (s) than an upper threshold, strike MCC18 compiler to free up sev- goes high. When the sample is eral blocks of its 1.5 KB of RAM Figure 5—Here is the relationship between a runner’s cadence and his stride less than a lower threshold, length. proved to be unexpectedly diffi- strike goes low. Otherwise, cult. The solution involved edit- strike retains its value. From ing the linker file and telling the com- runner’s hip over two footfalls. Each the data in Figure 4, the upper thresh- piler to alias several contiguous blocks footfall event is punctuated by two old should be set to 100 and the lower of RAM with a variable name, which peaks, one generated by the heel strike threshold should be set to 40. However, is referenced from within your C and the other by the toe launch.[2] The when the pace of the runner changes, source file (see Listing 1). change in amplitude between the two so do acceptable values for thresholds. With 640 bytes of RAM, there were footfall events reflects the fact that the The solution was to constantly look for about 13 s of logging capability. The DIY Wii was mounted asymmetrically the minima and maxima of the sam- logged data was then downloaded and over one hip. The period of the foot- ples and set the upper and lower analyzed in Excel. An example of the falls was extracted from the sample thresholds 25% over the minima and ADC samples from the ADXL (along data by converting it into a binary sig- 25% below the maxima. The minima with a lot of other information) is plot- nal, the “strike” curve in Figure 4, and maxima were maintained using a ted in Figure 4. The “sample” curve in which represented if the force was leaky capacitor model. In this model, Figure 4 represents the force at the high or low. To extract the signal from the current maxima are compared to the

50 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803018_Coulston.qxp 2/5/2008 3:46 PM Page 51

size of microcontrollers to Listing 1—To get the MCC18 compiler to recognize an array larger than 256 bytes, you have to modify the linker file (top) and use #pragma directives in your source file (bottom). build your own video games. I //------Modified 18f4520.lkr file ------// ACCESSBANK NAME=accessram START=0x0 END=0x7F Chris Coulston has a PhD in DATABANK NAME=gpr0 START=0x80 END=0xFF Computer Science and Engi- DATABANK NAME=gpr1 START=0x100 END=0x13F neering from Penn State DATABANK NAME=big START=0x140 END=0x47F PROTECTED DATABANK NAME=gpr4 START=0x480 END=0x4FF University. He is an associ- DATABANK NAME=gpr5 START=0x500 END=0x5FF ate professor and program ACCESSBANK NAME=accesssfr START=0xF80 END=0xFFF PROTECTED chair of Electrical, Comput- SECTION NAME=xaxis_scn RAM=big er, and Software Engineering STACK SIZE=0x100 RAM=gpr5 at Penn State, Erie. Chris //------Directive in C file ------// also runs ATAN consulting, #pragma udata xaxis_scn an electronics development static char xaxis_buffer[0x340]; and manufacturing firm that #pragma udata provides instrumentation solutions for local industry. current sample. If the sample is larger and thresh– exceeded some threshold. In his spare time, he likes to than the maxima, the maxima is This way, the pedo-speedo does not ride his bicycle around Erie county and assigned the value of the sample. Oth- measure the time you are standing race on the weekends. You can e-mail erwise, the maxima is decreased by a around getting the mail out of the Chris at [email protected]. fixed amount. This way, the maxima mailbox. A nice final touch was “discharges” down from its peak val- enabling the speaker to buzz when the PROJECT FILES ues and is able to quickly conform to strike signal was low. This gives the To download code, go to ftp://ftp.circuit any decrease in the amplitude of the user some auditory feedback in time cellar.com/pub/Circuit_Cellar/2008/212. runner. The thres+/thresh– curves in with his cadence and assures the user Figure 4 are set to 75%/25% of the that the unit is functioning properly. REFERENCES difference between maxima and mini- I’ve used the pedo-speedo on a cou- [1] R. Lacoste, “Easy Reflow: Build an ma. The strike signal goes high when ple of training runs and I am surprised SMT Reflow Oven Controller,” Circuit sample is greater than thres+. The at its accuracy. I often make sponta- Cellar 168, 2004. strike signal goes low when sample is neous decisions about which way to less than thres–. Otherwise, the strike go during my runs, making it difficult [2] J. Scarlett, “Enhancing the Perfor- remains unchanged. to determine the distance of a run. mance of Pedometers Using a Single All of the analysis in Figure 4 was However, this is not a problem when I Accelerometer,” Analog Devices, Inc., performed to determine how the peri- have the pedo-speedo with me. www.analog.com/library/analogDia od of the footfalls related to the speed logue/archives/41-03/pedometer.html. and stride length of a runner. A bunch MASTER SMDs of trials and a little massaging of the I hope that this article has made you RESOURCE data produced Figure 5. confident enough to use surface-mount SparkFun Electronics, www.sparkfun.com. The nonlinear relationship between devices in your next project. With a few the variables in Figure 5 means that it tools and a willingness to try, I am sure SOURCES makes sense to have the pedometer that you can pick up the necessary skills ADXL330 application use a look-up table. This to master SMDs. Learning these skills Analog Devices, Inc. is accomplished by comparing the will turn out to be a wise investment www.analog.com incoming period against the periods of because sooner or later you will run the data points in Figure 5. The inter- across a device like the ADXL330, which R276 No-clean solder paste polated value is formed from the clos- comes only in a surface-mount pack- Kester, Inc. est pair of periods. To further increase age. After your first project using SMDs, www.kester.com the efficiency of the computations, I am sure that you will find that their LCM-S01602DTR/M LCD the decimal numbers were stored space savings enables you to pack a big Lumex, Inc. using a fixed-point representation. punch in your tiny embedded project. www.lumex.com The finishing touches on the pedo- In the next installment, I will show speedo were to have the LCD show you how to take the acceleration val- MCC18 Compiler, MCP1252 DC-to- the instantaneous speed, distance cov- ues from the DIY Wii, send them to DC converter, PICkit 2 development ered, run time, and number of foot- your PC, and use this information to programmer/debugger, and falls. The actual run time was main- manipulate 3-D graphics. Hopefully, PIC18F4520 microcontroller tained by enabling the run-time clock you will learn how to leverage the Microchip Technology, Inc. when the difference between thresh+ power of your PC and the diminutive www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 51 2803015_dalrymple.qxp 2/7/2008 9:48 AM Page 52

FEATURE ARTICLE by Monte Dalrymple Robotics Made Easy A Peripheral Chip for Low-Level Functions

Robotics and motion control applications typically require specialized hardware and software. Monte introduces a simple peripheral chip that can take care of all of the low-level functions.

In these days of chips with almost is completely asynchronous, but channel I/O are used for part of the unlimited transistor budgets, it is hard because all of the internal logic is syn- data bus. This is why using the device to find a new peripheral chip to use chronous, there is a cycle-time restric- with a serial bus interface makes the when the main CPU doesn’t have tion on the bus. A Wait output is most sense. exactly the right mix of I/O. This is automatically generated by the device Five different options are available because it’s hard for chip architects to to enforce the cycle-time restriction so for the serial bus interface. Either sep- come up with a balance of functionality no extra external logic is required. arate serial input data and serial out- (transistors) versus pin count that Each of the eight channels is indi- put data can be selected or a bidirec- makes sense. vidually addressed, but the registers tional serial I/O bus can be used. With As a result, system designers often within a channel are accessed indirect- each of these options, the data can be end up having to add either an FPGA ly, using a two-step process that first sent either MSB first or LSB first. The or a small microcontroller to perform writes the register address, followed clock polarity is not programmable specialized I/O tasks. While this isn’t by a read or write of the data. Global though; output data always changes a big deal as far as the hardware is registers are accessed directly. on the falling edge of the clock and concerned, it adds another layer of Using the parallel bus interface is input data is always sampled on the software complexity. not without its drawbacks, because six rising edge of the clock. The Rabbit Semiconductor I/O (RIO) pins that are normally available for As in the case of the parallel bus, device was designed specifically with these facts in mind. In this article, I’ll Parallel interface Parallel function Serial interface Serial function describe the features of this new SER/*PAR Low (select parallel) SER/*PAR High (select serial) peripheral chip that should take care of *IOCS Chip select *IOCS Chip select everything you might need for a robot- *IORD Read strobe GPIN[4] General-purpose In ics or motion-control application. Then *IOWR Write strobe GPIN[3] General-purpose In I’ll give some examples of how to use A[2] Channel select 2 GPIN[2] General-purpose In the device for everything from driving A[1] Channel select 1 GPIN[1] General-purpose In motors to sensing position. A[0] Channel select 0 MSB/*LSB MSB First/LSB First G/*C Global/Channel select S/*RN Serial/RabbitNet TALKING TO THE CPU *P/I Pointer/Indirect BIDI/*NORM 1-Wire/2-wire Data This device consists of eight identical *WAIT Wait request SERO Serial data out channels in a small (10 mm × 10 mm) D[7] Data Bus 7 SERCLK Serial clock 64-pin package. To make the RIO as D[6] Data Bus 6 SERIO Serial data in/out general-purpose as possible, there are D[5] Data Bus 5 Ch6Port[3] Channel 6 I/O six different options for connecting D[4] Data Bus 4 Ch6Port[2] Channel 6 I/O the device to a CPU. The signals for D[3] Data Bus 3 Ch6Port[1] Channel 6 I/O the different bus interface options are D[2] Data Bus 2 Ch7Port[3] Channel 7 I/O shown in Table 1. D[1] Data Bus 1 Ch7Port[2] Channel 7 I/O A traditional parallel interface is D[0] Data Bus 0 Ch7Port[1] Channel 7 I/O available with the usual Chip Select, *INT Interrupt request *INT Interrupt request Read Strobe, Write Strobe, Address Table 1—The RIO can be used with either a parallel bus interface or a serial bus interface. The parallel bus Bus, and 8-bit Data Bus. The interface requires six of the 32 available channel I/Os.

52 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803015_dalrymple.qxp 2/7/2008 9:48 AM Page 53

Match 0 the operation of each channel. counter or latching the current count Match 1 Figure 1 shows a basic block when it is free-running. Of course the Match 2 diagram of a channel. current count and both of the latched Match 3 Inc Although the hardware of counts can be read by the CPU. Count latch (begin) (begin) Count latch (end) the counter is 16 bits wide, the In addition to the increment and Dec Status 0 (end) actual count limit can be set to decrement signals, each channel also 16-bit Counter Status 1 any value and the counter has a sync signal, which is used to Status 2 Limit wraps around while counting reset the counter to all zeros. Like the Sync Status 3 in either direction. This is very increment and decrement signals, the useful when you need some- sync signal has a range of options avail- I/O 0 I/O 1 I/O 2 I/O 3 thing that counts by other than able and is very useful for synchroniz- Figure 1—All eight identical channels are built around a 16-bit a power of two. I’ll talk about ing counters in different channels or up/down counter and four I/O pins. one example when I get to the synchronizing the counter to an exter- Position Sensing section. nal event. Note that the sync signal can first the address and transfer direction Four sets of compare logic and four be forced under CPU control. information is written to the device 16-bit match registers are connected That’s the basic functionality of and then the data is transferred in a to the counter. Each comparator sig- each channel. Now let’s look at how second serial operation. The serial bus nals a match when the count is identi- to put the RIO to work in motion con- is still reasonably high-performance, cal to the value in the match register. trol and robotics applications. because the maximum serial clock Each match signal can generate an rate is the system clock divided by interrupt and be used to set or reset MOTORS AND H-BRIDGES four and the system clock frequency any of the four channel status bits. The most common way to power a can be as high as 40 MHz. Each of the four channel status bits DC motor that needs to run in either The final bus interface option uses can be output on an I/O pin. The sta- direction is with an H-bridge. An the serial RabbitNet protocol, which tus bits can be set or reset by a count- example of an H-bridge using MOS- is a link layer protocol for connecting er rollover, in either direction, or by a FET transistors is shown in Figure 2. a processor to distributed slave devices sync signal (more on that later). This Other types of drivers are also possi- that is proprietary to Rabbit Semicon- enables the creation of PWM or pulse ble, ranging from bipolar transistors to ductor. I won’t go over the details position modulation (PPM) signals. A relays. But it’s the circuit topology here, but you can think of RabbitNet status bit can also be ANDed with one that’s important for this discussion, as an inexpensive alternative to USB. of the least significant bits of the not the exact characteristics of the The serial interface options do not use counter to create a pulse train that can drivers used. The four signals needed nearly as many pins as the parallel bus be output on an I/O pin. for an H-bridge are the main reason option, so there are a number of pins left While the status bits are the pri- that there are four I/O pins per chan- over. Four of the unused pins serve as mary outputs for the I/O pins, the I/O nel in the device. general-purpose inputs in this case. pins can also be used as simple out- To drive the motor in one direction, The dedicated Interrupt Request pin puts, sequenced outputs, simple circuit legs A and D are enabled, pro- is independent of the bus interface. To inputs, or counter inputs. Each I/O pin viding a power-to-ground path in one make the device as general-purpose as is individually programmed. The direction through the motor. For possible, there is no provision for an sequenced output option enables rudi- motor rotation in the opposite direc- interrupt acknowledge signal. Instead, mentary waveform creation by step- tion, circuit legs B and C are enabled, interrupts are removed by clearing the ping through one of four programmed providing current flow in the opposite status bits that signal the type of values on each counter rollover. direction through the motor. interrupt that is pending. Determining The counter obviously needs incre- The motor will run at full speed what kind of interrupt is pending is ment and decrement signals. There are while the current is continuous. PWM straightforward. A global register has a number of options available for each. is normally used to vary the speed, if an interrupt pending status bit for The increment and decrement signals required. This works because the each channel and a register within can come from any channel I/O pin each channel indicates exactly what and can be either level- or edge-trig- type of interrupt is pending. gered. There is a special quadrature

decoding option for increment/decre- A C CHANNEL HARDWARE ment and these signals can also be Each of the eight channels in the forced under program control. B D device is built around a 16-bit The counter can be used for timer up/down counter and four I/O pins. applications in a variety of modes. In While this might not sound like much this case, the increment and decre- Figure 2—Driving a motor in both directions is usually hardware per channel, about 25 8-bit ment signals function as begin and end done with an H-bridge. But don’t ever turn on both driv- control registers are required to control signals, either starting and stopping the ers on the same side.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 53 2803015_dalrymple.qxp 2/7/2008 9:48 AM Page 54

The phase relationship between two Raw A quadrature signals provides direction information, while the frequency of Raw B the signals provides rotational velocity

Sample information. When a separate index pulse is available, counting the edges A Output on the quadrature signals enables absolute position to be determined. B Output Quadrature encoders are available as off-the-shelf components with a vari- Figure 3—The pin-pair protection guarantees that both drivers on the same side of an H-bridge will never be on at ety of resolutions. The most common the same time. It also guarantees a dead time between changing the motor direction. encoders have either 500 or 512 quad- rature cycles per revolution. This is motor inherently acts like a low-pass on that pair of pins. The circuitry that where the programmable count limit filter for the pulse-width-modulated does this is actually the last bit of of the channel counter helps, because current. logic before the pad cells for the pair it allows any quadrature cycle count to There are two issues with an H- of I/O pins. If the channel somehow be supported. The count limit should bridge that complicate its use. The tries to output this illegal value, the be set to four times the cycle count, first should be obvious from the cir- pin-pair protection circuit substitutes minus one, because the counter incre- cuit topology. If circuit legs A and C the stored all-off value instead. ments or decrements on each valid (or B and D) are inadvertently active at There is more to the story because edge of one of the quadrature signals. the same time, no current goes the protection circuitry runs off of an As with the H-bridge, there are through the motor. Instead there is a independent timer that guarantees a some subtle issues involved in decod- direct power-to-ground short through dead time for the H-bridge drive sig- ing quadrature signals. The first is the the drivers, which will almost certain- nals. The timer is used solely for the handling of invalid transitions. As ly overheat and then destroy one or pin-pair protection. An example of shown in Figure 4, only one quadra- both of the drivers. how it works is shown in Figure 3. ture signal should change at a time. The second issue becomes a prob- The timer samples the channel out- Two signals switching at the same lem as a result of the first. Motors puts and transfers legal values to the I/O time is illegal. usually require a fair amount of cur- pins while substituting the all-off value The second issue has to do with rent and this means that the drivers for an illegal value. All of the features, how the signals are created. Because don’t turn on and off very quickly. So from the four I/O pins with independent they are most often the outputs of it isn’t enough to guarantee that both PWM signals to the pin-pair protec- photodiodes or other devices that drivers on one side of the H-bridge are tion circuitry, make driving a motor respond to light and that are being not on at the same time; they must with an H-bridge painless and safe. interrupted by a mechanical device, also have some non-overlap time. the signals often have less than ideal The RIO contains special circuitry POSITION SENSING switching characteristics. In fact, if that can be used to protect the user Trying to control any kind of the rotation of the encoder is stopped from inadvertently running afoul of motion without some type of feedback right where a transition is imminent, either of these issues. This function is about position or velocity is a recipe one output may oscillate. called pin-pair protection and is con- for disaster. One of the most common The RIO automatically takes care of trolled via a pair of global registers out- ways of sensing the position of any- these two issues. The logic ignores all side the normal channel register set. thing that rotates is with a pair of sig- illegal transitions by holding the state After a device reset, all of the chan- nals generated by a quadrature of the counter unless a valid transition nel I/O pins are inputs. If the four I/O encoder. Figure 4 shows the operation has been detected. In addition, the pins of a particular channel are con- of quadrature signals. quadrature inputs both contain digital nected to the H-bridge in Figure 2, the state of the four I/O pins will be the default all-off state because of the Inphase resistors. Enabling the pin-pair protec-

tion for the channel pins connected to Quadrature the left and right legs of the H-bridge samples this state and saves it for use Index by the pin-pair protection circuitry. From that point on, until the next Count inc inc inc inc inc inc inc inc inc dec dec dec dec dec device reset, the complement of the rst stored state (which would turn on both Figure 4—Rotational position and direction is sensed using quadrature signals. Tracking the absolute position drivers) is guaranteed never to be driven requires an index pulse.

54 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 55.qxp 1/28/2008 4:53 PM Page 1 More Effi Efficient cient 3-Phase Motor Control

USA and in other countries. All trademarks mentioned herein are property of their respective companies. Explore the New Motor Control Solutions from Microchip Are you considering moving to brushless motors, eliminating costly sensors or adding PFC? Let Microchip show you how to improve your efficiency, lower noise, reduce your form factor and explore cost reduction options. Visit www.microchip.com/DSCMOTOR and discover Microchip’s comprehensive motor control solutions, which feature 16- bit digital signal controllers, free software, development tool discounts, technical training and more!

Looking for? to... Microchip Has the Solution! ©2008, Microchip Technology Inc. All rights reserved. Microchip Technology ©2008, Add Power Factor Correction PWM with 2 Time Bases Energy Savings Incorporate Field-Oriented Control Free Software Noise Reduction Incorporate Sinusoidal Control Free Software Remove Expensive Sensors Free Software, 4 S&H ADC Integrate PFC and Motor Controller PWM with 2 Time Bases Cost Reduction Integrate Controller on Motor 6x6 mm Small Packages Easily Migrate to Other DSCs in Portfolio Optimized Feature Set Remove Crystal 1% Internal Oscillator Incorporate Field Oriented Control Free Software Better Torque Control Better Loop Response Multiple S&H ADC Improve Reliability Migrate from Brushed to Brushless Motors Free Software Noise Profile Diagnostics DSP Resource On-chip

Purchase Microchip’s motor control development solutions at... microchip DIRECT The Microchip name and logo, the Microchip logo and dsPIC are registered trademarks of Microchip Technology Incorporated in the the Microchip logo and dsPIC are registered trademarks of Microchip Technology The Microchip name and logo, www.microchipdirect.com www.microchip.com/DSCMOTOR

Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs

DSC Advanced Motor Contol Ad for1 1 1/11/2008 3:26:21 PM 2803015_dalrymple.qxp 2/7/2008 9:48 AM Page 56

used to input the echo detect signal. Status bit The input is programmed as the decre- ment signal to latch the count for Count bit 0 determining the round trip delay.

Count bit 1 THE LITTLE STUFF

Status & 0 There are a number of other bits and pieces that are common in robot- Status & 1 ics and motion control. The first is servos to move things. The most com- Figure 5—Driving an ultrasonic transducer directly requires a burst of pulses. This type of output can also be used mon servos use a PWM signal to con- to reduce the filtering requirements for a PWM signal used to create an analog value. trol movement. Typical timing for a servo is shown in Figure 6. filters that feed clean signals to the with the logical AND of a status bit The 20-ms frame rate of a servo cou- actual decoder. and one or more of the least significant pled with the 16-bit counter in a chan- Measuring the rotation of a shaft is bits of the counter. This feature is use- nel implies a maximum frequency into one thing, but what about sensing ful for creating a tone burst to drive an the counter of just over 3 MHz. Because position relative to the rest of the ultrasonic transducer (see Figure 5). the RIO is specified to operate at up to world? Contact sensors are easy, One channel can handle both the 40 MHz and the CPU bus interface because the state of the I/O pins can creation of the tone burst and meas- operates off of the clock input, this be read at any time. If you prefer an urement of the time to detect an echo. could be a problem. interrupt, just assign an I/O pin as the The sequence can be started under To handle this situation, there is a increment or decrement signal and program control by forcing a sync sig- global 8-bit prescaler for the clock that is select the appropriate edge or level to nal, which can set the status bit and fed to the channels. The prescaler decou- generate an interrupt. enable both counting and the burst of ples the bus speed from the channel Non-contact position sensing is sup- pulses. A second I/O pin can output and is individually enabled for ported by the Toggle Output mode. In the range gate signal, created from use by each channel so not all channels this mode, an I/O pin can be driven another status bit. A third I/O pin is have to be limited by the slow clock.

TrackBotTM

shown with optional SunSPOT (purchase separately)

TrackBot is an affordable, autonomous robot platform with a real-time P2P network of RISC chips which manage all transducers (including custom ones you can add). Any controller with a standard UART can be added as the high- level application brain. It's lead-free and RoHS-compliant. TrackBot was developed specifically for university-level education and research. It's so unique that multiple patents are pending.TrackBot is in stock and shipping now!

SYSTRONIX® 939 Edison Street, Salt Lake City, Utah, USA www.trackbot.systronix.com

56 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 57.qxp 1/29/2008 8:33 AM Page 1 58.qxp 2

Misc Ethernet I2C Scopes & Wfm Gens / PSA2701T $1990 etc. Built-inWi-Fi/Bluetooth/IR. unlimited storageforwfms,set-ups, single/peak-hold/avg sweeps - Spectrum Analyzer.Continuous/ Handheld PalmPC-based2.7GHz D66T$599 $325 PDS6062T PDS5022S Battery poweredoptional. cp ih78 colorLCD. 7.8” scope with st trigger Owon - eCOV-110-P $89 10/100mpbs RS-232 IP instant Provides an without aPCusingthis28”cable. Network yourserialproducteasily frequency counter. and BURST; 6digit200MHz wfms; FM, AM, PM,FSK,SWEEP RS-232, LAN/GPIB.10built-in 25/40MHz USB14-bit ARB w. USB DG2021A/DG2041A $995/$1495 USB I2C/IO$79 boards formoreI lines. Freesoftware. Usemultiple your PCto90kHzI “drop-in” solutionforconnecting Devasys - PoScope withprobes$199 gen. SPI/I2C/1-w/UART decoding. analyzer, 5-chsignalgen,8-chpattern 2-ch chartrecorder, 16-ch8MHzlogic 10-bit scope,2-chspectrumanalyzer, 6-in-1 USBscopeadapter!200kHz2-ch Serial-Ethernet Cable 1 EMC Spectrum Analyzer

Best Color LCDScope NEW! Seller RIGOL / 2008 10:51AMPage1 20/40MHz AWG 6 in1Scope USB toI2C otcompatible withmost port andalone USB Ethernet hubs. Provides asimple 25MHz 2 C/IO. 2 C +20I/O 2-ch + address. bench network speedsto8Mbps. W3100A microprocessor systems.Drop-in stack forhi-speedInternet- hardwired TCP/IP-I - NM7010A-LF REV2 DM3061 $795 Sensor, High/Low T Frequency, Period,Ratio, 2/4-wire R,C, 16-ch mux. Automeasure 6 1/2digit50KS/s,2MSmem.Opt. GS-10J$34 EG-SR-7150MJ Internet-enable anyserialpart. 230kbps serial.Ethernet/ - for 10/100Mbps Ethernet set-up Ethernet Gateway. Simple WIZnet - PS3423 automotivekit$2293 components &circuits. diagnostic tool.2&4ch. a into Picokit winning Automotive PS2203/4/5 from$318 /logging software, case,probes. screen updates.Inc.scope/FFT bandwidth andUSB2.0forfast scope rangewith5/10/25MHz 2-ch 40/100/200MS/s8-bit DS1102C $999 space. small footprintsavesbench Ultra Compact Designwith 2000 wfm/srefreshrate. 100MHz 2-ch400MS/sDSO NEW! Automotive Testing NEW! Ethernet toSerial

RIGOL Low-Cost Scope RIGOL Ethernet toI2C 100MHz DSO powerful vehicle-elec -based boardforinstant Ready-to-go DMM Diagnostics - Continuity, 2 C module.Offloads unyour PC s turn Limit Math. We search the world for unique, time-saving products - see our website for 100s more: volt/temp data loggers, wireless loggers, data volt/temp more: 100s for website our see - products time-saving unique, for world the search We boards, LCD display kits, Ethernet/IO, USB/RS232/485, USB-OTG, instant Ethernet-serial, CAN/LINbus, USB CAN/LINbus, Ethernet-serial, instant USB-OTG, USB/RS232/485, Ethernet/IO, kits, display LCD boards, cables/extenders, line testers, logic analyzers, color sensors, motion controllers, eng. software, wireless boards, SMD boards, wireless software, eng. controllers, motion sensors, color analyzers, logic testers, line cables/extenders, Don't forget to ask for your FREE Starbucks card with order! Check www.saelig.com often for special offers and bargains. bargains. and offers special for often www.saelig.com Check order! with card Starbucks FREE your for ask to forget Don't adapters, I2C adapters, FPGA kits, GPS loggers, automotive testing, security dongles, video motion detectors, motion video dongles, security testing, automotive loggers, GPS kits, FPGA adapters, I2C adapters, crystals/oscillators, custom switches, barcode scanners, robots, DSP filters, PLCs, Remote MP3 players. etc. etc. players. MP3 Remote PLCs, filters, DSP robots, scanners, barcode switches, custom crystals/oscillators, versions for Complete, enabling seria DC/AC, Award- Diode, emp, trics $22 l-to- DS1302A $1995 DS1202A $1595 saves benchspace. Compact Designwithsmallfootprint 2000 wfm/srefreshrate.Ultra 100/200/300MHz 2ch,2GS/sDSO S26Bnl $1574 PS3206 Bundle USB 2.0connection No powersupplyneeded,simple - 10GS/sforrepetitivesignals! 200MS/s 8-bitPCscopeadapter PS3206 - te-O2 $119 Ether-IO 24 TCP/IP Ethernetnetwork. programmable. Connects toany ports eachindependently digital I/Oboard3x8-bit TTL Ether-IO - host/device, verifycompliance. USB3.0 5Gbps too!Emulate TR110 /EX200EX260 and now- USB1.1/2.0/ FMod-TCP to anEthernet Connect I inputs, 19 xdigital I/O,5x10-bit A/D Fiveco - 100/200/300MHz DSO NEW! USB Bus NEW!

PicoScope 3206 RIGOL Ethernet toI2C Ethernet-IO Mixed -SignalPCOscilloscope and UART serialinterface. TCP/IP serverwithI2C, $999 /$2999CALL Is animpressive2-ch UDP/IP-controlled 24 2 C devices/sensors iei analyzers WiMedia EX260 Analyzers network! DS1102A $1295 from $250 UNIQUE PRODUCTS PRODUCTS UNIQUE can test 400kHz! Transparently monitorat UCA93LV and debugI2Cbussystems. gives windows-interfacetodevelop for PCs. PCI93LV Pico - PS3424 /PS3224$1398$793 with includedsoftware. and meterdisplayedatonce scope adapters.Scope,FFT, USB2.0-connected/ 2/4ch 12-bitUSB Scope FMod-TCP to anEthernet Connect I inputs, 19 xdigital I/O,5x10-bit A/D Fiveco - hnesx1,1,1 i with more channels x10,12,14bit swept signalgenerator. 2 Analog drilling andzooming.Optionalbuilt-in Huge 4or8MSbuffer fordeepdata hard-to-get-at glitches,spikes,etc. lets youdocomplextriggeringtofind 100 MHzScopeandLogic Analyzer CS700A CS328A-8 CS328A-4 inputs formixedsignaldisplay/trigger. dynamicrange.8digital than 60 dB B915FHtiny-plus/40-DIP-EA $804 B915FHtiny-plus/40-SMD-WA $64 reliable data transmission. & Complete RFsolutionforfast - 910MHz Easily createmeshnetworksat DS1102CD $1499 on data orsignaledge. logic data simultaneously. Trigger refresh rate.Seewaveformsand and logicanalyzer. 2000wfm/s 100MHz 2-ch/16logicscope + Scope + Analyzer Wireless Modules NEW! RIGOL Ethernet-IO I2C for New 2/4-ch12-bit and UART serialinterface. (signal generator) : industry-standard I2C TCP/IP serverwithI2C, (8MS Buffer) (4MS Buffer) like Zigbeeonlybetter! WINI2C/PCI 2 C devices/sensors SUPPORT! is USBversion. network! PCs from $250 powered software 20MS/s $1642 $499 $1149 $249 card USB-16COM-RM USB-8COM $195 USB-4COM $105 USB-2COM $48 USB Port. Add COMports HDS2062M 0H r6Mzrugged handheld USBscopewith3.8” 60MHz or 20MHz HDS1022M great foryourtoolkit. color LCD.Built-inmeter- PS5204 PS5203 analyzer and125MS/swaveformgen. 1GS/s. Adv triggering.250MHz 128 MS/sandreal-timesamplingof PS5204 - 15/20MHz WfmGen DG1011 /DG1021$650$795 frequency and BURST; 6digit wfms; FM, AM, PM, 10 Arbitrary wfmGenerators. 15/20MHz USB14-bit LD2- $49 CLCD420-B 2.36” x3.86” to 115Kbps. BASIC RS232 orI character Comfile - Portbase-3010/RS232 from$149 IP/DHCP/PPPoE. 10/100Mbps-230kbps. Static devices. 1/2/4/8/16/32ports network-enabling legacyserial RS232/422/485 deviceserver 1/2/4/8/16 xRS232 Blue &WhiteLCD NEW! Winner! Handheld Scope

World’s Fastest RIGOL Serial Server 128MS buffer 32MS buffer 2-ch 250MHzScopewith counter. E aki 4x20 LED backlit 2 (20MHz) (60MHz) communication C display. CuNET, USB-COM-S $20 (rackmount) via yourPC’s FSK, SWEEP programmed. 200MHz Function/ built-in $3360 $2237 $699 $499 $459 spec. for DG3101A/DG3121A gen. frequency counter;opt.16-ch built-in wfms;6digit200MHz w. USBRS-232,LAN/GPIB.10 60/100/120MHz USB14-bit ARB epiLbiwVEdri PS2105 Delphi/LabView/VEE C/VB/ 100MS/s, 24kSbuffer scope-in-a-probe! Upto PS2105 PS2104 One-to-one pinouts. inline spaced holes. m components with use yourultrafinepitchSMD Now side. each on footprints two OM-Adapt P01V0$205 PP1001-V00 control, SCADA, a webconnection. Collect analog&digital data over allows remoteI/Oandservicing. PicoServ business hints, kudos,etc." the-scenes company details, myself! Seemyblogforbehind- my customers,staff, and blessed' -whichiswhatIwantfor word meaning'happy, prosperous, 60/100/120MHz AWG ...a new name in high-end, in name new ...a high reliability, value- reliability, high priced test gear: RIGOL. RIGOL. gear: test priced Formerly the partner of partner the Formerly a large scope company scope large a we can't name, Rigol name, can't we produces the best the produces quality/value LCD scopes LCD quality/value available on the market today. market the on available SM PCB Adapters NEW!

Mini Web Server RIGOL (pronounced ‘regal’) (pronounced Announcing Pen Scope (25MHz, 100MS/s) (10MHz, 50MS/s) - 25MHz USB powered USB 25MHz - TM Saelig SM miniboardshave Miniature Web Server DG3061A $1895 building control. Remote sensing/ Olde English Saelig -an engineers! engineer -for Saelig asan says: "Istarted Alan Lowne ore useful0.1" $2795/$3995 from $9.52 vers. $234 $372 2803015_dalrymple.qxp 2/7/2008 9:48 AM Page 59

The channel I/O pins can be used as 20-ms frame simple inputs and outputs, but the counter makes a number of other Center - 1ms functions possible. For example, an input can start the counter operating Full left - 0.5 ms as a timer, with match values used to create a time-delayed output pulse or Full right - 1.5 ms two. A delayed interrupt can also be created with this configuration. Figure 6—Many servos use a 20-ms frame and a 1- to 2-ms position pulse. It’s easy to create four such signals The counter operating as a timer can per channel. be used to create synchronized output signals or special phase relationships No positional feedback is required for freeing up this channel for some among output pins. The global sync the tracks, but velocity information is other function. signal enables multiple channels to be required for closed-loop control and synchronized when more than four fault detection. Two inputs and the WRAPPING UP pins need coordinated timing. timer in channel 2 are used for this At first glance, the RIO seems like a function. The timer can be pro- pretty simple peripheral chip, but a ALL TOGETHER NOW grammed to measure either the width fair amount of thought went into the Figure 7 shows an example of how of the velocity pulses or the time features to make the device useful for the RIO might be configured to con- between successive velocity pulses, robotics and motion control applica- trol the operation of a basic robotics depending on how the signals are cre- tions. Yes, everything that the RIO platform. For this example, I’ve ated. The two remaining pins of chan- does can also be done with an FPGA assumed a track drive with a rotating nel 2 are available for use as simple or a small microcontroller, but dedi- turret to hold sensors and actuators. inputs or outputs. cated hardware will almost always be I’ve also assumed a serial bus inter- Channel 3 is used to control an H- a better choice. Give it a look next face so the entire channel I/O is bridge that drives the motor for the time you need to control something available. turret. Controlling the turret requires that moves. I Channels 0 and 1 are used to control positional feedback, so channel 4 is Author’s Note: Thanks to Norm Rogers H-bridges for the left and right tracks. used as a quadrature decoder for this of Rabbit Semiconductor for his vision function. The remaining I/O pin of a simple multi-purpose I/O chip. I in channel 4 feeds back the low also want to thank Pedram Abolgasem, battery detect signal or some A Lynn Wood, and Steve Hardy for help- B Left track drive other bit of status information. Channel 0 - H-bridge driver ing to bring it to fruition. C Channel 5 is used to control D four servos, perhaps for four Monte Dalrymple has been designing A B Right track drive degrees of freedom on an arm Channel 1 - H-bridge driver integrated circuits for 29 years. After C D attached to the turret. This tiring of the corporate world, he has channel uses a divided clock Left track velocity been designing on a contract basis for Right track velocity Channel 2 - Pulse width measurement for the slow frame rate of the the past 12 years. Monte is the design- – – servos. er of all four generations of Rabbit Channel 6 controls a pair of A microprocessors as well as the Rabbit B Turret drive Channel 3 - H-bridge driver servos for tilt and pan for a cam- C I/O chip. You may reach him at monted D era on the turret, while the @systemyde.com. other two pins connect to two I Q Turret position Channel 4 - Quadrature decoder contact sensors for the IDX RESOURCES Low battery inevitable case when the plat- Rabbit Semiconductor, “RIO Datasheet,” Servo 1 form bumps into something. Servo 2 www.rabbitsemiconductor.com/products Channel 5 - Servo drive (slow clock) The two inputs can be either Servo 3 /rio/Rabbit_RIO.pdf. Servo 4 polled or used to generate inter-

Servo 5 rupts. The divided clock is also ———, “RIO User’s Manual,” 019-0158 Channel 6 - Servo drive (slow clock) Servo 6 used for this channel. Interrupt inputs Front-left contact 070718-C, www.rabbitsemiconductor. Front-right contact Channel 7 is used for the last com/documentation/docs/manuals/ Rear-left contact two contact sensor inputs, so RabbitRIO/RabbitRIO.pdf. Channel 7 - Interrupt inputs Rear-right contact – two pins and the timer are – available for some other use. If SOURCE the contact sensor inputs are RIO Programmable I/O chip Figure 7—The RIO has the resources to handle an entire polled, they could be assigned to Rabbit Semiconductor robotics application, with room to spare. the unused pins on channel 2, www.rabbitsemiconductor.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 59 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 60

FEATURE ARTICLE by Kripasagar Venkat Efficient Micro Mathematics Multiplication and Division Techniques for MCUs Most inexpensive microcontrollers don’t have a hardware multiplier module and typically require numerous instruction cycles to perform multiplication and division operations. Kripasagar describes techniques based on Horner’s method for performing efficient multiplication and division in the absence of a hardware multiplier.

Low-cost microcontrollers are typi- across processors and their associated algorithms are specific to integer-inte- cally targeted at applications with low tools. All microcontrollers fall under ger multiplies or divides. This does levels of complexity and are optimized fixed-point processors and are mostly not mean that they are unable to sup- for cost and performance. The devices 8-bit or 16-bit devices. Fixed-point port multipliers or divisors that are should offer low power consumption processors suffer from the effects of pure fractions or real numbers. The and be simple to design. They should finite word length, round-off, and solution is a form of scaling that con- also provide easy interfaces to external truncation.[1] These issues have a verts all real numbers to integers. Dif- peripherals. As technology advances, direct impact on the accuracy of the ferent standards—such as Q formats— the demand for processing capabilities results obtained during mathematical have been introduced to accomplish and efficiency increases. This demand operations. A hardware multiplier is a this on fixed-point machines. There is, calls for an upgrade of existing micro- module that supports multiplication however, a potential loss in accuracy controllers with introduction of newer and multiply and accumulate (MAC) with such formats due to truncation peripherals. The design tools to sup- operations via dedicated central pro- of the real number on registers with port enhanced hardware and software cessing unit (CPU) instructions. Most fixed widths. Horner’s algorithm must also go through a process of con- low-cost microcontrollers do not have attempts to reduce this error and siderable development. Manufacturers a hardware multiplier module. They improve accuracy. This method for continuously strive to provide on-chip usually require a lot of instruction multiplication is easily extended to solutions for complex algorithms, thus cycles to perform multiplication using division, which is a multiplication by increasing cost. Some microcontrollers alternate algorithms. the divisor’s reciprocal. An innovative choose to go through limited enhance- Several algorithms have been scaling-free method to implement ments and adhere to low cost and low devised for fast multiply and divide integer-real multiplications will be power consumption. Complex algo- using only shift and add instructions described in this article. rithms and functions, such as digital for fixed-point processors.[2] These Horner’s algorithm is based on the filtering, at times become impossible on these devices. This forces design- ers to search for efficient methods 0. 2468 ×= 0.1357 ()0.001111110010111( 2−−−−379 +++ 2 2 2 111 +++ 2−−− 12 2 13 2 14 ) and make do with what is available. b = 0.0000011111 10010 This article focuses on one such effi- b + 0.00000000001 11111 cient method for microcontrollers. b

+ 0.0000000000 01111b + 0.0000000000 00011 ALGORITHMS b

Processors are broadly classified as + 0.0000000000 00001b

fixed point or floating point. Fixed- + 0.0000000000 00000b

point processors support only integers, + 0.0000000000 00000b whereas floating-point processors have additional circuitry to support integers 0. 000010001000100b = 0.03332519 53125 and fractions. Various standards for floating-point formats have been Figure 1—This is the binary equivalent of a 15 × 15-bit fractional multiplication with the multiplier known in established to maintain uniformity advance. Dedicated code would replace each of these steps to perform a multiplication on a 16-bit CPU.

60 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 61

bandwidth and lower power consump- Final product =× x 2−−−343 = ( x × 2 + x) × 2 65 tion. Performance of digital FIR digital =×−2 + ×+−−43× ()(x4 2 x) 2 x 2 filters on the MSP430 has also been shown to have excellent frequency =×+ ()()( x 2−−−224 x) ×+ 2 x × 2 + x × 2−3 3 responses. =×+ (()()( x 2−−−−1224 x) ×+ 2 x ×+ 2 x 2 + x) × 2−3 2 FRACTIONAL MULTIPLIER =×+ ((()()( x 2−−−−1122 x) ×+ 2 x ×+ 2 x × 2 + x) ×+ 2−−43 x) × 2 1 The data to be processed is usually an analog signal converted to digital sam- ⎛ −−−−−−−⎞ =×+( 111×+× + ×+×2243×+××+× ⎝((()() x 2 x) 2 x 2 x 2 ) 2 ) 2 x⎠ 2 ples using an on-chip ADC, for example =× x ( 2−−−−−37911121314 +++ 2 2 2 + 2 − + 2 − + 2 −) an ADC12, a 12-bit ADC on the MSP430. The digital samples can repre- sent analog signals such as temperature Figure 2—This is an example of a back substitution in the steps of Horner’s method for a fractional multiplier. This is done to verify if Horner’s method conforms to the conventional binary multiplication routine for fractions. captured by a sensor or audio signals that need some sort of digital filtering. position of the bits with a value of 1 known as poles) has a magnitude of less Horner’s algorithm is explained in and their distance to the neighboring 1 than one. Special care must be taken two parts, pure fractional multipliers in a multiplier. For this method to when scaling the IIR filter coefficients and pure integer multipliers. Steps have work, the multiplier or divisor should as it could easily render a stable IIR fil- been shown to distinguish their proce- be known in advance. This method ter unstable. Digital filter coefficients dures to achieve efficient multiplies. also relies on dedicated code for any almost always are real numbers. Their A fractional multiplier M falls in the multiplies or divides with a potential implementation on fixed-point proces- range –1 < M < 1. Multiplication by such increase in code size. These are not sors must support scaling to integers a number can be accomplished on fixed- serious limitations in applications and additional software to track any point machines only by scaling M an where speed is of prime concern or sort of overflow associated with them.[3] integer. Alternatively, the bits of value 1 when the multiplier or divisor does An alternative to all of this is to use can be identified and shift and add opera- not change run-time. The canonical high-level languages such as C along tions on any multiplicand x can be done. signed digit (CSD) format is introduced with a floating-point library to support This approach would lead to a dedicated to further reduce the CPU overhead. integer-real number multiplies. A C code for each multiplier. Consider the floating-point library would produce example with x = 0.2468 and M = 0.1357 FILTERING accurate results but with increased with 15-bit resolution: Filtering forms the crux of many digi- CPU overhead, rendering real-time pro- x == 0.2468 0.001111110010111 tal processing algorithms. Filtering can cessing would be at times impossible. b [1] M == 0.1357 0.0010001010111110 be viewed as a weighted multiply and ’s ultra-low-power b accumulate (MAC) process. Digital filters MSP430 microcontrollers are an exam- Figure 1 shows the exact bit-wise come in two flavors: finite impulse ple of modern 16-bit microcontrollers binary addition for this multiplication. response (FIR) and infinite impulse that support single-cycle shift and add The correct result for this multipli- response (IIR). A mathematician’s view instructions.[4] Although some of the cation using floating-point math is of a FIR is a transfer function with only a devices offer a hardware multiplier 0.03349076 and the absolute error numerator polynomial. An IIR filter is a module, this transfer function with both numerator method can still be and denominator polynomials. FIR filters used to accomplish 0.000111111001011b 0.001011110110001b use only present and past samples of the an integer-real mul- + 0.001111110010111 + 0.0011111100010111 x = b x = b input signal, whereas IIR filters in addi- tiply. Comparisons 1 2 0.0101111101100010 0.011011101001000 tion use previous samples of the out- of Horner’s method b b put.[1] Stability of these filters is extreme- and Horner’s 0.0011011101000100 0.000111011001110 ly important to preserve the sanity of the method using CSD b b + 0.001111110010111 + 0.001111110010111 signal being filtered at the output. A FIR are made with x = b x = b 3 4 filter is inherently stable with no restric- existing integer- 0. 011101100111011b 0.1 010111001100101b tion on the roots (also known as zeros) of integer multiply its polynomial. It can also exhibit linear algorithms and a C 0.000101110011001 0.0000010101100011 phase to reduce the phase distortion of floating-point b b + 0.0 001111110010111 + 0.001111110010111 x = b x = b any input signal. The IIR filter performs library. Results are 5 6 0. 010101100110000 0. 010001001001010 much better and requires a significantly shown to exhibit b b smaller order compared to a FIR filter for good accuracy the same set of filtering specifications. under low-power Figure 3—This is a binary representation and mapping of the implementation

An IIR filter is stable only if the roots CPU cycle count to steps of Horner’s method for Equation 1. The result of the intermediate steps x1 to

of its denominator polynomial (also imply reduced CPU x6 shows its progression to the final result.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 61 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 62

using the conventional method is ate result. The multiplicand x is again Final product =×= x 20 ( x ×+ 22 x) 0.0001655646875, an error of approxi- added to the weighted result for the 3 2 –11 =×+1 × 2 + mately 5.4 LSB. This error is due to occurrence of the 1 at bit position 2 . ()( x1 2 x) 2 x finite word-length effects on the mul- The result of this addition is now =×+ ()()( x 2312 x) ×+ 2 x ×+ 2 x tiplier. Horner’s algorithm attempts to stored as the intermediate result x3 for 0236 reduce this error. the next step: =× x ( 2 + 2 +++ 2 2) =× x 77

Horner’s algorithm identifies the posi- − x ×+= 21 x x tions of bits with a value of 1 in the mul- 2 3 [4] Figure 4—Here you see back substitution in the steps of Horner’s method for an integer multiplier. This is tiplier and their distance to the nearest 1 The fourth step is to proceed to the done to verify if Horner’s method conforms to the con- to the left. This is done starting from the next bit with a value of 1 (2–11). The near- ventional binary multiplication routine for integers. rightmost 1 and moving left to the last 1 est 1 to its left is at bit position 2–9. The before the binary point. For Equation 1 difference in weight 2–2 is applied to the Because it is the last binary 1, it does with M = 0.1357, the position of the bits intermediate result. The multiplicand x not have any ones to the left; there- with a value of 1 in the multiplier are is again added to the weighted result for fore, only its bit position is applied as {2–14, 2–13, 2–12, 2–11, 2–9, 2–7, 2–3}. The dis- the occurrence of the 1 at bit position 2–9. the weight to the intermediate result tance of the closest binary 1 to the left for The result of this addition is stored as the to give the final product (i.e., 2–3). The

each of the bits is {1, 1, 1, 1, 2, 2, 2, 4}. intermediate result x4 for the next step: result is the final product: Once this has been established, Horner’s − ×+=2 −3 x3 2 x x4 Final product =× x 2 algorithm generates a set of design equa- [5] 6 [8] tions using only shift and add operations. The fifth step is to proceed to the next The procedure can be validated by The design equations are written in bit with a value of 1 (2–9). The nearest 1 back substitution to give the same terms of the multiplicand x. It is assumed to its left is at bit position 2–7. The differ- result as the conventional multiply (see that the reader is aware that 2–1 is a right ence in weight 2–2 is applied to the inter- Figure 2). shift by 1 and 21 is a left shift by 1. mediate result. The multiplicand x is The bit-wise realization of design Equa- The first step is to initialize the inter- again added to the weighted result for tions 2 through 7 is shown in Figure 3. mediate result to x and proceed to the the occurrence of the 1 at bit position 2–7. It indicates the exact operations at rightmost bit (2–14). The nearest 1 to its The result of the addition is stored as the each stage and gives a brighter picture –13 left is at bit position 2 . The difference intermediate result x5 for the next step: of Horner’s method. The final product in weight 2–1 is applied to the intermedi- is 0.000010001001001 . x ×+= 2−2 x x b ate result. The multiplicand x is then 4 5 [6] This results in an absolute error of added to the weighted result for the At step six, proceed to the next bit 0.000012976796875, an error of approx- occurrence of the 1 at bit position 2–13. with a value of 1 (2–7). The nearest 1 to its imately 0.42522368 LSB. Thus, The result of this addition is now stored left is at bit position 2–3. The difference in Horner’s algorithm is extremely accu- –4 as the intermediate result x1 for the weight 2 is applied to the intermediate rate and does not suffer much from next step: result. The multiplicand x is again added finite word length effects. The design to the weighted result for the occurrence equations involve only right shifts and ×+=−1 [2] x 2 x x1 of the 1 at bit position 2–3. The result of add operations making it an extremely The next step is to proceed to the next this addition is now stored as the inter- fast algorithm. The design equations are –13 bit with a value of 1 (2 ). The nearest mediate result x6 for the next step: unique for this multiplier and a 15-bit 1 to its left is at bit position 2–12. The register width. This also implies that the x ×+= 2−4 x x difference in weight 2–1 is applied to the 5 6 [7] multiplicand x can be any number (inte- intermediate result. The multiplicand x The seventh step is to proceed to ger/fraction) of any sign (positive/nega- is again added to the weighted result for the last bit with a value of 1 (2–3). tive). If the multiplier is a negative num- the occurrence of the 1 at ber, 2’s complement for- bit position 2–12. The mat should be used for its M == 0.1357 0.001000101011110b result of this addition is group{ binary representation and now stored as the inter- should follow similar = 0.00100010 11 00010 b = 0.0001000 11 0100010b { { mediate result x2 for the group group steps to obtain the design

next step: −−−368−−10 14 equations. ==+− 0.001001010100010CSD 2 2 2 −− 2 2 x ×+= 2−1 x x Number of reducations in add is two 1 2 [3] INTEGER MULTIPLIER M = 891 ==== 11011110 11 b 1101111101bb 111 0000101 { The third step is to { { Horner’s method is eas- group group group proceed to the next bit ily extended to integer 10 7−2 0 with a value of 1 (2–12). = 10010000101CSSD =−−−= 2 2 2 2 1,024 − 128 −−= 4 1 891 multipliers using the same The nearest 1 to its left is Number of reductions in add is four concept. The only differ- at bit position 2–11. The ence is in the search for Figure 5—For any integer or fractional multiplier M, the CSD conversion of multipliers is done –1 difference in weight 2 is to reduce overhead. Stepwise grouping of adjacent binary 1s with the number of reductions in ones. The search is now applied to the intermedi- each case is shown. The integrity of the multiplier after conversion to CSD is also verified. from the leftmost bit to

62 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 63

Methods CPU cycles Code size Result Absolute error uses a ternary set {–1, 0, 1} compared to a Horner’s method 33 68 bytes 10656 0.38979 binary set {0, 1}. If looked at carefully, the Horner with CSD 27 56 bytes 10656 0.38979 number of steps in Horner’s algorithm Existing method (14) 107 54 bytes 9954 702.38979 depends on the number of 1s present in Existing method (15) 107 54 bytes 10665 8.61021 the multiplier. The CSD format attempts C Floating-point library 427 322 bytes 10656.38979 0 to reduce the steps by grouping consec- utive 1s in the multiplier and replacing Table 1—This evaluation of Horner’s method is done with comparisons to other methods on the MSP430 platform. For consistency, the same multipliers are chosen and the result for each multiply is shown. Cycle count directly them with a combination of the ternary relates to the overhead on the CPU and absolute error indicates the accuracy of each method. set {–1, 0, 1}. This modification reduces the number of add operations for multi- the rightmost bit before the binary point. tailor-made for algorithms that rely on pliers that have groups of consecutive 1s. The multiplier M in this case is any inte- bits with a value of 1 for their design.[3] By examination, the CSD representation ger. Additional care must be taken to The CSD format for its representation would never have adjacent 1s or –1s. ensure that the result of the multiply does not exceed the range for represen- tation in the microcontroller. The sec- ond example shows a similar scheme when the multiplier is an integer type. Only design equations have been pro- vided for this multiplier with x taking any form (integer/fraction). Consider the

multiplier M = 77 = 1001101b. The fol- lowing are design equations:

×+=3 x 2 x x1 [9]

×+=1 x1 2 x x2 [10]

×+=2 x2 2 x x3 [11]

=×0 Final product x3 2 [12] The weights in design Equations 9 through 11 are all positive powers of two rather than negative, as the direction is now from left to right, as opposed to right to left for fractional multipliers. The result of back substitution for the integer multiplier is shown in Figure 4.

REAL MULTIPLIER Procedures for pure fraction and pure integer multipliers were shown separate- ly to distinguish their implementation. Once this is established, a real number multiplication can easily be realized using either of the two approaches. The multiplier is scaled up or scaled down to either pure integers or pure fractions, and Horner’s method applied to them. Once the multiplication is complete, the result must be scaled accordingly. The resulting error is extremely small, similar to Equation 1. This makes filtering an easy task without the overhead of a C floating-point library.

CSD REPRESENTATION The CSD format or representation is

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 63 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 64

Don’t be confused by the term “ternary Listing 1—This is a section of typical MSP430 microcontroller code for an integer-real multiply. The dedicated set” because the process of introducing code mainly consists of add/subtract and shift instructions only. For an MSP430 microcontroller, the add/subtract –1s in a number is merely to replace and shift instructions are single-cycle. some of the additions by subtractions. The grouping is done starting from the inv.w R13 ; 2's compliment since the last digit is -1 add.w #1,R13 rightmost bit and proceeding left. rra.w R13 Figure 5 shows an example with the rra.w R13 steps involved in binary to CSD conver- rra.w R13 sion and subsequent reduction in add add.w R12,R13 ; X1=-X*2^-3+X operations. The ternary element –1 is rra.w R13 _ rra.w R13 represented as 1 in Figure 5. sub.w R12,R13 ; X2=X1*2^-2-X For the fractional multiplier, starting rra.w R13 from the rightmost, replace the first rra.w R13 group of 1s (2–14 to 2–11) by a combination rra.w R13 of {–1, 0, 1}. The four 1s are combined rra.w R13 _ rra.w R13 and 1 is placed at the rightmost bit rra.w R13 –14 position (2 ), zeros at the remaining sub.w R12,R13 ; X3=X2*2^-6-X position (2–13 to 2–11), and a 1 in the 1 bit rra.w R13 position to the left of this group (2–10). rra.w R13 This procedure is repeated for subsequent rra.w R13 rra.w R13 groups of ones already present or created add.w R12,R13 ; X4=X3*2^-4+X from previous groupings. A similar proce- rla.w R13 ; Upscale final result by 16 dure is shown for the integer multiplier. rla.w R13 The reduction in add operations is two in rla.w R13 the fractional case and four in the integer rla.w R13 ; Final result of multiplication mov.w R13, R12 ; Value returned to calling function case. This reduction is multiplier- ret dependent and effective only when there END are a number of groups of consecutive

64 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 1/28/2008 4:14 PM Page 1 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 66

the add operation implemented at the end of each step. 100 IMPLEMENTATION ON THE MSP430 Horner’s method works most effi- ciently on microcontrollers that sup- 10–1 port single-cycle add and shift opera- tions. For example, the MSP430 CPU supports this requirement and also performs single-cycle register-register –2 10 move operations, enabling fast multi- ply. A section of the MSP430 micro- controller’s assembly code is shown in Normalized gain (logarithmic scale) Listing 1. Table 1 shows a comparison –3 10 of the Horner’s method, Horner’s method using CSD, existing algo- rithms, and the floating-point C library. Performance measures such as 10–4 0 200 400 600 800 1,000 1,200 1,400 1,600 1,800 2,000 code size, CPU cycles, and the final Frequency (Hz) result have been shown for a standard integer-real multiply. Results for filter Figure 6—Horner’s method is used to implement a low-pass filter with a cut-off of 300 Hz. The response is depicted as a gain versus frequency plot and is shown to conform to the design. implementation using Horner’s method using CSD are implemented. ones in the multiplier. The CSD format way Horner’s algorithm is implemented. An approximate frequency response produces the same results for multiplies Because there would be a ternary set, all using a simple square and add opera- or divides with a slight reduction in CPU –1s would be subtracts and all 1s would tion in the filtered signal across vari- overhead. The introduction of the CSD continue to remain adds. This subtract, ous frequencies is shown in Figure 6 format introduces a small change in the when necessary, would merely replace and Figure 7.

CIRCUIT CELLAR® 66 Issue 212 March 2008 www.circuitcellar.com 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 67

Table 1 shows the comparison of least three times faster than the exist- Horner’s method and its variation to ing methods. These methods have alternate methods for an integer-real limited accuracy with the option of multiply of the number 711 and the scaling and using 32-bit registers to real multiplier 14.98789. The number improve accuracy. The floating-point 14.98789 is first scaled down by 16 library is almost not an option (right shift by four) to get 0.936743125. because it is almost 15 times slower. The result is then scaled up by the To exhibit the performance of filtering same number 16 (left shift by four). using Horner’s method, two filter The result of Horner’s method is the implementations have been shown. closest to the floating-point library The first example is a FIR low-pass fil- implementation losing only the frac- ter and the second is a FIR band-pass tional part of the final result. This filter. In both cases, the normalized result is as good as it can get consider- gain in dB versus frequency is shown. ing its implementation is on a fixed- Limited frequency resolution has been point processor. The existing method, chosen because the intent is to show although generic in implementation, the filter’s performance for a pre-fixed loses precision due to finite-word frequency sweep. In a real-world appli- length effects at the start of the multi- cation, frequency resolution does not ply. To be fair to the integer-integer have a role to play. The performance multiply algorithm, both cases of depends on the number of bits chosen rounding up to 15 and rounding down for the coefficients and the filter order. to 14 are shown. The multiplier, even For every increase in order, the if rounded-up, has significant error increase in the number of CPU cycles (see Table 1). can vary between 30 and 35 CPU Although Horner’s method requires cycles, which also includes memory dedicated code for each multiplier, the updates. These are huge savings when accuracy it provides is too tempting to compared to a floating-point library use it. The CSD format is just an addi- implementation. tional option to further reduce the Figure 6 shows the response of a thir- execution cycles and code size. tieth-order low-pass filter with its cut- For real-time filtering operations, off set at 300 Hz at a sampling frequen- Horner’s method is certainly preferred cy of 4,000 Hz. The entire filter takes over the other method because it is at 1,030 CPU cycles with 31 integer-real

100

10–1

10–2 Normalized gain (logarithmic scale)

10–3 0 500 1,000 1,500 2,000 2,500 3,000 3,500 4,000 Frequency (Hz)

Figure 7—When Horner’s method is used to implement a band-pass filter to extract the voice band of 300 to 3,400 Hz, the response is depicted as a gain versus frequency plot and it is shown to conform to the design.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 67 2803017_Venkat.qxp 2/7/2008 10:04 AM Page 68

multiplies and 30 memory-memory shown with examples. The CSD for- emphasis on digital signal processing. moves at each stage and occupying a mat was introduced and its effects on His current interests include signal code size of 1,696 bytes. The MSP430 reduction of steps was portrayed. This processing and filter design for low- microcontroller supports a real-time method not only showed superior per- power applications. operation for this case. If a floating- formance, but also removed the fear of point library was used instead, the CPU overhead on the real-time imple- PROJECT FILES cycle count would be a minimum of mentation of digital filters. The num- To download code, go to ftp://ftp.circuit 14,000 cycles preventing any real-time ber of CPU cycles and code size cellar.com/pub/Circuit_Cellar/2008/212. filtering. depend entirely on the resolution cho- Figure 7 shows an implementation sen for the filter coefficients. There REFERENCES of a twentieth-order band-pass filter cannot be a compromise on the inte- [1] S. K. Mitra, Digital Signal Process- specifically intended to limit the fre- ger part, but fewer resolutions for the ing: A Computer-Based Approach, quencies to the voice band, ideal for fractional part can significantly reduce McGraw-Hill, New York, NY, 2001. speech applications. The passband is the CPU cycles with a compromise to set from 300 to 3,400 Hz with a sam- performance. This method is certainly [2] C. Hamacher, Z. Vranesic, and S. pling frequency set at 8,000 Hz. The not limited to processors without a Zaky, Computer Organization, total instruction cycles in this case is hardware multiplier. Instead, it paves McGraw-Hill, New York, NY, 1990. just 677 CPU cycles with a code size the way for integer-real multiply on [3] R. M. Hewlitt & E. S. Swart- of 1,110 bytes. Both these filters are fixed-point machines. With memory zlantler, “Canonical Signed Digit Rep- very close to their respective floating- getting cheaper by the day, code size resentation for FIR Digital Filters,” point implementations. can never pose a limitation for such a 2000 IEEE Workshop on Signal Pro- powerful scheme! I ACHIEVE EFFICIENCY cessing Systems, Oct. 11 to 13, 2000. This article focused on efficient Kripasagar Venkat ([email protected]) is an multiplication and division of micro- applications engineer for MSP430 SOURCE controllers without a hardware multi- microcontrollers at Texas Instruments. MSP430 Family of microcontrollers plier module. The design steps to He holds a Master’s degree from the Texas Instruments, Inc. implement Horner’s algorithm were University of Texas at Dallas with an www.ti.com

68 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 69

FROM THE BENCH by Jeff Bachiochi

Navigating the Heavens With Celestron’s SkyScout, you can explore outer space without leaving your backyard. The handheld device gives you point-and-click convenience to identify thousands of stars, planets, constellations, and deep-space objects.You don’t even need instructions. Just turn it on and follow the directions on the LCD. ARM processor power brings the heavens to you.

Adding exterior lighting to streets, identifies any celestial object that is daylight. At the half-year mark, anoth- parking lots, buildings, and signage centered in the sighting tube. Alter- er solstice occurs. Now the South Pole makes our nights safer, but it nately, you can flip through a database is closest to the sun and the southern unknowingly adds to the growing light of objects on the LCD, choose one, and hemisphere experiences summer, pollution problem that may threaten the SkyScout will steer you toward it while the northern hemisphere is mid- some life on our planet (see Photo 1). via unique pointers in the sight tube. winter. After another equinox at nine Light pollution isn’t obvious unless To enjoy the SkyScout, you don’t need months, the Earth heads back to its you like to stargaze. If you do, you to know anything about celestial coor- original position and the yearly sea- quickly realize its effect of washing dinates, just turn it on and follow the sonal cycle begins again. out the nighttime sky. Civil engineers clear instructions. However, to under- The Earth is geographically mapped are now required to design with direc- stand how this device works, you’ll using latitude and longitude. Latitude tional lighting to help minimize this need to know a little about the sky. is a north-south measurement. Lines effect. Light pollution interferes with of constant latitude run east-west the way many plants and animals EARTH AND SUN around the Earth’s circumference, par- function. Although we cannot elimi- The Earth rotates about its allel to the equator. Longitude is an nate light pollution, we can reduce its North/South Pole axis once a day (24 east-west measurement, with lines effects and save energy by using illu- hours). It also orbits around the sun that run pole-to-pole dividing the mination wisely (as we should every once in a year while it spins (365 1/4 Earth into “orange wedges.” The resource). Although light pollution rotations or days). The Earth’s axis is prime meridian is the longitudinal interferes with this month’s topic, it’s not perpendicular to its orbit but tilted between the two poles that passes not the focus here. However, you are about 23.5°. (As with the mechanics of through Greenwich, England. It has encouraged to learn more about light most objects, the tilt isn’t constant. But been assigned 0° (with 180° on the pollution and its effects on our planet in an effort to make things less confus- opposite side of the Earth). Longitudi- by visiting your local library or using ing, we’ll ignore long-term effects.) nal lines to the east of the prime your favorite search engine. The Earth’s tilt is responsible for meridian are designated 0° to 180°E. To This month, I want to discuss the the change in seasons. At one point the west of the prime meridian they design of a device that makes it sim- during the orbital year, the Earth’s are designated 0° to 180°W. Latitudinal ple for anyone to enjoy stargazing. North Pole will be closest to the sun lines are north/south measurements Celestron has been making telescopes (the solstice). The northern hemi- based on the equator. The equator is since 1960 and it recently released the sphere is midsummer with its longest designated as 0°. From the Earth’s cen- SkyScout, a handheld device that gives period of daylight. The southern ter, angles measured from the equator its users a point-and-click way to hemisphere is mid-winter with its (0°) to either pole (90°) divide each identify thousands of stars, planets, shortest period of daylight. Three hemisphere into rings parallel with the constellations, and deep-space objects. months later, each pole will be equi- equator, either 0° to 90°N (north of The celestial sighting device uses an distant from the sun (the equinox). the equator) or 0° to 90°S (south of the exterior LCD to give instructions and While the northern hemisphere heads equator). For instance, the location 0° information. The device has two basic toward winter with shorter periods of longitude and 0° latitude defines a modes of use, Identify and Locate. Press- daylight, the southern hemisphere looks point off the shore of Africa. ing the Target button automatically toward summer and longer periods of It wasn’t until 1884 that Greenwich

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 69 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 70

field. From our vantage only at night, and our view of them point, all objects outside changes by 00:03:56 each night. It our solar system appear takes a full year to see all that the to be motionless. If the heavens has to offer because we get to 3 first stargazers were able “see” the stars only when we face to take photographs of away from the sun. 2 the constellations thou- The mapping system of the heavens sands of years ago and we is similar to our geographical coordi- compared them to what nate system on Earth. Imagine a clear we see today, there sphere surrounding the Earth that is 1 would be differences. able to stay fixed with the universe so That is because most the Earth rotates within it. The stars in a constellation Earth’s axis extends through the are at different distances sphere, effectively giving this new from us. Each moves at sphere poles. The sphere has longitu- its own rate, changing dinal wedges that are marked by time Figure 1—This graphic demonstrates a solar day and a sidereal day. A sidereal the general shape of the (like time zones). Whereas the geo- day is the difference between time 1 and time 2, or 23:56:04 (based on the change in the Earth’s position to a distant star). A solar day is the difference constellation’s pattern by graphical coordinate system uses the between time 1 and time 3, or 24:00:00, an additional 00:03:56 (based on the very small amounts. prime meridian’s intersection with the Earth’s change in position to the sun). On a prograde planet like the Earth, a Imagine for now that equator as the starting reference point, sidereal day is shorter than a solar day. At time 1, the sun and a certain distant we had no sun and it was the celestial coordinate system uses the star are both overhead. At time 2, the planet has rotated 360° and the distant star is overhead again, but the sun is not (1→2 = one sidereal day). It is not until night 24 hours a day. arc between its poles that passes through a little later, at time 3, that the sun is overhead again (1→3 = one solar day). This means that we the first star in the constellation Pisces (Source: http://en.wikipedia.org/wiki/Earth_rotation) would always be able to as a reference of time zero (00:00:00). see the stars. In 24 hours, Twenty-four wedges create a longitudi- was adopted as the universal prime we would see a complete tour of the nal line every 15 degrees, or one hour meridian (0°). Imagine the confusion constellations as the Earth makes one (360°/24 hours) (see Figure 2). Thus, time with mapmakers all using their own complete rotation. If we picked out a is used to indicate a “right ascension” to designation for the prime meridian! star, such as Betelgeuse (in the constel- the west in hours, minutes, and seconds lation Orion), and timed how long it (the amount of time it takes the Earth EARTH AND THE COSMOS takes the Earth to rotate bringing to rotate from the reference to the We are so enamored with the sun Betelgeuse back to the same position object of desire, 00:00:00 to 24:00:00). that we sometimes fail to look at the in the sky, it would not be 24 hours Just like latitude lines in the geo- bigger picture. Our solar system, the (24:00:00), but 23:56:04. Hmm. graphic coordinate system, declination sun, and all nine planets (yes, I still Because the rotating Earth moves in (DEC) is given in degrees north and consider Pluto a planet), are but a an orbit around the sun, it needs to south of the equator. Only in the speck in a spiral arm of the Milky rotate past 360° to get pointing back to celestial coordinate system, the Way galaxy. For a little comparison in the sun (see Figure 1). So, when we say degrees are designated by using (+) scale, let’s use the speed of light (the the sun rotates 360° every day, this is in instead of (N) and (–) instead of (S). fastest measure we know). From the reference to the sun (a minor player). I like to think of the radius of this sun, it takes about 8 min. for light to This definition of a solar reach Earth (about 80 min. to reach day is 24:00:00 in Pluto). This makes the diameter of our length. From the per- solar system about 160 light minutes, spective of the cosmos, or 2.6 light hours (about 1/10 of a light what we take for grant- day or 1/3,650 of a light year). The size ed is all wrong. The of the Milky Way is about 65 million celestial or sidereal day times larger, or more than 18,000 light is 00:03:56 shorter. years! It contains hundreds of millions With the sun back in of stars. place, things don’t It is enough to know that the Milky really change. It’s just Way galaxy is only a speck in the uni- our perception that verse. The number of galaxies in the changes because we universe is almost beyond comprehen- base our lives on the sion. All that is out there is in con- solar day and not the Figure 2—The celestial coordinate system uses time designated as right ascension (RA) and angle of declination (DEC) from a reference point where stant motion. To the average Joe on sidereal day. With the the celestial equator crosses the arc passing through the first star of the Earth, what he can see from Earth (by sun back in the pic- constellation Pisces. (Source: www.celestron.com/c2/images/files/downloads/ the unaided eye) defines his playing ture, we see the stars CPC800_11073.pdf)

70 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 71

provides a snapshot of the device’s posi- tion. This is used for identifying objects. In Locate mode, a database of objects is displayed via the LCD. Once an object is selected, eight LEDs around the inside of the sighting tube direct you to move toward the object until it is directly in the center of the sighting tube. The sim- plicity of coaxing you to move using a ring of directional LEDs disguises the complicated sensors and math computa- tions associated with the action. This is Photo 1—You can clearly see the light pollution of the east- the basis of good product design. ern seaboard as seen from the space shuttle as it passes Cell phones, navigation aids, the over the Long Island Sound. (Source: Earth Sciences and Image Analysis Laboratory, NASA, Johnson Space Center) LoJack, and other products take advantage of the system of satellites in geosynchronous orbit to gather clear sphere to be variable and just positional information. The SkyScout smaller than any object of interest. This uses an internal GPS module to calcu- way, any parallax error (the difference in late the precise position of its user. It viewing angle between the center of the Earth—the center of the sphere— and a viewer on the Earth’s surface) will be insignificant. The path the stars seem to take (while you spin on the Earth beneath them) will change based on where you view them from. If you lie down at the equa- tor and view the movement of the sky Photo 2—An LCD and controls are conveniently locat- ed on the side of the SkyScout. Two AA batteries sup- over the period of the night, the stars ply power for hours of nighttime viewing. (Source: will rise, move overhead, and set. If you www.myskyscout.com/skyscout_tour/index.html) fly to one of the poles and spend the night watching the stars, they will rotate in a circular pattern about the pole. requires sufficient signal from three satellites to triangulate the user’s posi- SkyScout tion on Earth (longitude, latitude, and The small, lightweight SkyScout elevation). It may attempt to receive can be used at length without fatigue. signals from up to 12 satellites. Once Any product’s success will depend on the SkyScout has acquired a fix, you many factors, but the user interface is the most important. If the product is intuitive, it is more likely to be suc- Name Polaris cessful. The SkyScout has a friendly Common name The North Star appearance with all controls, except Constellation Ursa Minor for one, mounted on one face with a Bayer 1-Alpha Ursae Minoris backlit (red to preserve night vision) Distance 431.42 LY LCD (see Photo 2). Each of the nine SAO 308 HIP 11,767 large rubber buttons (with a construc- Spectral F7;lb-IIv SB tion similar to a remote control) is Apparent magnitude 1.97 clearly marked with its function (i.e., Absolute magnitude –4.60 Locate). A Target button is positioned RA 2 h 31.84 min. for easy access beneath the forefinger DEC 89.2640° while viewing an object through the Type Binary star sighting tube. Unlike a telescope or Separation 18.4000 arc sec binoculars, there is no magnification Table 1—SkyScout’s database reveals plenty of infor- through the sighting tube. When you mation about constellations, including common and look at an object through the Sky- proper names as well as brightness and where it is Scout’s sighting tube, the Target button located in the celestial coordinate system.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 71 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 72

Name Jupiter Here a fixed RA and DEC won’t the Status (A = active or V = void). Diameter 139,822 km (86,833.7 miles) work. The RA and DEC must be “4807.038,N” is the latitude 48° Mass 1.90e + 27 (318 Earths) calculated. This is based on where 07.038′N. “01131.000,E” is the lon- Orbital period 11.86 Earth years the Earth is within its orbit and gitude 11° 31.000′E. “022.4” is the Rotation period 9.94 Earth hours where Jupiter (in this case) is within Speed over the ground in knots. Orbit radius 1,557 million km its orbit. A two-line element (TLE) “084.4” is the Track angle in degrees Apparent magnitude –1.85 is a data record that describes an True. “230394” is the Date, 23rd March RA 17 h 19.96 min. orbit’s features. Date and time infor- 1994. “003.1,W” is the Magnetic Varia- DEC –22.8579° mation from the GPS enables the tion. “*6A” is the checksum data, Table 2—The planetary database includes technical information, SkyScout to calculate orbit positions which always begins with an asterisk. such as size and mass in addition to the planets’ orbital physics. based on a TLE. The two calculated You might want to visit the NMEA orbital positions (in this case Earth web site or read one of my a previous can review the identified satellites and and Jupiter) can be used to determine an columns for more information on their associated strength along with RA and DEC for locating Jupiter. The using GPS data (“Where’s Waldo?: Pin- your present calculated position. GPS scientific data displayed for Jupiter is pointing Location by Interfacing with technology is the first step in making shown in Table 2. a GPS Receiver,” Circuit Cellar 126, this product user-friendly. It eliminates 2001). The more satellites a GPS the need for a user to determine longi- GPS receiver has to work with, the more tude, latitude, and time of day and then The Global Positioning System accurately it can calculate its location. have to enter them manually. (GPS) is a network of satellites, set in You can see from the selected sen- The remaining sensor technology geostationary orbit around the Earth, tence that date and time information (physical position of the SkyScout) is which transmits a time-synchronized is also provided by the GPS. used to locate or identify objects in signal. The National Marine Electron- The SkyScout uses the GPS to locate the sky. The order of the next two pro- ics Association (NMEA) developed the the user on the surface of the Earth cedures depends on whether you are specification that defines the data (where), and also to define a snapshot locating or identifying. When using issued by GPS receivers. One such in time (when). This information is the locate function, the database is sentence (ASCII data) is shown below: used to define a point in time when the used to determine the celestial posi- user geographic coordinate system is tion of the object. Then the position- $GPRMC,123519,A,4807.038,N,01 referenced to the celestial coordinate ing function directs the SkyScout 131.000,E,022.4,084.4,230394, system, as if the Earth has stopped toward the object’s position relative to 003.1,W*6A rotating in a known position in refer- the user’s position. When the identify ence to all of the objects in the sky. function is chosen, the positioning “RMC” is the recommended minimum functions determine the celestial posi- sentence C data. “123519” is the WHICH WAY IS UP? tion of the viewing tube and then time of the Fix, 12:35:19 UTC. “A” is At this point, all we’ve done is stop check the database for an the Earth. (We’ve taken a snapshot in object that matches that celes- time.) We still need to know where to tial position. look to find an object or where we are looking to identify an object. The DATABASE OF OBJECTS SkyScout uses magnetic and Objects outside of our solar accelerometer sensors to determine system require a minimum of its orientation based on the Earth’s data. These objects can be con- magnetic field and gravity. sidered standing still in refer- Several months ago, I explained ence to our lifetime. While how to use an accelerometer to only RA and DEC are necessary determine slope (“What’s the to fix its position on the celes- Slope?: Use an Accelerometer to tial sphere, other data provides Measure Slope,” Circuit Cellar 202, plenty of educational fodder. 2007). The Earth’s gravity looks The scientific data displayed like a 1-G acceleration toward the for Polaris is shown in Table 1. center of the planet. Once the GPS Objects within the solar has stopped and the Earth and the system have a life of their sky are in a fixed position, the own. Because they are (rela- accelerometer will provide a refer- tively) close by and have peri- ence vector from the center of the Figure 3—This map shows the declination offsets for the world as of the year odic orbits like that of Earth, Earth, through your position, and 2000. It is interesting to note that the magnetic poles are not 180° opposite one their positions relative to the another as are the true North and South poles (the Earth’s axis of rotation). extend directly overhead into the Earth are always changing. (Source: http://geomag.usgs.gov/charts/IGRF2000.dec.na.pdf) universe. This vector enables the

72 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 73.qxp 2/12/2008 10:52 AM Page 1 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 74

by miles a year. (It is inter- esting to note that charged particles from the sun cause it to wander in a daily ellip- tical perturbance.) Mapmak- ers note the difference between true north and magnetic north for a given map by declaring the mag- netic declination for the Figure 4—Red directional LEDs prompt you to move the sighting tube in the direction necessary to bring the object of interest into view. All area. As you pass from the LEDs on means you are there. (Source: www.celestron.com/c2/ East to the West Coast in images/files/downloads/1157656360_skyscoutmanualw.pdf) the U.S., this declination changes from about –20° to SkyScout to point directly toward the 20° (see Figure 3). You can see that the point in the celestial sphere that the declination is important to accuracy and GPS’s data has been able to calculate. its value is determined by where on Remember that the geographical coor- Earth you are located. You may have dinate and celestial coordinate systems noticed that the GPS output string have the N/S pole axis in common. To includes a magnetic variation element. move to other locations on the celestial Now that we know which way is sphere, we need to know which direction north, we can move to any other coor- is north. The SkyScout uses sensitive dinate in the celestial coordinate sys- magnetic sensors to accomplish this. tem from the known point directly (The SkyScout is so sensitive to magnet- overhead. But how does the SkyScout ic fields that it provides mu-metal lead the user toward an object of inter- shields to block any magnetic field inter- est? The sighting tube has eight LEDs ference from the AA batteries.) Most can located around its interior circumfer- tell you that a compass needle will point ence. Real-time calculations, based on north. Some know that this is not really the celestial map and position sensors north. Few know where on Earth it actu- (up and north), determine the shortest ally points because it is constantly in route and guide your movement toward motion. Presently, it is located in north- the object of interest. One or more of the ern Canada and it is moving northwest LEDs are illuminated to gently direct the

Gravitational 32-bit ARM processor sensors SDRAM

A/D Flash

Magnetic sensors GPS

Audio Stereo DAC Brightness playback

“Locate” indicator SD/MMC LEDs Socket

Contrast control Keypad Brightness Keypad LEDs LCD USB LED Backlight interface

Temperature Power supply - 2 Battery level sensor “AA” detect

Figure 5—This block diagram shows what peripherals support the ARM processor’s bid to make one of the most user-friendly, high-tech, educational instruments to be developed in recent years. The SkyScout rivals the iPhone for cool.

74 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 27803002-Bachiochi.qxp 2/7/2008 10:13 AM Page 75

user toward the destination (see sensor technology and provide a Figure 4). Because the SkyScout simple solution to a complicated senses magnetism and accelera- problem. The SkyScout is a per- tion in all three axes, the proces- fect example of how individual sor can continue to calculate the advances can be combined to correct direction independently provide a solution that was once of how you are holding the Sky- unthinkable. Scout. Object identification and While combining the proper location will work night or day electronic components in the and even through the Earth, as if right packaging provides a solu- the sun and Earth don’t exist. tion, a convoluted user interface Although we can’t “see” objects Photo 3—The LED direction ring has been removed from the sighting can ruin an otherwise great during daylight or on the opposite tube slot on the left. The GPS module is mounted beneath the right PCB. product. The ultimate interface The GPS patch antenna can be seen on the topside of the PCB along side of the Earth, the fact that the requires no “user’s manual.” As with the membrane Target button. SkyScout points there reinforces designers, we need to pay as the fact that just because we can’t much attention to the basic con- see it doesn’t mean it’s not there. text of astronomical facts (about cepts of the design as we do to coding To provide the SkyScout with the nec- astronomers, man-made objects, comets, the algorithms within. Can you say, essary computational power, the design and asteroids) and a glossary. The guide “iPhone”? I was built around Samsung’s S3C24310, includes a six-part audio guide to astron- an ARM9 series 32-bit processor. The omy and narrations or text descriptions Author’s note: Special thanks to Mike device supports plenty of goodies, includ- and scientific data of approximately Lemp, the architect and father of the ing USB, LCD, and SD interfacing (see 200 objects. The SD card interface per- SkyScout. Figure 5). The total design is based on mits expanding its knowledge bank. Jeff Bachiochi (pronounced BAH-key- three PCBs, GPS, an LED directional One of the typical improvements to AH-key) has been writing for Circuit ring, and the main processor board. newer embedded designs is the ability Cellar since 1988. His background Photo 3 shows the LED directional ring to update the operation system with- includes product design and manufac- (removed from its slot in the sight tube) out major surgery. The processor’s turing. He may be reached through the and the GPS board (with the GPS patch integrated slave USB port supports magazine (jeff.bachiochi@circuitcellar. antenna showing). The main board holds updates to the SkyScout. com) or his web site(www.imaginethat most of the other components with the now.com). opposite side saved for the LCD and FRIENDLY SKIES membrane push buttons (see Photo 4). A Except for picking out “the big dip- RESOURCES USB and headphone jack can be seen on per,” most of us must plead ignorance to the left and an SD card slot to the right. much of what’s out there. While loca- J. Bachiochi, “Car 54, Where (Exactly) tion information of celestial objects is Are You?: Adding E-Mail Capabilities to EMBEDDED EDUCATIONAL well documented, it requires a clock and Your Project,” Circuit Cellar 127, 2001. The SkyScout’s ARM processor puts calendar (time and date), a map of the ———, “Magneto-Inductive Direction its power to good use in providing real- world (location), a compass (direction of Finding,” Circuit Cellar 80, 1997. time calculations as its sensor arrays north), and a protractor (for azimuth) to indicate a continually changing position. calculate where and when to look. This ———, “What’s the Slope?: Use an But its expertise doesn’t stop there. Inte- complexity scares off most people who Accelerometer to Measure Slope,” grated SD card slot and stereo DAC might otherwise enjoy knowing more Circuit Cellar 202, 2007. interfaces add to the design features. The about the night sky. Our success as ———, “Where’s Waldo?: Pinpointing SkyScout’s internal field guide provides designers depends on our ability to take Location by Interfacing with a GPS Receiver,” Circuit Cellar 126, 2001. National Marine Electronics Associa- tion (NMEA), www.nmea.org.

SOURCES SkyScout Celestron www.celestron.com S3C24310 Evaluation board Photo 4—The main PCB contains most of the electronics including the Samsung 32-bit processor, the magnetic Samsung and accelerometer sensors, and all of the support circuitry. www.samsung.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 75 2803013 martin.qxp 2/8/2008 1:14 PM Page 76

LESSONS FROM THE TRENCHES by George Martin Do You Want to Do a Design? Linked Lists After months of learning C, it’s time to apply what you’ve learned in a real-world application. George explains how to tackle a real design problem from start to finish.

For more about C language and writing That means that we can not detect 9,,,18005551212,,123 (20 INT8s). Where code, visit George Martin’s blog, CCI activities or conditions such as dial the “,” indicates a pause. So, in my C Programming Design Review, at http://ccidesignreview.wordpress.com/. tone, ringing, or call answered. I sug- example we’re dialing 9, pausing three Code and additional files are also gest that we use timers in a state units, dialing a 1-800 number, then available on the Circuit Cellar FTP site. machine design to pace the code pausing two units, and then dialing through the calling process. We can extension 123. I think that should assume certain times for each of the cover just about any dialing issue that states of the telephone line interface. might come up. You’ve been learning C for a while Because we’re calling friendly users This design uses MAX_GROUPS × now. Hopefully, you can read and (their numbers have been determined MAX_NUMB × MAX_DIGITS = 10 × 4 × write C code. This month, I would to be available for calling), this should 25 = 1,000 bytes of memory. That data like to take a real design problem from be acceptable. The detail of interfacing needs to be saved in a nonvolatile the beginning to the end. Along the with the PBX hardware is very memory area so that it’s preserved way we’ll create a design, make design dependent on the specific interface. between power outages. That non- trade-offs, accept changes, and code With your indulgence, I would like to volatile type of memory is usually the design. This should be interesting. skip over this part of the design. Your EEPROM and it is more expensive and interface will most likely be different smaller than RAM or EPROM. So, we DESIGN CHALLENGE than mine, and you’ll need to match need to use it wisely. I think this A few months ago, a customer your software design to your calling design meets those requirements. asked if I would add a feature to their hardware (see Listing 1). Great, I wrote up this design approach product. The customer wanted me to Also, we need a way to enter the and was ready to start. Not so fast. The have their product call out using the numbers to dial for each of the prob- customer called and asked if we could telephone interface whenever a prob- lem types that we can detect. And I also handle 30 events with only one lem was detected. The design already would add a log file to log the activity. number for each event. Well, of course had a PBX interface that passed FCC I would like to have a record that we we could, but how? If we extend the Part 68. The PBX interface was used tried to call and no one answered or present design, MAX_GROUPS becomes to permit a user to call the unit and we could not get a free line. 30 and MAX_GROUPS × MAX_NUMB × enter commands. After a few more MAX_DIGITS = 30 × 4 × 25 = 3,000 bytes discussions, the customer thought DATABASE DESIGN of memory. In the second design that there might be 10 events that The internal database would look request, we would be using one of the would cause a call out to be initiated like this: four available numbers (25%), and in and that there should be four tele- the original design we would be using phone numbers to dial for each of the INT8 DialOut[MAX_GROUPS][MAX_NUMB] 10 of the 30 groups (33%). Neither is 10 events. The numbers would be [MAX_DIGITS]; using these valuable resources very dialed and a message played to the well and I bet the customer will come user. If the user entered the proper Database design is really straightfor- up with alternative requests that lead response, the error event would be ward. It’s just one large array of 8-bit to ever more inefficient EEPROM considered reported; if not, the next entities indexed by groups (type of error usage. This is a perfect opportunity to number would be called. detected) and the digits in the telephone try linked lists. This is a straightforward design and number. MAX_GROUPS is defined as 10, coding task, but some issues need to be MAX_NUMB as 4, and I’m going to USE A LINKED LIST looked at. First, the hardware interface define MAX_DIGITS as 25. That should Wikipedia describes a linked list as does not have call progress monitoring. be large enough to dial numbers like “one of the fundamental data structures,

76 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803013 martin.qxp 2/8/2008 1:14 PM Page 77

an indication of that condition. Listing 1—This is pseudocode of the problem of dialing out. Because we have only 10 (from the Detect a problem. first statement of the problem) or 30 If the problem has not been reported and acknowledged (from the second request) possible Try to get Outgoing Line numbers to call, we can use 8-bit If Successful entities for this array. Table 1 shows Dial 1st Number the array contents. Wait for connection Send Message INT8 CallOutGroup[MAX_GROUPS]; Wait for Acknowledge If Acknowledge is received Next, we’ll build a structure con- Mark problem as reported and acknowledged Else taining the digits to dial and a linkage Dial 2nd number to the next possible number (in this Wait for connection structure) to try to dial. And again a Send Message –1 will indicate we’ve come to the end Wait for Acknowledge of the numbers to try (see Table 2). If Acknowledge is received Mark problem as reported and acknowledged Struct CALL_OUT_NUMBERS { // define Else // the structure Dial 3rd number INT8 DialNumb[MAX_DIGITS]; Wait for connection INT8 NextNumb; Send Message }; Wait for Acknowledge If Acknowledge is received struct CallOutNumbs[MAX_NUMBERS]; Mark problem as reported and acknowledged // reserve memory Else Dial 4th number Look at Tables 1 and 2. And remem- Wait for connection ber C arrays start at 0. The first entry Send Message DialNumber[0] is empty (–1). The Wait for Acknowledge second number 1-800-555-1212 is If Acknowledge is received located at DialNumber[1]. If that Mark problem as reported and acknowledged number is dialed and we get no If not acknowledged Repeat the above process N times response, we should try the number Once problem is acknowledged mark it as reported. DialNumber[2]. If that number (1-800- When Problem goes away clear the reported flag. 555-1111) is dialed and we get no response, we should dial the number DialNumber[3]. If that number (1-800- and can be used to implement other more information. 555-2222) is dialed and we get no data structures. It consists of a We’re going to use a single linked response, that is the end of the sequence sequence of nodes, each containing list. Each node will have a number to of numbers and we should start the arbitrary data fields and one or two dial and a linkage pointing to the next calling out from the first number. references (‘links’) pointing to the next number. You will typically see mal- Hopefully, you can see that an event and/or previous nodes.”[1] Stanford loc() used in Linked list C examples starts the process by looking up the first University has a great tutorial on the for claiming memory for the lists. number using the CallOutGroup[] subject and a good set of problems Because we’re dealing with an embed- array. From then on, the CallOutNumbs with C code solutions. Refer to the ded system, we’re not going to use [] structure defines the number and Resources section of this article for malloc() to allocate memory for our the next number if there is one. This usage. We’re just going to assign a suf- ficiently large amount of memory to Call out group First number to call hold our data structures. If we need Index DialNumb [MAX_DIGITS] NextNumb 0 –1 (empty) more in the future, it’s just one 0 –1 (empty) –1 (empty) 11#define to change and recompile. And 1 1.8005551212 2 23remember that this memory is EEP- 2 1.8005551111 3 3 –1 (empty) ROM and it’s valuable, so we’re trying 3 1.8005552222 –1 (empty) ——to use it wisely. 4 –1 (empty) –1 (empty) 29 –1 (empty) First, we’ll build an array for each —— — of the call out groups that contain 39 –1 (empty) –1 (empty) Table 1—This is an array of the first numbers to try to call. An entry of –1 indicated an empty number. the first number to try to call. If no Table 2—This is the linked list for our call out Remember the array indexing in C starts at 0. number is entered, we’ll use a –1 as sequences. –1 indicates an empty entry.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 77 2803013 martin.qxp 2/8/2008 1:14 PM Page 78

over two sessions to get the CallOut code written and debugged. The file TestLinkList.c holds the main() routine and runs the test code. I created a file CalOutReports.c to generate printout type routines. These routines report the data in our internal elements out the DOS Figure 1—This is the UML case diagram for the initial design of the call out code. window for your viewing. And remember that you can pipe the output into a file for hard is a classic forward-linked list. And AddCallOutGroupNumb(); appends a copy documentation purposes. I have a you can also see that it is efficient in number to the end of the call out copy of that file (report.txt) in the files memory usage. More callout events group. It takes the group number and a area. I also created a CCILinkedlist.h linearly increase the size of the Call pointer to the string of digits to dial. It header file to hold system constants. OutGroup[] array. And more num- returns no parameters. DeleteCallOut So the meat of the solution is con- bers to call linearly increase the size Group(); deletes all of the numbers tained in the files CalOut.c and of the CallOutNumbs[] structure. in a call out group. It takes the group CalOut.h. Note that a better name for number and returns nothing. GetNext these files would be CallOut.c and .h. DESIGN IMPLEMENTATION CallOutNumber() takes the current That’s part of a review process and So we now have a design. Let’s look call out number and looks to see if more on that later. at what we need to implement that there is a next number to dial. If so, it If we look into CalOut.c, we’ll see design. I’m going to present the rou- returns that next number. If not, it the routines contained in the UML tines required using UML diagrams. returns –1. class diagram (see Table 3). Refer to the Resources section for Cir- The question to ask ourselves at Most of our original design had no cuit Cellar articles about UML. UML this point is this: can we complete the change. One is deleted and some are has several diagrams to describe a sys- design with these routines? Let’s see. added. What’s the story? The real tem: class diagrams, use case dia- We need to initialize the CallOut data world. As I was implementing the grams, collaboration diagrams, state elements probably at the factory. Per- code, I saw problems with the design, diagrams, activity diagrams, and haps we’ll give the user a means to easier ways to perform a task, or miss- implementation diagrams. Let’s start delete all the numbers. Then we need ing elements. with the case diagram of the operations to delete a particular group, add num- Look at FindFreeNumber. I need to for the call out design (see Figure 1). bers to a group, and get the numbers look through the struct CallOutNumbs[] I defined a class named CallOut. in order for a group. Looks like we’ve to find a free spot to save a new number Don’t worry, we’re not getting into got it covered. to. “Well, of course,” you might say, object-oriented programming (not just So, I sat down at the keyboard and but it escaped us at the initial design yet, he says, laughing hysterically). fired up Borland’s C++ BuilderX on a point. That one is not a big deal. But I would put all the call out code in PC. I’ve discussed this program in ear- Next, look at the missing GetNext a file named CallOut.c. The CallOut.c lier articles. I created a new console CallOutNumber();, which is file (class) has two static (think of application. I’m going to use a DOS replaced with the two routines INT8 them as private) variables and they are window to create and run a test pro- GetFirstCallOutNumberIndex(INT listed in the block below the name of gram to exercise the routines we’ve 8 Grp); and INT8 GetNextCallOut the class. And the routines or proce- just designed. Nothing fancy here. It NumberIndex(INT8 Idx);. If you dures of the class are listed in the next took me about four hours spread out consider how the database is designed, block. I also added a note that we first need to look into the you see attached to the class INT8 CallOutGroup[] array Routines Changes design. to see if there is a first num- InitCallOutGroup(); No change Let’s look into the routines ber entered or if the group is InitCallOutNumbsStruct(); No change as they are defined right now. empty. If there is a number, DeleteCallOutGroup(); No change InitCallOutGroup(); ini- we can start using the for- tializes the CallOutGroup. It void FindFreeNumber(void); New ward linkages to keep finding takes no parameters and void AddCallOutGroupNumb(INT8 Grp, INT8 *s) ; No change the next number in the returns no parameters. Init GetNextCallOutNumber(); Deleted group. So we really needed CallOutNumbsStruct(); INT8 GetFirstCallOutNumberIndex(INT8 Grp); New this change, but it could cre- initializes the CallOutNumbs INT8 GetNextCallOutNumberIndex(INT8 Idx) ; New ate other problems in the sys- structure. It takes no parame- Table 3—Here’s a list of the routines in the final version of the code and an indication tem. Once again, these are ters and returns no parameters. of what’s added, deleted, and changed. the type of real-world issues

78 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803013 martin.qxp 2/8/2008 1:14 PM Page 79

that you come across. Now the next PROJECT FILES Cycle,” Circuit Cellar Online 123, step is to redo the UML diagrams to 2000. To download code, go to ftp://ftp.circuit keep them current with the tested cellar.com/pub/Circuit_Cellar/2008/212. M. Manca, “Finite Machines and design. I’ll leave that up to you. Microthreads,” Circuit Cellar 193, REFERENCES 2006. CODE REVIEW [1] Wikipedia, “Linked list,” 2007, N. Parlante, “Linked List Basics,” The design is coded and tested. The http://en.wikipedia.org/wiki/ test cases and results are in the file Linked_list. Stanford CS Education Library, 2001, LinkListReport.txt. The next step is http://cslibrary.stanford.edu/103/ [2] Wikipedia, “Code review,” 2007, LinkedListBasics.pdf. for a code review. What’s a code http://en.wikipedia.org/wiki/Code_ review? Well, Wikipedia says: “Code review. ———, “Linked List Problems,” Stan- review is systematic examination RESOURCES ford CS Education Library, 2002, (often as peer review) of computer http://cslibrary.stanford.edu/105/ source code intended to find and fix V. Kosuri, “UML in a Product’s Life LinkedListProblems.pdf. mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills.”[2] Let’s have a code review. I’ll start it. What happens if a string, longer than the permissible size, is some- how entered for the number to dial? Should we protect against that event? How? What happens if a group number less than 0 or greater than the maxi- mum is entered? Should we protect against that event? How? You get the picture. Do a code review and post your comments on the blog I’ve created for this design review: CCI C Programming Design Review (http://ccidesignreview.word press.com/). Then we’ll keep that active and see where it takes us. Let’s go. Don’t put it off any longer. Next time, let’s look deeper into compiler output. We’ll take apart the C compiler generated code. Sounds like fun. See you next time. I

George Martin (gmartin@circuitcellar. com) began his career in the aero- space 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 servo-motion control, graphi- cal input and output, data acquisi- tion, and remote control systems. George is a charter member of the Ciarcia Design Works Team. He’s cur- rently working on a mobile communi- cations system that announces high- way info. He is a nationally ranked revolver shooter.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 79 2803003-Cantrell.qxp 2/8/2008 1:16 PM Page 80

SILICON UPDATE by Tom Cantrell

More Bits, Less Filling Tom is a proponent of the 32-bit MCU revolution. This month, he covers several respectable 32-bit chips that deliver performance at a reasonable price. Exciting new applications are on your horizon.

Long-time readers have heard me and a microprocessor (MPU)? Obviously, there are gray areas. The tell the story of the IC company exec- In the old days, the answer was pret- dividing line between “big-ticket” and utive who tried to convince me that ty simple. If a chip had onboard mem- “little-ticket” software can be blurry. the 8-bit market was “dead.” The ory and I/O enabling it to run stand- For example, the term “RTOS” kicker is that he made that statement alone as a “single chip,” it was an encompasses everything from a tiny 25 years (and many billions of 8-bit MCU. Otherwise (i.e., external memo- scheduler that fits in a few kilobytes MCUs) ago. ry and I/O), it was an MPU. End of story. to a full-featured OS with megs of Indeed, as far as I’m concerned the As a practical matter, for a long time, code supporting a GUI, networking 8-bit market will still be going strong you could safely say MCUs were general- stack, file system, and more. uCLinux in another 25 years. True, it may not ly “8-bit” and virtually all “32-bit” and Microsoft’s .NET come to mind as be as much about new applications chips were MPUs. That simple “sin- “computer-in-drag” software that can anymore. But don’t underestimate the gle-chip” criteria is still pretty valid, run on an MCU. fact there are billions of folks around but obviously, the business about “bit- Nevertheless, you’ve got to draw the globe who have a lot of catching ness” has changed. the line in the silicon somewhere. At up to do gadget-wise. There are plenty Of late, I’ve adopted a more soft- least for now, when I refer to an MCU, of unfilled sockets for 8-bitters. ware-centric approach to the question. you’ll know what I’m talking about. That being said, I’ve also been a These days, I divide the world into cheerleader for the 32-bit MCU revo- two camps. If a chip is designed to run ARMs RACE lution. These are the chips that deliv- big-ticket software such as Windows, ARM MCUs are unique among all of er performance at a price that enables Windows CE, Linux, and more, it’s an the others by virtue of their “open archi- exciting new applications. MPU. If it isn’t, it’s an MCU. tecture” with a bandwagon of licensees, Increasingly, software is parts, and third-party sup- what makes or breaks a porters that’s rolling so fast product, and 32-bit chips it’s hard to keep up. Give can tote the code. NXP Semiconductors (under Whether high-end or their former guise as Philips low, the market for MCUs Semiconductors) credit for isn’t a zero-sum game (see being first to shatter the Figure 1). As long as myth that 32-bit chips are Moore’s law keeps deliver- only for “high-end” designs ing more for less, there (see Photo 1). A chip like will be plenty of sockets to their LPC2101 may have a go around for everybody. 32-bit ARM7 core, but other- wise, it is remarkably MCU VS. MPU streamlined with just 8 KB The emergence of the 2003 2004 2005 2006 2007 of flash memory, 2 KB of

latest generation of 32-bit 8-bit 16-bit 32-bit RAM, and a small 48-pin chips once again raises the package. question of just what’s the Figure 1—Development tool sales are a good leading indicator of design trends. Today, Now NXP is making 8- and 16-bit MCUs still dominate unit shipments and indeed designs continue apace. difference between a But as this sales data from tool supplier IAR Systems Software shows, 32-bit MCUs are moves at the high end, microcontroller (MCU) where tomorrow’s action is. notably via their recent

80 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803003-Cantrell.qxp 2/8/2008 1:16 PM Page 81

acquisition of Sharp’s stacked die approach for integrat- “Bluestreak” product line. ing memory on their MCUs. The Bluestreak parts like the ARM9- virtue of this multi-chip-in-pack- based LH7A00 bring LCD appli- age strategy can be debated, but cations into the mix with a built- there’s no doubt that it’s the way in display controller, frame to go if you want a lot of memo- buffer, and interface. ry. Software bloat getting you NXP has also rolled out their down? Relief is just an AT91 own home-grown ARM9-based MCU (with up to 2 MB of flash LPC3000 line starting with the memory and 256 KB of SRAM) 90-nm, 208-MHz, 320-pin, vector away. floating-point LPC3180. The MCU business isn’t for the Per the earlier discussion, these faint of heart, and it is dominated parts are really MPUs. They don’t by companies with decades of lead- have the flash needed for single- ership. Conventional wisdom chip operation, but they include would say the idea of starting a “computer” features (e.g., virtual new MCU company this late in the memory MMU, cache, a high- game is iffy at best. It’s testimony speed external bus, and more) that to the momentum behind ARM can handle operating systems like that the introduction of their latest Windows CE and Linux. But never Photo 1—Check out this cool gadget using an NXP ARM7-based and greatest Cortex M3 MCU core fear, NXP is filling the high-end LPC2119 MCU. Remember when “32 bits” was a big deal? It’s still a spawned a new MCU company, big deal in terms of exploding growth and new applications, but this MCU gap with their ARM9-based namely Luminary Micro. time it’s a big deal that comes in a single, tiny package. LPC2900 series. These strip out the Like pregnancy, being “kind of” MPU features and replace them in the MCU business isn’t an with flash memory to deliver a high- like NXP, offers a full catalog of option. Dribbling out a part or two performance single-chip solution. MCUs (ARM7) and MPUs (ARM9). while watching the cash gauge bounce is another powerhouse that, However, unlike NXP, Atmel uses a on “E” won’t cut it. Fortunately for

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 81 82.qxp 2/1/2008 11:05 AM Page 1

LEARN TODAY. DESIGN TOMORROW.

Conference: April 14 – 18, 2008 Expo: April 15 – 17, 2008 McEnery Convention Center, San Jose, CA

Embedded Systems Conference Silicon Valley delivers a comprehensive technical program focusing on 15+ critical topics that affect your designs. Learn how to solve your engineering issues today.

register today at www.embedded.com/esc/sv 2803003-Cantrell.qxp 2/8/2008 1:16 PM Page 83

Luminary, their backers appear to need the full MMU Flash size STM32F103CB STM32F103RB STM32F103VB have the means and will to make a go baggage but still 20-KB RAM 20-KB RAM 20-KB RAM of it. They shot out of the starting want some protec- 128 KB STM32F101CB STM32F101RB STM32F101VB gate with a complete line-up of gener- tion, synthesis 16-KB RAM 16-KB RAM 16-KB RAM al-purpose MCUs ranging from the alternatives include STM32F103T8 STM32F103C8 STM32F103R8 STM32F103V8 such-a-deal $1 LM3S101 (8 KB of flash basic 20-KB RAM 20-KB RAM 20-KB RAM 20-KB RAM memory, 2 KB of SRAM, 28-pin) to the USER/SUPERVI- 64 KB STM32F101T8 STM32F101C8 STM32F101R8 STM32F101V8 LM3S1968 (256 KB of flash memory, SOR protection and 10-KB RAM 10-KB RAM 10-KB RAM 10-KB RAM 64 KB of SRAM, 100-pin). Now, a limited hardware STM32F103T6 STM32F103C6 STM32F103R6 they’ve virtually doubled the size of (i.e., no virtual 10-KB RAM 10-KB RAM 10-KB RAM 32 KB their portfolio with a second wave of memory) “memory STM32F101T6 STM32F101C6 STM32F101R6 parts tailored for Ethernet, CAN, and protection unit” 6-KB RAM 6-KB RAM 6-KB RAM motor control applications. (see Table 1). 36 pins 48 pins 64 pins 100 pins Another notch in ARM’s Cortex-M3 The ability to QFN LQFP LQFP LQFP/BGA belt comes from STMicroelectronics, trade-off price, who have added the core to their exten- power, and per- Figure 2—Right out of the gate, STMicroelectronics offers more than a dozen Cortex M3-based STM32 MCUs divided into the “Access” (i.e., 36-MHz, low-cost) and sive line-up of MCUs. Make no mistake formance is key to “Performance” (72 MHz with USB and CAN) lines. But that’s not all. Parts with more that ST is a major player with a lot of the soft-core con- flash memory (e.g., 512 KB) and more pins (e.g., 144) are already in the works. weight to throw around, and it shows in cept. For example, the initial strength of their product the Nios II core comes in three it comes to embedded, the old ways are offering and third-party bandwagon (see “flavors” (fast, standard, and econo- usually the good (enough) ways. Figure 2). Chips on the table range from my), giving designers the flexibility to The latest “V1” version of Coldfire 32 KB of flash memory and 36 pins, to optimize for a wide range of different cuts the fat to compete in the low-end 128 KB of flash memory and 100 pins, applications. Flexibility also extends “buck and change” segment, which is with 512 KB and 144 pins in the to implementation options with Altera where growth is really exploding. For works. Support comes from a who’s- and collaborating to offer less than $2 (10K quantity), you can get who of tool suppliers, including Keil NIOS II for real ASIC designs. I guess a chip that delivers nearly 50 MIPS while (now owned by ARM), Hitex that makes it a hard-core soft core. consuming only 50 mW (e.g., 27 mA at Development Tools, Raisonance, and 1.8 V). We’re not talking about a IAR Systems, just to name a few. “V” stripped-down loss leader either. There’s The name is different and the iconic 32 KB of flash memory, 8 KB of RAM, SOFT PARADE batwing logo is gone, but Freescale and plenty of upscale I/O including 20- Designers have an abundance of Semiconductor carries forward the channel 12-bit ADC, two each SCI, I2C, standard MCUs to choose from for historic embedded leadership of SPI, and up to 54 general-purpose I/Os. middle-of-the-road applications. At Motorola. Over the years, Motorola Another interesting move is what the other extreme, ultra-high-volume seemingly never met a 32-bit architec- Freescale calls their “controller con- products may call for a custom ASIC. ture they didn’t love. There was tinuum” strategy (see Figure 3). The Filling the gap are soft-core processors 68K/Coldfire, PowerPC, ARM, M- idea is to ease upward and downward running on FPGAs (i.e., a roll-your- Core, and 88K, not to mention DSPs. migration across their entire 8-, 16-, own SoC solution). Except for the 88K (lived fast, died and 32-bit line-up. The linkage is Leaving no socket unturned, ARM young), these all soldier on under the established with bridge-the-gap parts is making their own soft-core moves Freescale banner. But Coldfire is the that use different cores (e.g., one chip by working with to deliver core that Freescale expects to do the using an ’S08, the other a Coldfire V1) ARM7 capability in flash-based heavy lifting when it comes to general- but otherwise offer exactly the same FPGAs. Just recently, the duo purpose MCU applications. While the I/O, package, and pinout. announced a new, more streamlined chip name may have changed, the fam- Cortex-M1 core that cuts the gate ily resemblance of Coldfire to the ven- PRESCRIPTION FOR CHANGE count and power consumption, factors erable Motorola 68K is no coincidence. Did you know that Renesas that are always a consideration with Designers have made it clear that when Technology has shipped a billion FPGAs. flash MCUs? Don’t For their part, Virtex-5 Resources Spartan-3 Resources apologize if you didn’t. is boosting aspirations (MMU) 910 LUTs, 1 Block RAM 1,100 LUTs, 1 Block RAM The fact is, much of for their Microblaze core (MPU) 560 LUTs, 1 Block RAM 670 LUTs, 1 Block RAM the volume is concen- with the addition of a User/Supervisor Privilege 34 LUTs 38 LUTs trated in giant, but full-fledged Windows CE hidden, applications and Linux-capable MMU Table 1—With the addition of virtual-memory MMU, the Xilinx Microblaze soft core joins the such as automotive. ranks of Windows CE and Linux-compatible MPUs. Of course, the raison d’etre for an FPGA soft to the architecture. For core is the flexibility to jettison baggage if you don’t need it. So, simpler memory management Most of their business applications that don’t solutions are an option. is figuratively, not to

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 83 2803003-Cantrell.qxp 2/8/2008 1:16 PM Page 84

mention literally, “under Colors indicate versus Reality” face-offs the hood.” pin/peripheral compatibility where traditional RISC ColdFire ColdFire General purpose It’s true that a lot of ColdFire LCD Controller theology blinks first. Renesas MCUs reach the ColdFire For instance, in their S08 ColdFire general-purpose mass mar- USB Enabled CAN Device quest for brutal simplici- S08 ket, but the success is General purpose S08 ty, old-timey RISCs were LCD Controller spread across a catalog known for “Relegating S08 S08 bursting with decades USB Enabled CAN Device Impossible Stuff to the worth of legacy parts hand- Compiler.” Indeed, the ed down from Hitachi and 2007 2008 “MIPS” moniker is said Mitsubishi. To be fair, the to have stood for line-up is pretty coherent at Figure 3—Freescale Semiconductor bridges the gap between 8-bit and 32-bit designs by “Microprocessor without giving otherwise pin- and I/O-compatible parts a brain transplant. the low end (e.g., entry- Interlocking Pipeline level H8s) and the high end Stages.” Instead of hard- (SuperH). It’s in between where position- and faster silicon) doesn’t nearly justi- ware interlocks, the idea was to have the ing gets tricky with high-line H8s and fy the cost in terms of wasted code compiler schedule around hazards by middle-of-the-road M16s and M32s all space and bus bandwidth. moving instructions, inserting NOPs, jostling for the same sockets. So we went from fixed-length 32-bit and so on. So, I have to smile now that Enter the new “RX” family, which is instructions to adding “modes” (e.g., I see in the PIC32 datasheet that said to stand for “Renesas Extreme.” Thumb and MIPS16) that carved out a “Pipeline interruptions are handled Frankly, it’s also the Rx for marketing subset of leaner 16-bit instructions. entirely in hardware.” indigestion brought on by architectural More recently, we see Cortex M3 with Another example is interrupts—or overindulgence. RX is said to offer big- native 16- and 32-bit instructions. rather, in the case of the original MIPS tent compatibility and an upgrade path RX goes even further with a byte- design, lack of same. As I recall, soft- for all the existing mid-range parts. For variable instruction length that encodes ware was expected to handle nearly example, there’s explicit “bi-Endian” the most frequently used instructions every aspect of interrupt processing, support to accommodate the “big in the least amount of bits. That’s a with the chip doing little more than Endian” and “little Endian” parts in the great idea—just like it always was. stacking the PC and status word in a current line-up (see Figure 4). single-deep backup register. Want to Technically, what I’ve seen of RX so MIPS FOR THE MASSES know where the interrupt came from? far makes sense to me. Notably, I give The icing on the 32-bit MCU cake Use software. Want to handle nested Renesas credit for calling a spade a comes from Microchip Technology. interrupts? Use software. Want to imple- spade—or, in this case, a CISC. Most Say hello to the MIPS-based PIC32 ment priority? Use software. By con- marketeers still call their chips RISCs, (see Figure 5). trast, the “Rev.2” variant of the archi- although at this point, virtually every This is an interesting announcement tecture used in PIC32 has an altogether distinguishing characteristic of the on a number of levels. From Microchip’s modern vectored interrupt capability original concept has fallen out of favor. perspective, a MIPS deal gives them a and even a spare register set dedicated to Take the issue of instruction encod- credible and expedient alternative to a the cause of exception processing. ing, with fashion having changed “me too” ARM or “hard sell” propri- There are plenty of other tweaks. For faster than hemlines. The original etary core strategy. Meanwhile, MIPS instance, just toggling a bit on the early RISC concept insisted on fixed-length gets to expand their presence beyond the RISCs required a 32-bit load/mask/store 32-bit instructions. Although sellable ASIC business into the merchant MCU sequence. Not only is this wasteful in at the time, I always thought it was a market. That’s not just an upside for many ways, it’s also slow and subject to goofy idea. Spend 32 bits to increment their bottom line, but a must to boost glitches due to the fact it takes multiple a register, compare to zero, do a short their long-term prospects for architec- cycles (i.e., updates are “non-atomic”). branch? It wasn’t long before folks real- tural staying power. PIC32 brute-forces the traditional RISC ized the ostensible benefit of a 32-bit I haven’t followed the MIPS archi- bit I/O problem away by supplementing fixed-length instruction (slightly simpler tecture closely because it’s pretty each peripheral register with three other much been positioned as an registers dedicated to setting, clearing, ASIC-only option. Skimming and inverting bits (see Figure 6). Rs Rd the datasheet, I can see that REVL Rs, Rd A B C D➠ D C B A from high altitude, PIC32 cer- THAT’S NOT ALL FOLKS tainly resembles the MIPS I’ve touched on half a dozen eminent- REVW Rs, Rd A B C D ➠ B A D C chips of yore (e.g., R3000 and ly respectable 32-bit architectures com- R4000). But look a little more prising hundreds of parts supplied by a Figure 4—Providing an upgrade path for a myriad of legacy MCUs closely and you’ll find evi- top-tier list of global IC powerhouses. is the challenge for the forthcoming Renesas Technology RX MCU. Doing so starts with the basics, namely the ability to handle data in dence of the changing times. Could you ask for anything more? Of big or little Endian format. There are clearly some “RISC course, when it comes to silicon, it

84 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803003-Cantrell.qxp 2/8/2008 1:16 PM Page 85

I Stage E Stage M Stage A Stage W Stage

A to E Bypass M to E Bypass Reg File Rs Addr Rs Read Instruction ALU ALU Rt Addr M Stage E Stage Rd Write Rt Read

Bypass Load data, HI/LO data or CP0 data

Figure 5—At the heart of the PIC32 is a powerful MIPS core with performance-oriented features, including pre- fetch cache, virtual memory MMU, and a high-speed math . The sophisticated-for-an-MCU five-stage pipeline reduces stalls by forwarding results directly to waiting stages.

doesn’t matter if you ask because Tom Cantrell has been working on you’re getting it anyway. chip, board, and systems design and There’s a whole parallel universe of marketing for several years. You may DSPs that are a must for the most reach him by e-mail at tom.cantrell@ signal-centric applications. However, circuitcellar.com. PRESTO all the DSP suppliers (e.g., Analog The First USB In-Circuit Devices, Freescale, and TI) have been SOURCES Multipurpose Programmer working hard to offer chips that are Cortex M1 Soft-core FPGA more MCU-like, both in terms of Actel Corp. hardware features (e.g., flash and I/O) www.actel.com and development environment (“C,” NIOS II Soft-core FPGA RTOS, and debug). If you’re up for an Altera Corp. ASIC, there are custom cores from www.altera.com Very fast and flexible in-system the likes of MIPS, ARC, and programmer for many devices: CAP Metal-mask programmable SoC Tensilica. Then there’s multicore, x Atmel AVR, 8051 architecture Atmel Corp. where you’ve got everything from a x Microchip PIC, dsPIC, rfPIC, ... www.atmel.com x $10 Propeller chip to sci-fi parts with Texas Instruments MSP430 x hundreds of cores today, thousands Coldfire 32-bit Microcontroller ARM MCUs by Atmel, NXP (Philips) - including debugging tomorrow. Freescale Semiconductor, Inc. www.freescale.com x FPGAs, CPLDs & SCPs What a wonderful time to be an by Xilinx, Altera, Lattice, ... embedded designer. Combine these IDE, RTOS, and TCP/IP x Serial Flash, EEPROMs, ... new-age MCUs with other advances IAR Systems Software, Inc. (e.g., sensors, wireless, and Internet), www.iar.com SIGMA and the race for new applications is PIC32 Microcontroller Unique Logic Analyzer on. You’ve got some really strong Microchip Technology, Inc. horses to choose from. Now, it’s time With Extremely Large Memory www.microchip.com for more than 14,000,000 events, to ride. I LPC2900, LPC3000, and LPC3180 up to 16 inputs, up to 200 MHz Microcontrollers sampling, flexible triggering, ... Register address Peripheral register NXP Semiconductors ...and more Clear bits www.nxp.com Register address + 4 H8, RX, and SuperH Microcontrollers MU Beta - unique PIC emulator Set bits USB modules - parallel & serial Register address + 8 Renesas Technology Corp. SPINET - Ethernet-SPI interface Invert bits www.renesas.com Register address + 12 Development boards and kits, ... STM32 Microcontroller For developers by developers. Figure 6—In the beginning, RISCs were all about STMicroelectronics [email protected] reducing hardware by doing things in software. www.st.com [email protected] Unfortunately, that doesn’t work well for control tasks such as bit I/O. The solution, as embodied in the Microblaze soft-core FPGA PIC32, is simple: reduce software by doing things in Xilinx, Inc. hardware. www.xilinx.com tools.asix.net

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 85 ib-212.qxp 2/11/2008 10:43 AM Page 86 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet. ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. Call for current rate and deadline information. Send your disk and digital submission sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail [email protected]. For more information call Shannon Barraclough at (860) 875-2199.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/ is your guide to a variety of engineering products and services.

phyCORE® OEMable Single Board Computers UUSSBB XScale: PXA270, PXA255 Add USB to your next

ARM: LPC3180 (ARM9); LPC22xx, LPC229x, AT91 (ARM7) project—it’s easier than you

PowerPC: MPC5554, MPC5200B, MPC565, MPC555 might think! ColdFire: MCF5485 : Elan SC520 v USB-FIFO up to 8 mbps CAN C166/XC16x/ST10/8051 v USB-UART up to 3 mbps Blackfin: BF537 v USB/Microcontroller boards Faster-to-Market: Save time by integrating a PHYTEC Single pre-programmed with firmware Board Computer Module into your target circuitry. v 2.4GHz ZigBee™ & 802.15.4 Make -or - Buy: Why make your own when you can buy v RFID Reader/Writer PHYTEC off-shelf solutions, cost-effective to 1000s units/year? Absolutely NO driver software Integrated Support Services: Let PHYTEC assist you in the design of your end product: from tools and RTOSes to production. Our hardware is bundled with leading compilers (Keil, IAR, CodeWarrior), RTOSes (WinCE, development required! Linux) and debuggers. Immediate Support: Talk to PHYTEC technical staff with every call. No waiting for answers. www.dlpdesign.com Your OEM solution: With 20 years design, production, and integration experience, PHYTEC is your OEM partner.

PHYTEC America, LLC I 203 Parfitt Way SW, G100 I Bainbridge Island, WA 98110 USA www.phytec.com I (800) 278-9913 I www.phycore.com

86 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-212.qxp 2/11/2008 10:43 AM Page 87

Outsource Your Next Design To Ohio! Product Line Strategy Consulting Circuit Design and PCB Layout Electromechanical Algorithm Development Analog Design Wireless Simulation Embedded Software Rapid Prototype We specialize in designing with Microchip products

O’Keefe Electronics Inc. www.okeefe-electronics.com O’Keefe Electronics Inc. 440 647 5193

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 87 ib-212.qxp 2/11/2008 10:43 AM Page 88

LV- MaxSonar Ultrasonic Ranging is EZ actual size -Lowpower! 2.5V-5.5V, current 2mA -Tinysize! less than 1 cubic inch -Lowcost! -Choiceofbeampatterns. - Easy Interfacing. Serial, pulse width, & analog voltage outputs. - Reliable and stable range measurement. - No dead zone. Detect objects up to the front sensor face. For more info please visit us at www.maxbotix.com

Bargain LCD Scope!

Portable, benchtop 25Mhz 2-ch color LCD Scope. Download waveforms via USB1.1 to PC. 7.8" 640 x 480 Color LCD 3.5lbs. Sampling Rate 100 MS/s. Volt/Time Automatic Measurement Peak-to-peak Value, Average, RMS, Frequency and Cycle. FREE 1x/10x probes, USB cable. Compare with expensive LCD scopes!

PDS5022S $325! PDS5022S-BAT (Battery Powered) $399!

1-888-7SAELIG [email protected] www.saelig.com

88 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-212.qxp 2/11/2008 10:43 AM Page 89

Hundreds of complete embedded projects.

Start with www.circuitcellar.com/ microchip2007

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 89 ib-212.qxp 2/11/2008 10:44 AM Page 90

® ARM® 8051 COLDFIRE®

ARE Three quality tool suites q C/C++* q Code Wizards q Debugging q Simulation q Support * Embedded C++ for ARM and ColdFire only Advanced software tools since 1984 www.crossware.com Tools for Embedded Development Tools CROSSW 360-812-2397

90 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-212.qxp 2/11/2008 10:44 AM Page 91

ANYONE Can Now Easily Hand Solder Surface- Mount Components! Even A 10 Year Old!

www.schmartboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 91 ib-212.qxp 2/11/2008 10:44 AM Page 92

Order online at: Phone: (719) 520-5323 microEngineering Labs, Inc. Fax: (719) 520-1867 www.melabs.com ® Box 60039 Development Tools for PIC Microcontrollers Colorado Springs, CO 80960

® USB Programmer $89.95 LAB-X Experimenter Boards BASIC Compilers for PICmicro for PIC® MCUs (as shown) Pre-Assembled Boards Easy-To-Use BASIC Commands Available for 8, 14, 18, 28, Windows 9x/Me/2K/XP Interface RoHS and 40-pin PIC® MCUs PICBASIC™ Compiler $99.95 Compliant 2-line, 20-char LCD Module BASIC Stamp 1 Compatible Programs 9-pin Serial Port Supports most 14-bit Core PICs PIC MCUs Sample Programs Built-In Serial Comm Commands including Full Schematic Diagram low-voltage PICBASIC PRO™ Compiler $249.95 (3.3V) devices Pricing from $79.95 to $349.95 Supports Microchip PIC10, PIC12, PIC14, PIC16, PIC17, and PIC18 microcontrollers Includes ™ Direct Access to Internal Registers Windows PICPROTO Prototyping Boards Supports In-Line Assembly Language 98, Me, NT, With Accessories for $119.95: Interrupts in PICBASIC and Assembly 2K, and XP Includes Programmer, Software, USB Cable, Double-Sided with Plate-Thru Holes Built-In USB, I2C, RS-232 and More Software and Programming Adapter for 8 to 40-pin DIP. Circuitry for Power Supply and Clock Source Level Debugging Large Prototype Area Parallel Port Programmer Boards Available for Most PIC® MCUs See our full range of products, including starting at $59.95 Documentation and Schematic books, accessories, and components at: Serial Port Programmer Pricing from $8.95 to $19.95 www.melabs.com EPIC™ starting at $79.95

92 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 2/8/2008 1:29 PM Page 93

CROSSWORD

1

23

4 5

6 7

8

9 10

11

12 13

14

15 16

17

18

19

Down 1. Unofficial rules of conduct that regulate interaction and behavior on the Internet 2. The main material used in most semiconductors Across 3. Legal protection that enables the creator of original 6. A short description on a web site material to restrict the use and reproduction of 8. An instrument used to measure acceleration on a sensor his/her work 9. Created the Playfair cipher in 1854 4. A receiver/transmitter that decodes parallel data 12. A PC’s ’Net-connected location from a CPU into serial bits 15. Shaped like a spiral or coil 5. A datatype that has two values: “1” and “0” 16. A mobile electronic device that fits in your hand 7. This occurs when the operation of an entire system 17. Smoke produced by dysfunctional circuits is restricted by one component 18. Think: General Electric Research Lab, ductile tungsten, 10. A headphone and microphone system used to com- 1927 IEEE Edison Medal municate over a telephone 19. Project Genie began at this University of California campus 11. This type of “iron” refers to a fast supercomputer in 1964 13. The ancient Greek engineer, mathematician, and astronomer who was killed in Syracuse in 212 BC 14. Fi The answers are available at www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 212 March 2008 93 94-advertiser's index.qxp 2/12/2008 10:59 AM Page 94

INDEX OF ADVERTISERS The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page Page Page Page 91 AAG Electronica, LLC 88 FlexiPanel Ltd. 87 MCC (Micro Computer Control) 88 Saelig Co.

56 AP Circuits 88 FlyPCB China Co., Ltd. 88 MaxBotix Inc. 91 Schmartboard

85 ASIX 10 Front Panel Express LLC 90, 92 Micro Digital, Inc. 11 SEGGER Microcontroller Systems LLC

88 All Electronics Corp. 88 Futurlec 55 Microchip 92 Senix

89 Apex Embedded Systems 13 Geist Technology 92 microEngineering Labs, Inc. 21 Silicon Laboratorie, Inc.

7 Atmel 68 Grid Connect 95 Mouser Electronics 56, 91 Systronix

48 Bitscope Designs 87 Hagstrom Electronics 89 Mylydia, Inc. 92 TAL Technologies

65 CWAV 90 HI-TECH Software LLC C2 NetBurner C3 Tech Tools

79 CadSoft Computer, Inc. 74 HobbyLab LLC 3 Noritake Co., Inc. 91 Technical Solutions Inc.

10 Calao Systems 17 ICOP 67 Nurve Networks LLC 32, 33 Technologic Systems

41 Comfile Technology, Inc. 87 IMET 87 O’Keefe Electronics Inc. 90 Technological Arts

90 Crossware Products, Inc. 89 IMAGEcraft 81 PCB-Pool 89 Tern, Inc.

86 Custom Computer Services, Inc. 91 Intec Automation, Inc. C4 Parallax, Inc. 49 Tibbo Technology, Inc.

1 Cypress MicroSystems, Inc. 86 Ironwood Electronics 86 Phytec America LLC 87 Tin Can Tools, LLC

86 DLP Design 64, 91 JKmicrosystems, Inc. 39 Pico Technology Ltd USA 88 Trace Systems, Inc.

74 DMM Technology Corp. 2 Jameco 90 Picofab Inc. 90 Triangle Research Int’l, Inc.

85 Decade Engineering 67 Jeffrey Kerr, LLC 90 Pioneer Hill Software 71 Trinity College Robot Contest

87 Designnotes 5 Keil Software 40 Pololu Corp. 92 VANTEC

68 EMAC, Inc. 23 LPFK Laser & Electronics 91 Pulsar, Inc. 88 WCSC (Willies Computer Software Co.)

82 ESC-West 67 Lakeview Research 42, 66 Rabbit, A Digi International Brand 47 Wiznet

90 Earth Computer Technologies 87 Lawicel AB 87 Rabbit, A Digi International Brand 86 Zagros Robotics

66 Elprotronic 13 Lemos International 63, 89 Reach Technology, Inc. 90 Zanthic Technologies, Inc.

22 ExpressPCB 50 Linx Technologies 25, 57 Renesas Technology

64 ezPCB 89 Loadstar Sensors, Inc. 87 Robot Power

86 FDI-Future Designs, Inc. 73 Luminary Micro 50, 58 Saelig Co.

Preview of April Issue 213 ATTENTION ADVERTISERS Theme: Embedded Programming May Issue 214 Parts ATA I/O: Use ATA Interfaces for General-Purpose I/O Applications Deadlines Simple Hardware Development Space Close: Mar. 12 Programmable Power: Build a Simple USB DAC Material Close: Mar. 21 Do-It-Yourself Motion-Controlled Gaming (Part 2): Manipulate 3-D Graphics Video Stamp: A Video Display for Debugging Programs Theme: Embedded Linux Development (Part 1): A Virtual Linux Environment on a Measurement & Sensors Windows System BONUS DISTRIBUTION: Sensors Expo, PCB East THE DARKER SIDE Low Power Techniques: Build Better Energy-Saving Electronic Systems Call Shannon Barraclough ABOVE THE GROUND PLANE TRIAC Control Meets An Inductive Load now to reserve your space! FROM THE BENCH Digital Touch: A Potentiometer with No Moving Parts 860.875.2199 SILICON UPDATE STM32 e-mail: [email protected]

94 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com 95.qxp 2/13/2008 1:43 PM Page 1

The Newest Semiconductors

The ONLY New Catalog Every 90 Days

Experience Mouser’s time-to-market advantage with no minimums and same-day shipping of the newest products from more than 335 leading suppliers.

The Newest Products For Your Newest Designs

www.mouser.com (800) 346-6873 Over 920,000 Products Online

MoMouser_CircuitCellar_3-1.indduser_CircuitCellar_3-1.indd 1 11/21/08/21/08 12:26:2212:26:22 PM steve_edit_212_v1.qxp 2/8/2008 4:22 PM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director What Happened to Performance?

It seems like I’ve been spending a lot more editorial space ranting these days. I think the reason is that I feel more at the mercy of ridiculous engineer- ing than I used to. There was a time when if I didn’t like how something worked, I’d just go re-design or customize it, but with today’s complex proces- sors and million-line operating systems, re-engineering commercial items is pretty much impossible. Basically, we’re at the mercy of whatever corporate profit-inspired crap they want to shove our way. Do I sound bitter? Whether your embedded expertise involves software or hardware, our professional lives these days mandate the use of a PC and there aren’t a whole lot of options. Choices regarding system configuration and processor speeds are still ruled by our wallet, as they should be in a capitalistic econ- omy, but the sad choice of operating systems is a terrible statement of monopoly politics. I have three computers (two Sony VAIOs and a Toshiba) that I use on a regular basis. One is a large desktop and the other two are large and small laptops. All of them are about three years old and use Windows XP Pro. For the most part, they have been bug-free and I haven’t had any problems installing software for the many programs and devices that I like to use. However, like everything technical these days, evolution continues. Certainly, now that we have dual and quad processors galore, I could expect to see a remarkable increase in performance in a couple of new top-of-the-line VAIOs with Microsoft’s latest and greatest multi-processor operating system—Vista. I’m glad I wasn’t the first one on my block to try this because it would have been a disaster. But in order to get a better handle on reality versus all of the Microsoft bashing, I bought a dual-processor Gateway laptop with Vista Home Premium to see the results of three more years of Moore’s Law in action. In my opinion, Vista is a sexy, graphic-intensive operating system designed to move us all into the world of flashy video, Internet-centric living, and more Microsoft-provided software services and advertising. (Sounds a lot like Google doesn’t it?) My single-processor 2.39-GHz P4 XP seems faster than a 2.6-GHz Core 2 Duo with twice the RAM running Vista. And, there seems to be very little driver support for the small-company peripherals and software packages that I am currently using under XP.(It should have been a clue when I did a Google search on “Vista sucks” and got 150,000 results using exactly those words.) ;-) At this point, the decision is to forget upgrading (a concept that if it catches on should strike panic in every PC manufacturer), switch to a Mac or Ubuntu (unfortunately not enough driver support here either), or buy new hardware and just install XP Pro instead of Vista (easier said than done). I hope PC manufactures get the message, but they need to know they have been led down the path by Microsoft. Perhaps like many of you, I’m vot- ing with my wallet. I’m not buying any new PC hardware until they sell it to me without Vista or in a configuration that I can easily install XP alone. For example, we needed new desktops for everyone at the office this year. To the detriment of all the other PC manufacturers who only sell Vista, the solu- tion was getting them from Dell because Dell would configure them preloaded with XP. Unfortunately, I don’t think Dell has the laptops I want, and solving my personal PC requirements is turning into a whole ’nother bag of worms. Unless I order some expensive exotic gaming machine where they already know it has to be XP or a way off-brand PC, I don’t see any laptops from the “reg- ular guys” that aren’t preloaded with Vista. (And who’s the idiot that thought up four different versions of Vista to further confuse the market?) Unlike a desktop where we can configure the hardware to accommodate the available drivers and do a clean XP install, prepackaged laptops are black boxes with few configuration options. The only option for most VAIO, HP, Toshiba, etc. laptop owners is to try to install XP as a second disk partition. The good news is that this indeed gives you back the use of XP, but apparently Vista never goes away, and doing this has its own unique set of bugs. Forget that. Still, hardware is hardware, isn’t it? Logic suggests that we should be able to simply buy a new HP or Gateway laptop, wipe Vista off the machine, and then install XP.Unfortunately, the reality is that most retailers are selling a lot of this new hardware as “Vista-only” machines and internal peripher- al XP drivers aren’t necessarily available for that specific laptop. The result is that it may require numerous calls to the manufacturer (how’s your Chinese?) to obtain XP drivers.Yes, you can install XP, but you might find that the DVD player doesn’t work because you have the wrong driver. So, right now I’m sitting here with three computers I’d like to upgrade and about $6,000 I’m not spending on any manufacturer until someone sells me a new laptop with XP Pro on it. I have a list of favorite brands, but I’m open to suggestions. If you’ve spent more time researching this problem and have some answers, please e-mail me and tell me where to look. In the meantime, I’ll trust that Vista Service Pack 1 has helped mitigate some of the performance issues, but until then, I guess Google’s content scanning will make this editorial 150,001 the next time someone searches that phrase.

[email protected]

96 Issue 212 March 2008 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 3/30/2007 1:38 PM Page 1 C4.qxp 2/11/2008 11:23 AM Page 1