circuit cellar 2012-03

84
www.circuitcellar.com THE WORLD’S SOURCE FOR EMBEDDED ELECTRONICS ENGINEERING INFORMATION $7.50 U.S. ($8.50 Canada) MARCH 2012 ISSUE 260 Q&A: The Enterprising Roboticist HOW TO: Plan for Component Obsolescence PROJECT: Parallel Port Interface Replication LOCATION: New Zealand LOCATION: Canada LOCATION: United States PAGE: 16 PAGE: 50 PAGE: 60 Robot Navigation with Acoustic Delay Triangulation Get Started with a Mechatronics Robot “NakedCPU” Experiments An MCU-Based Color Identifier IR Thermal Detection PLUS DIY GAMING PLATFORM Develop a System from Start to Finish // Hack a Joystick & Add a New Circuit Board // Emulate Classic Arcade Hardware // Sound Interface Device Implementation // And More ROBOTICS Robot Navigation with Acoustic Delay Triangulation Get Started with a Mechatronics Robot “NakedCPU” Experiments An MCU-Based Color Identifier IR Thermal Detection

Upload: sara-romi

Post on 20-Apr-2015

463 views

Category:

Documents


31 download

TRANSCRIPT

www.circuitcellar.comTHE WORLDS SOURCE FOR EMBEDDED ELECTRONICS ENGINEERING INFORMATION$7.50 U.S. ($8.50 Canada)MARCH 2012ISSUE 260Q&A: The Enterprising Roboticist HOW TO: Plan for Component Obsolescence PROJECT: Parallel Port Interface ReplicationLOCATION: New Zealand LOCATION: Canada LOCATION: United StatesPAGE: 16 PAGE: 50 PAGE: 60Robot Navigation with Acoustic Delay TriangulationGet Started with a Mechatronics RobotNakedCPU ExperimentsAn MCU-Based Color IdentifierIR Thermal DetectionPLUSDIY GAMINGPLATFORMDevelop a System from Start to Finish// Hack a Joystick &Add a New Circuit Board// Emulate Classic Arcade Hardware// Sound Interface Device Implementation// And MoreROBOTICSRobot Navigation with Acoustic Delay TriangulationGet Started with a Mechatronics RobotNakedCPU ExperimentsAn MCU-Based Color IdentifierIR Thermal Detection The RL78 Green Energy ChallengeWith an incredible ecosystem of hardware, software and third-party vendors, Renesas family of RL78 MCUs are optimized for efcient power consumption and deliver up to41 DMIPS at 32MHz. These versatile MCUs offer a true low-power platform for the most demanding 8- and 16-bit embedded applications.Renesas, along with Circuit Cellar and Elektor, invites you to experience true low power by developing a green energy application using the RL78 MCU and IAR tool chain. Succeed and win a share of $20,000 in cash prizes! Be the green you see in the world and get ready for the RL78 Green Energy Challenge.www.circuitcellar.com/RenesasRL78ChallengeIn association with Elektor and Circuit Cellar3x faster and backwardcompatible with TS-72xxS Most products stocked and availablefor next day shipping Engineers on Tech SupportDesign your solution with one of our engineers (480) 837-5200Custom configurations and designs w/excellent pricing and turn-around timeOver 25 years in businessNever discontinued a productN Open Source VisionHigh-End Performancewith Embedded Ruggedness128MB DDR RAMGigabit ethernet2 host USB 2.0 480 Mbps12K LUT customizable FPGA512MB high-speed(17MB/sec) onboard FlashSleep mode uses 200 microamps2 SD socketsLinux 2.6 and Debian by default10 serial portsqty 100229$Unbrickable design5 ADC (10-bit) 2 SATA ports110 GPIOBoots Linux 2.6 in 0.7 secondsInternal PCI Bus, PC/104 connectorshown w/ optional SD CardsLow power - 4W@5Vqty 1269$ TS-TPC-7390200 MHz ARM9Dedicated framebuffer- 8MB RAM800 x 480 video core64MB SDRAM (128MB opt)Runs Eclipse IDE out-of-the-boxBoots Linux 2.6 in less than 2 secondsUnbrickable, boots from SD or NANDRuns X Windows GUI applications512MB Flash w/ Debian LinuxMountable aluminum frameLow Power, Industrial Quality Designqty 1449$Audio codec with speaker7 Color Touch Panel ComputerMore Touch Panel Computers on our websiteq TS-7800500 MHz ARM9 Embedded Systems Start your embedded s design5 SystemsTechnologicVisit our TS-7800 powered website atWe use our stuff.www.embeddedARM.comM New Products design5 TS-4200: Atmel ARM9 with super low powerLow profile w/ 6mm spacingCommon pin-out interfaceSeveral COTS baseboards for evaluation & developmentTS-4300: Cavium ARM11 with dual 600 MHz and FPUTS-4700: Marvell PXA168 with video and 1.2 GHz CPUSecure connection w/ mounting holesDual 100-pin connectorsTS-4500: Cavium ARM9 at very low costqty 10092$starts atseriesT qty 1185$ TS-SOCKET MacrocontrollersJump Start Your Embedded System DesignE TS-SOCKET Macrocontrollers are CPU core modules that securely connect to a baseboard using the TS-SOCKET connector standard. COTS baseboards are available or design a baseboard for a custom solution with drastically reduced design time and complexity. Start your embedded system around a TS-SOCKET Macrocontroller to reduce your overall project risk and accelerate time to market.TS-4800: Freescale iMX515 with video and 800 MHz CPU75 mm / 2.953 in.55 mm / 2.165 in.Current projects include:Ideal for gateway or firewall, protocol converter, web server, WiFi audio, and unattended remote applications64MB DDR-RAM480Mbit/s USB, Ethernet, PoE optionRS-232, RS-485, CAN, RTCCustomizable FPGA - 5K LUTBoots Linux 2.6.24 in < 3 secondsMicro-SD Card slotPower via 5-12 VDC, USB, PoE (opt.)Low power (3.2 watts), fanlessUn-brickable, boots from SD or flashOptional DIN mountable enclosure256MB ultra-reliable XNAND driveHeader with SPI and 11 DIOTS-WIFIBOX-2A Complete Solution for 802.11g WiFi ApplicationsFOUNDER/EDITORIAL DIRECTORSteve CiarciaEDITOR-IN-CHIEFC. J. AbateASSOCIATE EDITORNan PriceCONTRIBUTING EDITORSJeff Bachiochi Bob JapengaRobert LacosteGeorge MartinEd NisleyGeorge NovacekRichard WotizPROJECT EDITORSKen Davidson David TweedADVERTISING800.454.3741 978.281.7708 www.circuitcellar.com/advertiseADVERTISING REPRESENTATIVEPeter WostrelStrategic Media Marketing, Inc.1187 Washington St., Gloucester, MA 01930 USA800.454.3741 [email protected] www.smmarketing.usFax: 978.281.7706ADVERTISING COORDINATORKim HopkinsE-mail: [email protected]: www.circuitcellar.com, e-mail: [email protected]: 800.269.6301, www.circuitcellar.com, Circuit Cellar, P.O. Box 462256, Escondido, CA92046Address Changes/Problems: E-mail: [email protected] INFORMATION860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] REPRINTS INFORMATION860.875.2199, E-mail: [email protected] e-mail addresses (when available) are included at the end of each article.CIRCUIT CELLAR (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) subscrip-tion rate USA and possessions $50, Canada $65, Foreign/ROW $75. All subscription orders payable in U.S.funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct sub-scription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 462256,Escondido, CA 92046 or call 800.269.6301. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 462256, Escondido, CA 92046.Circuit Cellar makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for theconsequences 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 orfrom 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 tobuild things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right toconstruct or operate any of the devices described herein under the relevant patent or other intellectual property law of the readers jurisdiction.The reader assumes any risk of infringement liability for constructing or operating such devices.Entire contents copyright 2012 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc.Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.Cover photography by Chris RakoczyRakoczy Photographywww.rakoczyphoto.comPRINTED IN THE UNITED STATESThe seed for the interview with Hanno Sander on page 16was sown at the 2008 Embedded Systems Conference in SanJose, CA. Hanno was at the Parallax booth demonstrating hisDancebot, which is a Propeller-based, two-wheeled balanc-ing robot he wrote about in Circuit Cellar 224 (March 2009).Since Circuit Cellar is scheduled to publish Hannos bookAdvanced Control Robotics later this year, it made sense tointerview him for our annual Robotics issue. As youll learn,Hanno is an enthusiastic designer whose intellect and passionfor engineering have enabled him to travel the world and makeelectronics innovation his lifes work. His story should be aninspiration to everyone who reads this magazine. After you finish the interview, check out the two robotics-related articles featured in this issue. First, on page 20, LarryFoltzer tackles the topic of robot navigation with a fascinatingarticle about position determination and acoustic delay trian-gulation. Next, turn to the back of the issue for Jeff Bachiochisarticle, Wheel-Free Mobile Robots (p. 64). Jeff takes youinside a Freescale FSLBOT mechatronics robot. Study theconcepts he covers to prepare yourself for your next mobilerobot design. The rest of the issue includes a variety of articles on cre-ative designs and essential engineering topics. Im sure youllagree that the following articles are just as inspirational asthey are informative.Engineer and video game enthusiast Chris Cantrell explainshow he built a Propeller-based TV gaming platform (p. 28). Hedescribes how he hacked a joystick and got the classic SpaceInvaders video game up and running.On page 36, Charles Edmondson presents his RainbowColor Reader. The compact design can identify and announcecolors for visually impaired users.In the February issue, Alexander Pozhitkov introduced theNakedCPU project. This month he wraps up the article seriesby describing actual experiments and sets the foundation forfuture research (p. 42).On page 50, George Novacek helps you prepare for theinevitable: microelectronic component obsolescence. Youllfind his tips invaluable as you move on to new projects. Interested in the topic of thermal detection? Want toknow how IR thermal sensing works? Turn to RichardWotizs article on page 54.On page 60, columnist George Martin provides his nextengineering lesson learned from a real-world project. Thismonth he covers the topic of working withor without?printer port connections.Id like to wrap up with a note to our staff and long-timereaders. This is the 260thissue of Circuit Cellar. Thats quitean achievement! Thank you, colleagues, friends, and readers! Creativity in [email protected] CIRCUIT CELLAR www.circuitcellar.comMarch 2012 Issue 260TASKMANAGERCircuit Cellars mission is to collect, select, and disseminate need-to-know informa-tion around the world in the fields of embedded hardware, embedded software, andcomputer applications. Circuit Cellar uses an assortment of print and electronic con-tent-delivery platforms to reach a diverse international readership of professionals,academics, and electronics specialists who work with embedded, MCU-related tech-nologies on a regular basis. Our aim is to help each reader become a well-rounded,multidisciplinary practitioner who can confidently bring innovative, cutting-edge engi-neering ideas to bear on any number of relevant tasks, problems, and technologies. THE WORLDS SOURCE FOR EMBEDDED ELECTRONICS ENGINEERING INFORMATIONPUBLISHERHugo Van haeckeASSOCIATE PUBLISHERShannon BarracloughART DIRECTORKC PrescottCONTROLLERJeff YancoCUSTOMER SERVICEDebbie LavoieADMINISTRATIVE COORDINATORValerie LusterMARKETING REPRESENTATIVEAmanda AndersonGRAPHIC DESIGNERGrace Chen6CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260INSIDE ISSUETASK MANAGER 4Creativity in DesignC. J. AbateNEW PRODUCT NEWS 8TEST YOUR EQ 15QUESTIONS & ANSWERS 16Advanced Robot TechnologiesAn Interview with Hanno Sander CROSSWORD 74INDEX OF ADVERTISERS 79April PreviewPRIORITY INTERRUPT 80A Rose by Any Other Name...Steve Ciarcia50 THE CONSUMMATE ENGINEERMicroelectronic Component ObsolescenceHow to Prepare for an Inevitable Scarcity of PartsGeorge Novacek54 EMBEDDED UNVEILEDInfrared Thermal DetectorsRichard Wotiz60 LESSONS FROM THE TRENCHESPrinter Port ConnectionsGeorge Martin64 FROM THE BENCHWheel-Free Mobile RobotsJeff Bachiochi20 Robot NavigationPosition Determination from Acoustic DelayTriangulationLarry Foltzer28 All-in-One JoystickBuild a Propeller-Based TV Gaming PlatformChris Cantrell36 The Rainbow Color Reader (Part 1)A Talking Color Identifier for the Visually Impaired Charles Edmondson42 The NakedCPU (Part 2)Experimentation and CommunicationAlexander PozhitkovMarch 2012 RoboticsRobot Design with Hanno SanderDIY Gaming Platformp. 16Thermal Sensing Tech Unveiledp. 28p. 54Fastest Part Search.Best Selection.Immediate Delivery.The Newest Products for Your Newest DesignsFind It Here. Faster.GOmouser.comMouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. 11:02 AM8CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260ENHANCED EMBEDDED BOARDSThe ECM-CDV, EBM-CDV, and EQM-CDV are powered by the next-generation Intel Atom processor N2600, N2800, andD2700 and Intel NM10 Express chipset featuring low-power consumption and high performance. The newest Intel Atomprocessor series, formerly codenamed Cedar Trail, is based on Intels 32-nm processtechnology, and features a two-chip platform integrating the Northbridge chip with CPU. Thistwo-chip solution will provide system builders with supports for slimmer housing designs.This platform features enhanced performance, energy efficiency, manageability, securityfunctions, and smoother visual experiences. The 3.5 embedded board, ECM-CDV, supports one 204-pin DDR3 SODIMM system memorywith up to 4 GB capacity. ECM-CDV supports dual-channel 18/24-bit (Note: 24-bit is enabled onD2700 only) low-voltage differential signaling (LVDS) with eDP, and multiple display configu-rations (CRT+LVDS, HDMI+LVDS, or CRT+HDMI). The rich I/O deployment includes one SATA,two COM, seven USB 2.0, and 16-bit GPIOs, making various requirements of embeddedapplications possible. One audio jack supports Realtek ALC892, 7.1-CH audio. Two Intel 82574LGigabit LANs and one expansion slot of mini PCIe card (support mSATA) and one CF card slot.The 5.25 embedded board, EBM-CDV, supports one rank of onboard DDR3 system memory with up to 2-GB capacity andone 204-pin DDR3 SODIMM system memory with up to 2-GB capacity. EBM-CDV supports dual-channel 18/24-bit (Note: 24-bitis enabled on D2700 only) LVDS (with eDP) and multiple display configurations (CRT+LVDS, HDMI+LVDS, or CRT+HDMI). Therich I/O deployment includes one SATA, six COM, eight USB 2.0, and 16-bit GPIOs, making various requirements of embeddedapplications possible. One audio jack supports Realtek ALC892, 5.1-CH audio. Two Intel 82574L GB LANs and one expansionslot of mini PCIe card (supports mSATA).The Q7 Module board, EQM-CDV, supports onboard DDR3 system memory with up to 2-GB capacity. EQM-CDV supportssingle-channel 18-bit LVDS and HDMI + LVDS display configurations to baseboard. For I/O, it includes two SATA ports tobaseboard, eight USB 2.0 ports to baseboard, one Intel 82574L GB LANs, and three PCIex1.Avalues Intel Atom processor N2000 and D2000 series boards are designed to meet embedded market requests for low-powerconsumption. They are well suited for designers who need an embedded board with a small form factor for high-performance, multi-media applications. They are also suitable for applications, including POS/KIOSK, digital signage, ordering machine, medical, andtransportation.Contact Avalue for pricing.Avalue Technology, Inc.www.avalue.com.tw2-Mb SERIAL NONVOLATILE FRAM MEMORYThe FM25V20 is a 2-Mb high-performance serial FRAM device. It is a member of Ramtrons V-Family of FRAM products,which offers a wide operating voltage range. Manufactured on a low-power 130-nm CMOS manufacturing process, the RamtronV-Family of F-RAM products includes serial I2C, serial peripheral interface (SPI), and parallel memories.The FM25V20 features fast access, NoDelay writes, virtually unlimited read/write cycles(1e14), and low power consumption. The latest FRAM device is a drop-in replacement for2-Mb serial flash and serial EEPROM memories in applications including industrial controls,metering, medical, military, gaming, and computing.The FM25V20 features an advanced ferroelectric process that yields virtually unlimitedendurance of 100-trillion (1e14) read/write cycles and reliable data retention for 10 years.The device uses a fast SPI, operating up to full bus speed of 40-MHz frequency. The low-power operation features a wide voltage operation of 2.0 V to 3.6 V, a typical standby cur-rent of 100 A, and a sleep mode current of 3 A. A read-only Device ID feature, standardon the serial V-Family devices, enables the host to determine the manufacturer, productdensity, and product revision. The FM25V20 operates over an industrial temperature rangeof 40C to 85C and is available in standard green/RoHS-compliant eight-pin EIAJ SOIC and eight-pin TDFN packages.Pricing for the FM25V20 starts at $8.99 for 10,000-piece quantities.Ramtron International Corp.www.ramtron.comNEWPRODUCT NEWSwww.circuitcellar.comCIRCUIT CELLAR9March 2012 Issue 260NPNOFFLINE LED DRIVER DIMS TO ZERO LIGHT INTENSITYThe MAX16841 is a fixed-frequency offline light-emitting diode (LED) driver that provides flicker-free dimming from maximumlight intensity down to zero intensity with both leading-edge (triac) and trailing-edge (transistor) dimmers. Constant frequencycontrol optimizes efficiency at both low- and high-AC line voltages. With a wide 90-VAC to 265-VAC input range, the MAX16841provides a universal solution for Japanese, Chinese, U.S., and European dimmer models. The driver enables seamless replace-ment of incandescent and halogen lamps, eliminating compatibility issues with preinstalled dimmers. Because it can operatewithout electrolytic capacitors, the MAX16841 prolongs the life of LED lamps and provides space and cost savings.The MAX16841 features a unique, proprietary approach to control a lamps input current. By actively shaping the inputcurrent, the driver ensures flicker-free operation with most electronic transformers and dimmers. This enables LED lampdesigners to create drop-in replacements for halogen and incandescent lighting with dimming down to zero light intensity.The MAX16841 can be designed in isolated (flyback)and nonisolated (buck) configurations making it ideal bothfor high-AC line voltages (220 VAC to 230 VAC) and low-AC line voltages (100 VAC to 120 VAC). A constant-fre-quency control scheme improves efficiency by using theoptimal conduction mode (DCM or CCM), depending onthe input voltage. Dimming efficiency also improves dueto the MAX16841s current-control technique. This tech-nique does not require current bleeders for the hold cur-rent of the dimmer since sufficient hold current is alreadyguaranteed by the switching regulator itself.The MAX16841 reduces inventory and design costssince it does not require separate LED drivers to satisfyinternational voltage requirements. In addition, it can bedesigned in without electrolytic capacitors. This extendsthe lifetime of the LED lamp, since electrolytic capacitorsare usually the first component to fail in the driver circuit.If electrolytic capacitors are available from an existingdesign, the MAX16841 enables the lamp to continue to operate even when those capacitors fail. The LED driver saves spaceand ensures longer lamp life by eliminating bulky electrolytic capacitors that consume valuable space and often fail. It is idealfor retrofit dimmable LED lamps and universal LED bulbs in industrial, commercial, and residential lighting applications.The MAX16841 is fully specified over the 40C to 125C temperature range and is available in an eight-pin SOIC package. Pric-ing starts at $1.35 in 1,000-unit quantities.Maxim Integrated Productswww.maxim-ic.com5-kV RMS SIGNAL-ONLY ISOLATED CAN TRANSCEIVER The ADM3054 is a 5-kV RMS signal-isolated CAN physical-layer transceiver that fully complies with the ISO 11898 CANstandard. The new CAN transceiver leverages Analog Devicess iCoupler digital isolator technology and combines a three-channel digital isolator with a CAN transceiver in a 10 mm 10 mm single-surface-mount, 16-lead, wide-body small-outlineIC (SOIC) package.By reducing printed circuit board (PCB) component count by as much as 70% compared to traditional discrete, optocouplerbased component circuits, the ADM3054 transceiver simplifies design while reducing board space by up to 61%. The ADM3054 is targeted toward applications where an isolated power rail already exists or an additional overwind froman existing isolation transformer can be used. The devices logic is powered with a single 3.3-V or 5-V supply on VDD1while the bus side uses a single 5-V supply on VDD2 only. Loss of power on the bus side (VDD2) can be detected by themicrocontroller using the integrated VDD2SENSE signal. The transceiver has integrated 36-V fault protection on the buspins, CANH and CANL, to guard against shorts to power/ground in 12-V and 24-V systems. The ADM3054 also has current-limiting and thermal-shutdown features that protect against output short circuits and situations where the bus may beshorted to ground or power terminals. The transceiver creates an isolated interface between the CAN protocol controllerand the physical layer bus. It is capable of running at data rates of up to 1 Mbps and is fully specified over the industrialtemperature range of 40C to 125C.The ADM3054 costs $2.10 in 1,000-unit quantities. Analog Devices, Inc.www.analog.com10CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260MINIATURE LED DRIVERSXP Power added four drivers to its LDU series of printedcircuit board (PCB) mount DC input constant current light-emitting diode (LED) drivers. The LED drivers provide poweroutputs of 5 W, 7 W, 14 W, and 20 W. They have a typicalefficiency of 93% for the 5-W, 7-W, and 14-W models and95% for the 20-W devices. The LDU20 series provides up to 700 mA output current,and the LDU05, LDU07, and LDU14 series has a maximumoutput of 1,000 mA. The drivers can accommodate a widerange of input voltage from 7 VDC to 30 VDC.Dimming options include two analog methods (voltage orresistance) and a pulse width modulation (PWM) input sig-nal. The PWM approach has a maximum operating frequencyof 1 kHz, with a minimum of 200-ns on/off time. When usingan analog dimming method, the output current range canbe adjusted from 25% to 100% of nominal current.A remote on/off control input enables the designer tocontrol the output or sequence the start-up. All modelsprovide protection in the event of a short or open circuit ofthe LED device.The LDU series iswell suited for abroad range ofindoor, outdoor,underwater, andautomotive LEDapplications as wellas battery-poweredapplications.Pricing starts at$7.02 for 500-pieceorders of the LDU055-W part.XP Power Ltd.www.xppower.comNPN5-G MEMS CAPACITIVE MODULESDesigned to support a variety of lower-frequency aerospace,automotive, defense, energy, industrial, and general test andmeasurement requirements, the low-noise, single-axis model2210-005 accelerometer module features high-quality MEMScapacitive sensing elements. Sensing elements are packagedwithin compact, lightweight,anodized epoxy-sealed alu-minum housing, occupying atotal footprint of just 1 squareinch. The accelerometers fea-ture a simple four-wire connec-tion and internal voltage regula-tor to minimize supply voltagevariation effects. Units are rela-tively insensitive to tempera-ture changes with quick, easy self-calibration. The 210-005accelerometer modules also feature high-drive, low-imped-ance buffering to support low-frequency acceleration measure-ment requirements from 0 (DC) to 400 Hz.The accelerometer module produces two analog voltageoutputs that vary with acceleration. The module offers achoice of single-ended or differential output, which doublesthe sensitivity over single-ended output to 800 mV/g.The sensitive axis is perpendicular to the bottom of thepackage, with positive acceleration defined as a force push-ing on the bottom of the package. The signal outputs arefully differential about a common mode voltage of approxi-mately 2.5 V. The output scale factor is independent fromthe supply voltage of 9 V to 32 V. At zero acceleration, theoutput differential voltage is nominally 0 V DC; at fullscaleacceleration, the output differential voltage is 4 V DC.The 2210-005 accelerometer module costs approximately$500 per unit.Silicon Designs, Inc.www.silicondesigns.comDESIGN SOFTWARE WITH ARRIA V AND CYCLONE V DEVICE SUPPORT Quartus II software version 11.1 delivers support for the latest 28-nm Arria V and Cyclone V devices, and enhanced supportfor Stratix V devices. The design software includes: support for the Arria V and Cyclone V device families; support for extendedtemperature on Cyclone IV E devices; enhanced support for the Stratix V device family; and System Console, a scalable, easy-to-use hardware debug and monitoring tool. The Qsys system integration tool and the MegaWizard Plug-In Manager generate scripts to help set up a simulationenvironment for third-party simulators. In addition, the softwares updated Tasks window now includes flows for gate-leveland register-transfer level (RTL) simulation.Additional enhancements to the software include fractional phase-locked loops (fPLLs) which enable dynamic phase shiftingand reconfiguration of many individual counter parameters; a transceiver reconfiguration controller to support the adaptiveequalization engine and decision feedback equalizer engine; the EyeQ viewer which provides the ability to see post-equalizedeye opening, including the ability to monitor the receiver eye and supporting both horizontal and vertical measurements; andARM-based system-on-a-chip (SoC) devices including Early power estimator and AXI bus functional model (BFM) beta.The Quartus II Web Edition software (no license required) can be downloaded for free. Contact Altera for a paid Quartus IISubscription Edition software.Altera Corp.www.altera.comMicroprocessor Design UsingWith the right tools, such as this new book, designing a microprocessor can be easy. Okay, maybe not easy, but certainly less complicated. Monte Dalrymple has taken his years of experience designing embedded architecture and microprocessors and compiled his knowledge into one comprehensive guide to processor design in the real world. Buy it before March 15, 2012 and SAVE 15% off the cover price. Yours for just $38.25! www.cc-webshop.com Monte demonstrates how Verilog hardware description language (HDL) enables you to depict, simulate, and synthesize an electronic design so you can reduce your workload and increase productivity.Microprocessor Design Using Verilog HDL will provide you with information about: Veri|og HDL Review Veri|og Coding Sty|e Design Work Microarchitecture Writing in Veri|og Debugging, Verication, and Testing Post Simu|ation and more!Verilog HDL12CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260FULL-FEATURED EVALUATION BOARD The AT91SAM9G45-EVK is a co-branded evaluation kit from Atmel and element14. The full-featured evaluation board isbased on Atmels AT91SAM9G45 processor which runs at up to 400 MHz and features 128-Mb DDR2 memory and 256-MbSLC NAND flash. The board provides a range of peripherals, including a high-speed USB host/device port, an Ethernet 10/100interface, two high-speed SD/MMC slots, and a QVGA 320 240 liquid crystaldisplay (LCD) panel with resistive touchscreen. In addition, the board supportsLinux, WinCE, and Android operating systems (OSes) and offers example applica-tions under these three OSes.The ARM926EJ-S based AT91SAM9G45-EVK features the frequentlydemanded combination of user interface functionality and high data rateconnectivity, including a LCD controller, resistive touchscreen, camera inter-face, audio, Ethernet 10/100, and high-speed USB and SDIO. With theprocessor running at 400 MHz and multiple 100+ Mbps datarate peripher-als, the AT91SAM9G45-EVK has the performance and bandwidth to thenetwork or local storage media to provide an adequate user experience.The AT91SAM9G45-EVK supports the latest generation of DDR2 andNAND flash memory interfaces for program and data storage. An internal133-MHz multilayer bus architecture with 37 DMA channels; a dual externalbus interface; and distributed memory including a 64-Kb SRAM which can be con-figured as a tightly coupled memory (TCM); sustains the high bandwidth required by theprocessor and the high-speed peripherals. The I/Os support 1.8-V or 3.3-V operation, which areindependently configurable for the memory interface and peripheral I/Os. This feature eliminates the needfor any external-level shifters.In addition, the evaluation kit supports 0.8 ball-pitch package for low-cost printed circuit board (PCB) manufacturing. TheAT91SAM9G45 power management controller features efficient clock gating and a battery back-up section which minimizespower consumption in active and standby modes.Contact Atmel or element14 for pricing.Atmel Corp.www.atmel.comElement14 www.element14.comWIRELESS OPTIMIZATION FOR 3G/Wi-Fi/BT/GPS SUPPORTThe Matrix MXE-5300 series of rugged, quad core, fanless embedded computers is based on the high-performance 2ndGeneration Intel Core i7/i5/i3 processor and QM67 chipset. The high-performance computers feature wireless optimizationcapability, robust mechanical design, and Intel AMT 7.0 support. The MXE-5300 is well suited for intelligent transportation,in-vehicle multimedia, and surveillance and factory automation applications. Other features of the MXE-5300 include: performance-enhancing mechanicaland thermal design, including customized copper conduits to enhancethermal dissipation efficiency; memory and storage stabilizers to withstandthe challenges of high-vibration environments; and an anodized aluminumalloy chassis to prevent corrosion. With industrial solid-state drive (SSD)storage devices, the MXE-5300 provides an operating temperature rangeof 20C to 70C for reliable performance in mission-critical and harshenvironments. The MXE-5300 also features a unique thumbscrew design, whichmakes replacement or swapping of hard disk drive (HDD) and RAM/mini PCIemodules easy, lowers maintenance costs, and increases flexibility.The MXE-5300 supports rich I/O interfaces, including four serial ports,six USB ports (two USB 3.0), four isolated digital I/Os, and four GB Ethernet ports. In addition, the MXE-5300 providestwo Mini-PCIe and one USIM slot for wireless needs. Intel AMT 7.0, available on the MXE-5300, enables remote monitoringand control over embedded devices via the Internet, remote system reboot in the event of operating system (OS) failure,and system disconnect from the web when malicious intrusion is detected to prevent migration to other devices.Contact ADLINK for pricing.ADLINK Technology, Inc.www.adlink.comNPNCircuit Cellar feature articles are contributed by professional engineers, academics, and students from around the globe. Each month, the editorial staff reviews dozens of article proposals and submissions. Only the best make it into the pages of this internationally respected magazine.Get PUBLISHED. Get NOTICED. Get PAID.Do you have what it takes? [email protected] Contact C. J. Abate, Editor-in-Chief, today to discuss the embedded design projects and programming applications youve been working on and your article could be featured in an upcoming issue of Circuit Cellar magazine. www.circuitcellar.comCIRCUIT CELLAR13NPNTEMP SENSOR GUARANTEES HIGH ACCURACY & RESOLUTION The MCP9808 silicon temperature sensor guarantees a high accuracy of 0.5C from 20C to 100C, along with a hightemperature resolution of 12 bits (0.0625C/LSB). The MCP9808 comes in small MSOP and 2 mm 3 mm dual-flat noleads (DFN) eight-pin packages for space-constrained applications. Additional features include shutdown, an under/over-temperature monitor and a critical-temperature alert.The MCP9808 is well suited for applications that require high accuracy over a variety of temperatures, such as thermo-stats (20C to 45C), personal computers (85C), and industrial/automotive (125C). In addition, many applications canbenefit from reduced energy usage via accu-rate temperature monitoring and control thatenables more efficient operation.The sensor features shutdown and tempera-ture monitoring/alert features, to help adjust thereal-time power utilization of everything fromresidential HVAC systems to industrial equip-ment. The shutdown feature reduces power con-sumption in both line- and battery-powered sys-tems. The on-chip over/under temperature mon-itor can improve system performance throughthermal optimization. The MCP9808 also fea-tures a critical-temperature alert that canincrease the systems life by preventing harmfuloperating temperatures.Pricing for the MCP9808 starts at $0.84 eachin 5,000-unit quantities.Microchip Technology, Inc.www.microchip.comMarch 2012 Issue 26014CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260NPNMOTOR CONTROL KIT FOR SPINNING THREE-PHASE BRUSHLESS MOTORSThe DK-LM3S-DRV8312 motor control kit features a 32-bit Stellaris LM3S818 microcontroller and DRV8312 motor driver tospin sub-50-V, 6.5-A, three-phase brushless DC (BLDC) motors in minutes. The easy-to-use kit is a low-cost solution for high-volume motor control applications including low-voltage fans, blowers, pumps, tools, and compressors. The Stellaris LM3S818 controlCARD module, which is included in the kit, has the required firmware preprogrammed in flashmemory to run TIs InstaSPIN-BLDC solution out-of-the-box, along with other customer-developed applications, when pluggedinto the DRV8312 motor driver base board. The InstaSPIN-BLDC solution is a free back-electromagnetic field (EMF) techniquethat spins any motor in seconds without knowledge of any motor parameters.Unlike traditional back-EMF zero-crossing techniques, InstaSPIN-BLDC extendssensorless operation down to lower speeds and exhibits high immunity tomiscomputation caused by rapid speed changes. Reliable motor start-up hasbeen demonstrated over a wide range of conditions, including full torque. The controlCARD module with Stellaris LM3S818 MCU features 50-MHz per-formance, 64-KB flash memory, 8-KB SRAM, and six pulse-width modulation(PWM) generators, enabling developers to create complex motion-controldesigns with a small footprint.The DRV8312 motor driver delivers up to 6.5 A current, without the needfor an external heat sink. It is a reliable, fully protected motor driver withcycle-by-cycle over-current, over-temperature, cross-conduction, and under-voltage protection, reducing design complexity and board space and ensuringhigher system reliability. The kit includes a 24-V, three-phase BLDC motor operating at up to 3.5 A continuous.The supporting software includes StellarisWare software with TIs IQmath Library for easy fixed to floating-point conversionand InstaSPIN-BLDC software for quick and reliable motor start-up on any motor.Any system design can be accelerated with an intuitive graphical user interface (GUI) powered by third-party CrosshairsEmbedded. The existing GUI can be customized or created with easy drag-and-drop development by downloading CrosshairsInterface Designer.The DK-LM3S-DRV8312 development kit costs $299. For those who own the DRV8312-C2-KIT, which includes theDRV8312 and C2000 Piccolo MCU, the existing controlCARD can be exchanged with the Stellaris LM3S818 controlCARDmodule for $49.Texas Instruments, Inc.www.ti.comLOW-POWER ARM CORTEX-A8 SoM WITH 3-D VIDEO The SoM-3517M is a system-on-module (SoM) based on the Texas Instruments ARM Cortex-A8 processor. This fanless600-MHz SoM features an Ethernet PHY along with four serial ports. The SoM utilizes up to 512 MB of external DDR2/SDRAMand 1 GB of NAND flash. It also includes an on-module SD flash socket and an MMU that enables it to run Linux and WindowsCEoperating systems. The SoM-3517M incorporates the same small 200-pin SODIMM formfactor utilized by other EMAC SoM modules. All of the ARM processorcore is included on this tiny board including flash, memory, serialports, Ethernet, SPI, I2C, I2S audio, CAN 2.0B, pulse width modulators(PWMs), timer/counters, ADCs, digital I/O lines, video, and a clock/calendar. In addition, the SoM-3517M provides a math coprocessor,and 2-D/3-D accelerated video and image scaling/rotation. The SoM-3517M is designed to plug into a carrier board thatcontains all the connectors and any custom I/O required for theapplication. This approach enables the customer or EMAC to designa custom carrier board that meets the customers I/O, dimensional,and connector requirements without having to worry about theprocessor, memory, and standard I/O functionality. Using this SoMapproach, a semi-custom hardware platform can be developed inas little as a month.Contact EMAC for pricing.EMAC, Inc.www.emacinc.comwww.circuitcellar.comCIRCUIT CELLAR15March 2012 Issue 260Tes t Your Whats your EQ?The answers are posted at www.circuitcellar.com/eq/You may contact the quizmasters at [email protected] 1In an RS-232 interface, why is the idleor mark level a negative voltage?Problem 2Similarly, why does the mark level cor-respond to a logical high level on the TTL side ofthe interface?Problem 3In the listing to the right, what does theC function compute? You may assume the inputargument is a positive integer.Problem 4Suppose you are given some calibrationconstants for a sensor in the form of four-digit hexa-decimal (16-bit) integers, and you are told that the formatof these numbers is 7 integer bits and 9 fractional bits.How would you go about converting these constants tofloating point so that you could, for example, work withthem in a spreadsheet? int function (int x){int y = 1;int z = 0;int i = 0;while (x > 0) {z += 6;y += z;x -= y;++i;}return i;}Contributed by David Tweed16CIRCUIT CELLARwww.circuitcellar.comAdvanced Robot TechnologiesAn Interview with Hanno SanderNAN: You moved to New Zealand in 2005. Why did youend up there?HANNO: My wife and I fell in love with the NewZealand lifestyle during our honeymoon, so we moved toChristchurch after the birth of our first child. Even withthe recent earthquakes, we love living in a communitythat places top value on family life. We take full advan-tage of the beautiful beaches and scenery that NewZealand offers. Its also exciting as an engineer to be sur-rounded by innovative Kiwis who love to tinker. It seemslike everyone here has a steam engine in their garage.NAN: You have always had a passion for electronics. Infact, you programmed a lunar lander game for the z80when you were just 6 years old! When did you realize youwere so interested in engineering? Were you inspired by afamily member or teacher when you were young? HANNO: My mom taught high school physics and math,while my dad pioneered optical recording at Philips Elec-tronics. From an early age, Ive loved learning how thingswork and building new things. Growing up, I spent count-less hours with Legos, Meccano erector sets, Mrklintrain sets, computers, and remote-controlled toys. My dadcontinues to be a patient mentor with a passion to distillcomplex concepts onto a single piece of paper. NAN: Tell us about that game you designed at age six.HANNO: I think Ive always loved to teach people aboutscience and technology. I wrote my Lunar Lander gameafter learning about the Apollo space missions to share myknowledge with my younger sisters. The game included asimulated rocket launch, a flight through a meteor field, acontrolled descent onto the moon, and then a return toQUESTIONS & ANSWERSearth with a parachute-assisted splashdown into the ocean.This was programmed on my dads self-built z80 completewith 1022-byte sectors read from tape, a homemade key-board, and four potentiometers for analog control.NAN: Where did you go to school and what did you study?HANNO: I studied computer science at Stanford Universityin California. I loved learning from my professors and fel-low students but had even more fun developing a hybrid carand a microsatellite. I graduated in three years to start myfirst company, Daptyx, an interactive online newspaper.After making some money from my start-up, I brought sev-eral advanced technology projects to market during my Sili-con Valley career at Oracle, Yahoo!, and Verity. NAN: Tell us about your company, HannoWare. Describesome of your projects.HANNO: HannoWare is my attempt to share my hobbieswith others while keeping my kids fed and wife happy. Itstarted with me simply selling software online but is nowa business developing and selling software, hardware, andcourseware directly and through distributors. I get a kickout of collaborating with top engineers on our projects andElectronics have always captivated Hanno Sander, who began programming at an early age. His interests in science andtechnology led him to start his own company, which enables him to collaborate with other engineers to designrobots and create development environments. In January, I interviewed Hanno about his engineering interests, bookwriting, and the future of artificial intelligence.Nan Price, Associate EditorA Turing machine debugged with ViewPortMarch 2012 Issue 260IN ASSOCIATION WITH: Visit www.chipkitchallenge.com for complete rules and details. hot idea Turn acoolinto asolution.chipKIT is a registered trademark of Microchip Technology Inc. Max32 is a registered trademark of Digilent, Inc.DesignSpark chipKIT ChallengeGet ready to win your share of $10,000 in cash prizes! Its time to see if your hard work and superior engineering skills have paid off. The deadline for the DesignSpark chipKIT Challenge is just around the corner. Its time to nalize your design and prep your entries for the judges! Will your design change the world? Reduce power consumption? Improve energy efciency? Theres only one way to nd out. Manage your project entry by clicking on the My Project tab at www.designspark.com/chipkitchallenge-projects/latest. Be sure to upload, and clearly label, all materials necessary for judging your entry including an abstract, complete documentation, and source code. For more information and tips on how to enter, visit www.designspark.com/chipkitchallenge/faq. Dont delay! The DesignSpark chipKIT Challenge ends on March 27, 2012 at 18.00 GMT (13.00 EST). Deadline for Entries: March 27, 2012balancing robot to market in thiseconomy, but its still on my to-dolist. I did contribute several chaptersabout the DanceBot to another book,Programming and Customizing theMulticore Propeller Microcontroller:The Official Guide, and the hard-ware and software are available aspart of the open-source PropellerSmorgasboard project.NAN: Your upcoming Circuit Cellarbook covers all things robotics, frommicrocontrollers and peripherals tovisual debugging and test instruments.The book is designed for DIYers, com-puter science students, and profession-al engineers alike. What was yourimpetus for writing the book? Whatcan readers can expect to learn from it?HANNO: There are plenty of booksthat introduce people to robotics. Iwrote my book to appeal to those look-ing for more meat on more advancedsubjects like computer vision, control18CIRCUIT CELLARwww.circuitcellar.comlove hearing from customers abouttheir success.Our first product was the ViewPortdevelopment environment for theParallax Propeller, which featuresboth traditional tools like line-by-linestepping and breakpoints as well asreal-time graphs of variables and pinI/O states to help developers debugtheir firmware. ViewPort has beenused for applications ranging from cre-ating a hobby Turing machine to cali-brating a resolver for a 6-MW motor.12Blocks is a visual programminglanguage for hobby microcontrollers.The drag-n-drop style of programmingwith customizable blocks makes itideal for novice programmers. LikeViewPort, 12Blocks uses rich graphicsto help programmers understandwhats going on inside the processor.The ability to view and edit theunderlying sourcecode simplifies tran-sition to text languages like BASICand C when appropriate.TBot is the result of an Internet-only collaboration with Chad George,a very talented roboticist. Our goal forthe robot was to excel at typical robotchallenges in its stock configurationwhile also allowing users to cus-tomize the platform to their needs. Afull set of sensors and actuatorsaccomplish the former while themetal frame, expansion ports, andsoftware libraries satisfy the latter.NAN: Tell us about your PropScopedesign, which is one of the projectsfeatured on your companys website(www.hannoware.com).HANNO: The PropScope is a multi-function USB oscilloscope built aroundthe Parallax Propeller microprocessor.The Propellers eight cores allow it tosample and analyze both digital andanalog signals at high speed while gen-erating customizable waveforms. Stu-dents and engineers use the PropScopeas an affordable tool to understand andshare electronic signals. NAN: You have given several TechTalks at Google. Tell us a little aboutthe talks and how you came to beinvolved.HANNO: I first heard about Googlewhen my senior project advisor atStanford told me to talk to a coupleguys who were indexing the Internetsadly, I didnt follow his advice. I nowmake an annual pilgrimage to theGoogleplex to lunch with friends,marvel at a SpaceShipOne replica,and talk about the projects Iminvolved with. The Tech Talks arefilmed on an elaborate stage with aslew of robotic cameras and lightsresulting in a quality production. NAN: In addition to designing andpresenting, youve also done a fairamount of writing, including an articlefor Circuit Cellar and a soon-to-bepublished book about advancedrobotics. In your 2009 article,Vision-Guided Robotics: A Next-Generation Balancing Robot (CircuitCellar, 224), you introduced theDanceBot, a balancing robot you builtwith a Parallax Propeller, a handydesign kit, and a camera. Tell us howthe DanceBot has evolved since then.HANNO: I developed the DanceBotright when my son was learning towalk, so I challenged myself to get myrobot to take a step before my son.The DanceBot did win, but my sonhas evolved much further since. Ivebeen reluctant to bring a vision-guidedThe TBot educational robotThe DanceBotA 12Blocks programMarch 2012 Issue 260The ViewPortinterfacewww.circuitcellar.com CIRCUIT CELLAR19March 2012 Issue 260algorithms, and wireless control. My goalwith each topic was to provide some techni-cal background, code, and schematics toexplain the concepts and then discuss appli-cations and best practices.NAN: Why such a strong interest in robotics?HANNO: I think robots are a wonderfultool to help people relate to the abstractconcepts inherent in science, technology, engineering, andmath (STEM) subjects. Since the industrial revolution,people have fantasized about interacting with mechanicalcreatures and were lucky enough to live in the age wheretheyre becoming real. NAN: Aside from advanced robotics, what other electronicsengineering topics interest you and why?HANNO: Im a big advocate of science and technology andlove learning about new developments in both. Im currentlyexcited about the rapidly decreasing cost of photovoltaicpower, applying the storage capacity of lithium batteries torevolutionize existing products, and the flexibility of additivemanufacturing (e.g., 3-D printers).NAN: We often ask interviewees about their predictions forupcoming hot topics. Some recentanswers have included: DSP and compres-sive sensing, smaller and faster CPUs, andhardware design using programmable logic.What are your thoughts?HANNO: Todays computing devices featureincredible horsepower, memory, and connec-tivity to basically all of human knowledge inaddition to high-definition cameras and othersensors. Were starting to see artificial intelligence in com-mercial offerings with IBMs Watson and Apples Siri. I thinkthat, for better or worse, the trend over the next decade is tobring human-level intelligence to devices all around us.NAN: Final question: If you had a full year and a goodbudget to work on any design project you wanted, whatwould you build?HANNO: I like to think that HannoWare gives me the flex-ibility to pursue my passion. Im currently very excited towork with teachers from kindergarten through universityon a set of videos, example programs, and supportingresources that conform to New Zealands curriculum stan-dards. Weve set up the OneRobot organization to help typ-ical schools to enhance their offering with resources thathave been proven to get results. IThe ParallaxPropScope20March 2012 Issue 260Robot navigation doesnt have to be complicated to be effective. You can implement themathematics of navigation described here to chart a course to a target destination whilestaying within the native bounds of the 8-bit microcontroller and 8-bit mathematics.Robot NavigationAFEATUREARTICLEby Larry Foltzer (USA)utonomous robot behavior has interested me foryears, primarily as an observer. But prior toretirement, I had little time outside my profession toexplore extracurricular interests. After retiring, and abouttwo years ago, I decided to explore what it takes, algo-rithmically speaking, to make a robot that is capable ofdiscovering its position on a playing field and figuringout how to maneuver to another position within thedefined field of play. Later on I will build a minimalist-like platform to test algorithms performance.In the interest of hardware simplicity, my goal is to useas few sensors as possible. I will use ultrasonic sensors todetermine range to ultrasonic beacons located at the cor-ners of the playing field and wheel-rotation sensors toPosition Determination from Acoustic Delay TriangulationFigure 1The square playing fieldS = 64 UnitsTb = Vs 2RbTd = Vs 2RdTa = Vs 2Ra[0, S] BA [0, 0] Xa D [S,0]S = 64 UnitsPlaying field diagonal = 90.5 UnitsC [S, S]Probot = [Xa, Ya]Ya Ra = Xa + Ya Rb = Xa + S 2 2 22 2( )( )12 Ya Rd = S Xa + Ya R2 2( ) ( )223 ( )from aa Rd = S2 + Ra + Rd Ra Rd S 2 2 ( ) ( ) ( ) ( )Xa2 and Ra Rb = S2 Ra + Rb Ra Rb 2 2 ( ) ( ) ( )Ya2 SSRecalling that R = Vs Td2 and defining one uni( ) tt time delay as the 3" round-trip prop delay, the playing field is 16' squareCIRCUIT CELLARwww.circuitcellar.commeasure distance traversed, if wheel-rotation rate timestime proves to be unreliable.From a software point of view, the machine must beable to determine robot position on a defined playing field,determine robot position relative to the targets position,determine robot orientation or heading, calculate robotcourse change to approach target position, and periodicallyupdate current position and distance to the target. Becauseof my familiarity with Microchip Technologys 8-bitmicrocontrollers and instruction sets, the PIC16F627A ismy choice for the microcontrollers (mostly because I havethem in my inventory).To this date, the four goals listedin terms of algorithmdevelopment and codeare complete and are the mainsubjects of this article. Going forward, focus must nowshift to the hardware side, including software integrationto test beyond pure simulation.SENSOR TECHNOLOGY & THE PLAYING FIELDA brief survey of ultrasonic ranging sensors indicatesthat most commercially available units have a rangecapability of 20 or less. This is for a sensor type thatdetects the echo of its own emission. However, in thiscase, the robots sensor will not have to detect its ownechoes, but will instead receive the response to its queryfrom an addressable beacon that acts like an active mir-ror. For navigation purposes, these mirrors are located atthree of the four corners of the playing field. By usingactive mirrors or beacons, received signal strength willbe significantly greater than in the usual echo rangingsituation. Further, the use of the active mirror approachto ranging should enable expansion of the effective widthof the sensors beam to increase the sensors effectivefield of view, reducing cost and complexity.Taking the former into account, I decided the size ofthe playing field will be 16 on a side and subdivided into3 squares forming an (S S) = (64 64) = (26, 26) unitgrid. I selected this size to simplify the binary arithmeticused in the calculations. For the purpose of illustrationhere, the target is considered to be at the center of theplaying field, but it could very well be anywhere withinthe defined boundaries of the playing field. ECHOES TO POSITION VECTORSReferring to Figure 1, the corners of the square playingfield are labeled in clockwise order from A to D. Ultra-sonic sonar transceiver beacons/active mirrors are placedat three of the corners of the playing field, at the cornersmarked A, B, and D.The beacons are unique in that they have an assignedname or address, and, as slaves, only speak when spokento. The robot is the system master and polls the beaconsin turn, then measures the delay between the poll and thecorresponding response. For each beacons poll/responsedelay count, a propagation-delay arc is constructed fromtheir vertices where the point of intersection of the arcsmarks the robots position.The distance between the robot and each of the beaconsis determined by measuring the extended propagationdelay of the ultrasonic signal in air, which is roughly150 s per inch, round trip time. (Note: Extended/padded, round-trip propagation delay = Tprop + 50 ms.Having the beacon wait 50 ms to issue a response enablesreal, direct playing field echoes to decay. After 50 ms,received echoes should all be beacon responses.) Thelengths of the adjacent radius vectors are Ra, Rb, and Rd.Assuming the origin of the grid to be coincident with cor-ner A of the playing field, vector Ra terminates on therobots position (X, Y) at a distance from the origin, cour-tesy Pythagoras.However, from beacon Bs perspective, the position of therobot is (X, S Y), making the length:Similarly, from beacon Ds perspective, the robots positionis at (S X, Y) at a distance of:Working with the squares of the Radius vectors andsolving for X and Y we get:Note that the numerator of the second terms in the aboveequations are the difference of two squares, and can befactored into sum and difference terms: (Ra + Rb) (Ra Rb)= Ra2 Rb2. Also note the possible range of values forthese terms on our 64 64 playing field. For example, ifthe robot is in close proximity to position C [coordinates(S, S)], then:Rb and Rd = 64. This makes (Ra Rb) = 27 and (Ra + Rb)= 155. These values are easily accommodated in a singlebyte, and their 16-bit product can be computed using asimple 8-bit 8-bit multiplication routine. The denomi-nator of the second terms is fixed and equal to 128(0x80). Division by 128 using binary arithmetic is accom-plished either by performing seven right shifts of the sec-ond terms numerator, or by a single roll-left-file (RLF)Ra = + Y2X2( )Rb = + S Y X22 ( ){ }Rd = X + Y2S ( ){ }2XX = S2 + Ra Rd S Y = S2 + Ra Rb S = 32 2 22 2( )( )22++ Ra + Rd Ra RdY = 32 + Ra + Rb Ra ( ) ( ) { }( ) 128 Rb ( ) { }128Ra = S = 9122 ( )www.circuitcellar.com CIRCUIT CELLAR21March 2012 Issue 26022CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260from the signs of X = (Xz Xu) and Y = (Yz Yu) andmore precisely from the magnitude of the slope of therobots current heading. The resulting change in positionmay be interpreted as a velocity vector (H), containingboth speed and direction information. At this point, how-ever, we are only interested in the directional informa-tion (slope) contained in the vector:In support of further discussion, we label the quadrantsH XH slope ,( ) Y = V U = Xv Xu + j Yv Yu = ( ) ( ) ( ) YX = Yv YuXv Xu ( ) ( )instruction of the numerator:In the second case, the second-term numerator is leftshifted once, changing 0x05A0 into 0x0B40, with theinteger part of the result in the most-significant bit (MSb)and the fractional part of the division in the least-signifi-cant bit (LSb). If bit 7 of the 16-bit result is set, add one(1) to the integer value.Repeat the process using Ra and Rb, and calculate thevalue of Y. The robots position, relative to the playingfield origin at the location of beacon A, may be calculated.Furthermore, with prior knowledge of the target positioncoordinates, we can compute the distance to the target,but I am getting ahead of myself.DETERMINING ROBOT HEADINGHaving determined the robots current position at pointU (Xu, Yu), we know in which quadrant the robotresides. However, being blind, we do not know in whichdirection the robot is pointing, so we must move therobot to a second point to find out. We call this secondpoint Z (Xz, Yz) and see how our position coordinateschange as a result. In the real world, one would consultone or more sensors to see if the coast is clear beforemoving into harms way and perhaps falling off the edgeof mother earth. But thats another story.By taking the difference between the coordinates of Zand U, we can determine the robots general directionFor Ra = 77 and Rd = 67: X = 32 + 1,440128 = 43or X(Hex) = 0x0020 + 0x05A00x80 = 0x05A0 >>>>>>> 0x000B = 0 05 00 80x Ax111 (base 10)or 0x05A0 < 0x0B40 = 11 64and 32 + 11 = 43Figure 2Thequadrants of thesquare playingfieldS = 64 Units [0, S] BA [0, 0] D [S,0]S = 64 UnitsC [S, S]Quadrant B(Xt Xu),(Yt Yu) = = (+, ) Quadrant C(Xt Xu),(Yt Yu) = = (, ) (Xt, Yt)2 (Xz, Yz)Z-U(32, 32)Distance to target location =0 is the angle the robot must turn through to point in the direction of the target0Quadrant A(Xt Xu),(Yt Yu) = = (+, +) Quadrant D(Xt Xu),(Xt Xu) = = (, +) 2 (Xt - Xu)2 + (Yt - Yu)2 Tforarget position = Xt, Yt Xt, Yt = Center = 32, 33( )( ) ( )ddX = Xz Xu dY = Yz Yufor negative dX sign and posi ttive dY signAction Table 1 says:Rotate CW and go forwardPllaying field diagonal = 90.5 units Ra = Xa + Ya Rb = Xa + S 2 2 22 2( )( )12 Ya Rd = S Xa + Ya from R2 2( ) ( )223 ( )aa Rd S2 + Ra + Rd Ra Rd Sand Ra2 22 ( ) ( ) ( ) ( )Xa2 Rb S2 + Ra + Rb Ra Rb SRecallin2 ( )= ( ) ( ) ( )Ya2gg that R = Vs Td2 and defining one until time del aayas the 3" round-trip prop delay, the playing field is 166' squareU (Xu, Yu)Table 1Position and heading-dependent action tableQuadrant Sign X Sign Y ActionA + + Go straight+ Rotate CCW and go + Rotate CW and go Back up and rotate CWB + + Rotate CW and go+ Go straight + Back up and rotate CCW Rotate CCW and goC + + Back up and rotate CCW+ Rotate CW and go + Rotate CCW and go Go straightD + + Rotate CCW and go+ Back up and rotate CW + Go straight Rotate CW and gowww.circuitcellar.comCIRCUIT CELLARMarch 2012 Issue 26023rise to the question: how much rotation is required? Toanswer that question, one needs to calculate the anglebetween the robots current heading and a vector fromthe robots position to the target position. At first, I con-sidered using the dot-product method, but I discoveredthat I would need an arc-cosine look-up table and aninterpolation routine to calculate the turn angle. I hatelook-up table solutions except where there is no othersolution; therefore, I looked into other solutions, andonce again Euler came to the rescue! Manipulating Eulers exponentials one comes up withEquations 1 and 2 below, which calculate the componentsof a new heading vector, in terms of the components ofof the playing field A, B, C, and D in accordance with thecorner references used in previous discussion (see Figure 2).If the robot finds itself in quadrant A, it knows it mustmove in the general northeast direction to close the dis-tance to the targeted center of the field, at coordinate(32, 32).Table 1 defines, in a general way, the next course ofaction based on the signs of X and Y. We use this signinformation later on in the test code to set or clear adirection flag bit that is used to select between CW orCCW equation in the code.Note that three of the four prescribed actions in eachquadrant include a rotation of the platform. This givesTable 2Fractional value of a byte and sine and cosine of binary anglesBit # Fractional Value Cos(Angle) Cos(Angle) Angle Sin(Angle)7 0.5 255/256 0.9961 5.065929 0.0883026 0.25 254/256 0.9922 7.166643 0.1247565 0.125 253/256 0.9883 8.780177 0.1526444 0.0625 252/256 0.9844 10.14179 0.1760853 0.03125 251/256 0.9805 11.34258 0.1966752 0.015625 250/256 0.9766 12.42926 0.2152341 0.0078125 249/256 0.9727 13.42954 0.2322490 0.00390625 248/256 0.9688 14.36151 0.248039247/256 0.9648 15.2377 0.262824sum 0.99609375 246/256 0.9609 16.06725 0.276765= cos(5.066) 245/256 0.957 16.85704 0.289985www.robotpower.comPhone: 253-843-2504 s [email protected] MotorSpeed Control!Scorpion XXL6 7V - 28V 6 Dual 40A+ Peak H-Bridges6 Current/Temp limiting6 R/C inputs w/mixing6 Optional enclosure6 3.25 x 2.25 x .5MegaMoto Plus Shield6 7V-28V - H-bridge or Dual Half-bridge6 20A Continuous - 6 Current sensor outputs can be sent to any analog pin6 Up to three units can be stacked on one Uno or compatible6 Independent half-bridges can control brushless/steppers too!40A peakMADE INTHE USACheck out our othermotor controls 2A - 160AMarch 2012 Issue 260CIRCUIT CELLARwww.circuitcellar.com24the robots current heading vector, the desired directionand angle of rotation.[1][2]Unfortunately, we do not know the total angle of rota-tion. However, we do know what our heading should beto match the course to the target. And as luck will haveit, we can use Equations 1 and 2 in an iterative process tocalculate the angle to the target destination. (Note theuse of in Equations 1 and 2.)When computing the cos( + ) and sin( + ), weare talking about a counter-clockwise rotation of therobot heading vector by degrees. Furthermore, cos( ) and sin( ) performs a clockwise rotation of theheading vector by degrees. Table 2 is used to select themost direct direction of rotation.To use Equations 1 and 2 iteratively, we need to selecta suitably small and fixed angle that gives reasonableangular resolution and whose binary values are consis-tent with an 8-bit solution. Luckily, by interpreting abytes contents as a fraction, we discover that we canobtain a resolution of 5.We are now in a position to look at the quality of theresults of our algorithm, as implemented in machinelanguage, and relative to a floating-pointsolution performed in an Excel spreadsheet.The machine code, which can be found onCircuit Cellars FTP site, was tested usingthe Microchip IDE code simulator, and isthe source of the data used in the plot ofFigure 3. Figure 3 contains three plots, thereference trace being the upper-most floating-point plot delineated by the diamond datapoints. All three plots start from coordinate(20, 10). The plot directly below the refer-ence shows the results taken from themachine code for an increasing step-angle(CCW) of 10. The lower plot is again fromthe machine code, but for a decreasing stepangle, CW. The magnitude radial distancefrom the center of the plot for the floating-point solution is very stable, as expected.The magnitude of the machine code solu-tion spirals inward in the CCW direction.Nevertheless, the angular progression of thevector is quite regular, which is the mostimportant feature since it is the heading orslope of the destination vector that mattershere.VECTOR PARALLELISM TESTThe test for vector parallelism uses Equation 3R = X n + 1 X n cos Y n sin ( ) ( ) =( ) ( ) ( ) ( )cos R sin = Y n + 1 =Y n cos X n sin ( ) ( )( ) ( ) ( ) ( ) as a zero-crossing detector.[3]We exit the iteration process on a change of sign of theindicated sum. Upon completion of the iterative calcula-tions, the angle through which the robot must turn toalign its heading with the target destination vector isthe product of angular step size used in the calculationsand the iteration count. It is now up to the robot hard-ware to effect the required change of course and make Ytarget Yrobot Xtarget = 0where ( ) ( ) Xrobot Ytarget = Ytarget Yrobot, Xtargett = Xtarget Xrobot, Yrobot = Yrobot2 Yrobot1,and Xrobot = Xrobot2 Xrobot1 Figure 3The 10 step size, floating point versus machine language algorithmTo keep things simple on the sensor front,it is best if the robot has an omnidirectionalultrasonic sensor to communicate with thesystem beacons. In this way, the robot neednot be concerned with having to find, andthen point at, the appropriate beacon beforeit can issue a robust poll of the beacon forranging purposes. One waythe expensivewayis to use multiple ultrasonic sensorsin a circular array to achieve coverage. www.circuitcellar.comCIRCUIT CELLAR25March 2012 Issue 260PROJECT FILESTo download the code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2012/260.SOURCESPIC16Fxx Family of microcontrollers, IDE code simu-lator, and PIC12F609 microcontrollerMicrochip Technology, Inc. | www.microchip.comLarry Foltzer ([email protected]) was employed for 30years in the fiber optics communication industry. First, hecofounded Optelecom, Inc. A decade later, his focus shiftedto data and telecommunications. For Motorola, he participatedin the IEEE-802 MAC subcommittee on Token-Passing accesscontrol methods. Later, Larry was the System Architect of theRaychem/Raynet Passive Optical Network System.its way to the target.The code on Circuit Cellars FTP site does not performthe zero-crossing function. That task is a simple processthat is left to you.ALGORITHM TEST CODEThe code on the FTP site is for your enjoyment. It waswritten and simulated using Microchips IDE for thePIC12F609 8-bit microcontroller. The selection of aprocessor for testing was arbitrary and simply to ensureit was code-compatible with other microcontrollers con-sidered for this application.I placed the variables in the GPR space so they show up inan orderly place when displayed in the simulator window.Furthermore, I broke up the code into functional blocks toaid readability. All is displayed in a twos complement in thesimulator.ULTRASONIC SENSOR MODIFICATIONSMore work in progress? To keep things simple onthe sensor front, it is best if the robot has an omnidirec-tional ultrasonic sensor to communicate with the sys-tem beacons. In this way, the robot need not be con-cerned with having to find, and then point at, the appro-priate beacon before it can issue a robust poll of the bea-con for ranging purposes. One waythe expensive wayis to use multiple ultrasonic sensors in a circular arrayto achieve coverage. An alternative is to use a conicalacoustic mirror (see Photo 1). Will it work? I dont knowyet, but do know there is no free lunch. Spreading thebeam will decrease transmitted power density. However,that was the reason to go with an active mirror conceptin the first place, where signals are unidirectional andare not subject to the loss associated with the albedo ofthe target.LEARN, BUILD & PROSPERWell, there you have it. There is nothing new here thathas not been done before. However, the application of themathematics and its implementation in machine code torobotics was new and a fun thing to do. And I did it myway. I hope newcomers to the field find this work usefulenough to build upon it and prosper! IPhoto 1A conical acoustic mirrorNEED-TO-KNOW INFOKnowledge is power. In the computer applicationsindustry, informed engineers and programmersdont just survive, they thrive and excel. For moreneed-to-know information about some of the topicscovered in this article, the Circuit Cellar editorialstaff recommends the following content:A Sensor System for Robotics Applicationsby Guido OttavianiCircuit Cellar 236, 2010This article covers how to add senses to aninteractive robotics platform, from sight to hearingto touch and more. Topics: Robotics, Sensors, ADC,Arduino I2C, Ultrasonic PhotoresistorVision-Guided RoboticsA Next-Generation Balancing Robotby Hanno SanderCircuit Cellar 224, 2009Are you interested in building a sophisticated,vision-guided, balancing robot that can interactwith its environment? You can tackle this projectwith a Parallax Propeller, a handy design kit, and aninexpensive camera. Topics: Robotics, Vision, FuzzyLogic, Propeller, ViewPortRobot Localization and Controlby Ethan Leland, Kipp Bradford, and Odest ChadwickeJenkinsCircuit Cellar 188, 2006This team shows you how to use wireless nodesto simultaneously localize and control a WowWeeRobosapien humanoid robot. The ZigBee nodesoutputs mimic the control signals. Topics: Robot,Wireless, ZigBee, GUIGo to Circuit Cellars webshop to find these articlesand more: www.cc-webshop.com26 CIRCUIT CELLAR www.circuitcellar.comMarch 2012 Issue 260Now in its final month, the DesignSpark chipKITTMdesign challengefor energy-efficient applications is still open for submissions. So, ifyoure quick,Last Chance to Enter theDesignSpark chipKITTMChallengeTADVERTISEMENTby Ian Bromleyhe DesignSpark chipKITTMcompetition is now in its final weeks, and there remains just enough time toenter for a chance to win a prize. Total cash prizes of$10,000 are there to be won, including a first prize of$5,000. The response and enthusiasm for the competitionhas been fantastic and weve been delighted by the highquality of the submitted ideas. As a reminder of what hasgone before, or for those hearing about this for the firsttime, the DesignSpark chipKITTMchallenge is all aboutencouraging engineers, students, and hobbyists to developnew and innovative energy-efficient solutions, while alsomaintaining an eco-friendly footprint.So, as the competition approaches its climax, entrantswill now be well advanced in their designs for energy-efficient and environmentally friendly applicationsbased on the chipKITTMMax32TMArduino-compatibledevelopment platform from Digilent. The kit featuresMicrochip Technologys 32-bit PIC32 micro-controller and enables developers to easilyand inexpensively integrate electronics intotheir projects. Just to whet your appetite forthe smorgasbord of ideas weve had, here arejust a few of them weve receivedwhich arealso available at the online DesignSpark com-munity at www.designspark.com. One very interesting project is the develop-ment of an unmanned underwater vehicle(UUV) that employs gliding as its method ofpropulsion, enabling the UUV to operate for anextended period of time due to its extremelylow power consumption. An extender boardbeing developed for the vehicle will interface tothe sensors and actuators required for operationof the UUV. The design will include a three-axisaccelerometer, a three-axis gyroscope, and a three-axismagnetometer for underwater orientation, in addition to aglobal positioning system (GPS) receiver to determineglobal position on the surface. A buoyancy engine, togetherwith pitch and roll actuators, will control the UUVs move-ment through the water. In addition CTD sensor willmeasure conductivity, temperature and depth, with thedata being recorded in flash memory on board the UUV,enabling profiling of salinity characteristics.Another project is a hydroponics water and nutrient-control system that will monitor climatic conditions todetermine the level of nutrient-feed requirements forplants in a hydroponic environment, thereby saving onwater usage and nutrient chemicals. As most hydroponicsfarms currently use established feed regimes that runwithout adjustment for environmental conditions, thedesign could deliver both financial and water savings.A smart garden project for the control of the natu-ral cycle of a plant with minimal human interventionis yet another innovative entry. The project aims tocombine renewable energy sourcessuch as solarpowerwith low energy consumption of the board con-trol circuitry operating at significantly reduced power.The system will include various sensors such as thosefor humidity, temperature, and light, and actuatorssuch as an irrigation pump. Additionally, the modularsystem will also be able to be expanded, for example,adding Bluetooth technology to enable user notifica-tionsa possibility created by the ongoing Internet ofThings revolutionabout which we expect to be hear-ing a great deal more this year.And these are just three of many highly innovativeongoing projects. As a quick final reminder on thecompetition, all entries must include an extensioncard developed using RSs free-of-charge and award-winning DesignSpark printed circuit board (PCB) soft-ware tool with code compiled using MicrochipsMPLAB IDE software. Entrants are also stronglyencouraged to engage and interact with other membersof the online DesignSpark community by postinginformation on their projects, providing updates onprogress, and sharing comments and ideas on theirrespective designs. Participants will automatically qualifyfor entry into bonus Community Choice Awards, inaddition to admission into spot prize draws for the bestcollaboration to win vouchers exchangeable for productsordered from RS Components/Allied Electronics.The competition entries will be judged on the level ofenergy efficiency and the quality of the extension cardsPCB design. Entries are due on March 27, 2012 and thewinners will be announced in April 2012. Further detailsand registration for the DesignSpark chipKITTM challengeare available at: chipkitchallenge.com.Ian Bromley is a Technical MarketingEngineer at RS Components and theProject Manager for the DesignSpark PCBsoftware tool. Prior to working for RS, Ianworked for many years as a design sup-port consultant with Texas Instruments,in addition to working as a field applica-tions engineer immediately following hisgraduation in 1994 with an honorsdegree in Microelectronic Engineering.To register and enter the DesignSpark chipKITTMChallenge, go to: www.chipkitchallenge.comDeadlineWI N YOUR SHARE OF $10, 000 I N CASH PRI ZES!$5,000 rst prize$3,000 second prize$1,000 third prizeFive $200 honorable mention prizesFOR ENTRIESMarch 27, 2012 at 18:00 GMT (13.00 EST)www.chipkitchallenge.com he middle schoolers in my carpool asked how big my cell phone waswhen I was their age. Even in their 12 shortyears, they have seen how fast technologygrows. I told them, when I was 12, therewas no such thing as a cell phone. Now Ihad their attention. What did we have?We kids had pretty much the same kindof things as kids today, just less powerful.We had phones, but they were wired to awall in the kitchen. We had game consolesthat hooked up to the television. They werenot high-definition or online, and they usedplastic cartridges instead of CDs, but theprinciple was the same. We had arcadeswith lots of noisy flashing video games thatwould hypnotize you into dribbling awayyour allowance one quarter at a time. Nowthe classic machines huddle togetherbehind the skee-ball tables in restaurantswhere animatronic mice hypnotize you intobuying pizza. But the classics are stillthere. Nothing ever dies in this age of eBay,Wikipedia, and YouTube.The big difference is the size and cost.The same TV game console I played as akid now fits inside its joystick along with adozen of the best games. You can buy the28CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260The only thing more exciting than gaming is gaming on a system you develop. Readyto hack an old joystick? You can remove the circuit board and add a custom gamesystem that reads games from an SD card. This article details how to create a virtualmachine in a Propeller chip for the arcade hardware of a classic game.All-in-One JoystickTFEATUREARTICLEby Chris Cantrell (USA)Build a Propeller-Based TV Gaming Platform Photo 1This is the complete system in action. The portable DVD/TV display is turnedsideways to match the rotation of the arcade monitor in the real system.www.circuitcellar.comCIRCUIT CELLAR29March 2012 Issue 260three round buttons labeledReset, Select, and Start. I leftthis board in place but cut tracesand rerouted wires so that oneside of each switch is groundedto the negative terminal of the6-V battery pack. I left the powerswitch on the front of the joy-stick intact, but I rewired thetiny red power LED as a general-purpose output to be controlledby a Propeller I/O pin. Thus, thehacked mini board provides sixwires to the main board: 6 V,ground, an LED output, andthree switch inputs.I pulled the main board outand used it as a template for anew circuit board (see Photo 2).The main board has five contactpads for the five joystick con-trols (left, right, up, down, andfire). Each pad is a circular areawith two traces that weavearound one another withoutactually touching. A conductivefoam disc encased in a springyyellow case mounts above eachpad. When the button ispressed, the disc presses against the circuit board andshorts the two woven traces together. When the buttonis released, the yellow casing pulls the disc up andbreaks the contact.The joystick shaft sits above the four directional but-tons. Mechanical linkages push the buttons down whenthe joystick is moved in the four directions.I carefully measured all the screw holes, pads, andmounting holes and transferred them to my circuit boardusing the free ExpressPCB software. I went throughdozens of tedious print, compare, and tweak cycles. But Iended up with a board that matched the original circuitboards pad and mounting configuration.THE PROPELLER CIRCUITI used the same basic Propeller processor circuit in thisproject that I have used in many others (see Figure 1). ThePropeller chip requires very few external components: aserial EEPROM, a crystal, and a pull-up resistor. Anotherfour resistors are all you need for complete NTSC videoand audio. Each switch from the joystick is grounded onone contact and pulled up to 3.3 V with a 10-k resistor atthe Propellers port pin. I used an SD-MMC card breakout board from SparkFunElectronics. There is just enough room in the joystickunder the main board for the breakout board. (Refer toPhoto 2.) I cut a slot in the side of the joystick and gluedthe breakout board to the top of the battery compart-ment. I cut another slot in the other side of the casing forJakks Atari Classics joystick for the same price youwould have paid for a single Atari 2600 game cartridgeback in the day. Jakks Pacific also makes several arcade collection joy-sticks. Each has a different handful of classic machinesshrunk down into a joystick. You can buy one from theweb for the same roll of quarters you would carry to thearcade. What wonderful times we live in!What Jakks doesnt make is a joystick with an SD cardslot for switching games. They dont own the rights tothe old classic games, after all. They own their hardwareand they are in the business of selling plastic joysticksnot SD cards.But we electronics enthusiasts have shrunken inexpen-sive electronics in our arsenal too! In this article Ill showyou how I replaced the circuit board in a Jakks joystickwith my own Parallax Propeller-based game system thatreads games from an SD card (see Photo 1). Ill also showyou how I created a virtual machine in the Propeller for thearcade hardware of the classic Space Invaders.HACKING THE ATARI JOYSTICKI chose the Atari 10-in-1 joystick because of its blandcasing. All the other game sticks I have seen have color-ful images for the games they contain. The Atari gamestick is just a generic black joystick with a few orangebuttons.There are two circuit boards inside the stick. A smallboard at the front of the stick provides contacts for thePhoto 2The replacement circuit board has five switch pads. One yellow conductive button isshown mounted. This yellow casing acts like a spring for the conductive disc inside. The circuitcomponents are soldered to the surface of the other side of the board.30CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260the four-wire programming interface.The real challenge was soldering the tiny surface-mount components, especially the 44-pin QFN Propellerchip. I bought a magnifying lamp with an adjustable armfrom an office supply store. I also bought a fresh solder-ing iron tip and a set of precision tweezers/probes fromthe local electronics store. Then I watched a few SMTtutorials on YouTube and began what felt like performingbrain surgery.EMULATING THE ARCADE HARDWAREThe Space Invaders arcade game released by TaitoCorp. in 1978 is surprisingly simple. The memory mapis split between 8-KB ROM and 8-KB RAM. Seven of the8 KB of RAM are tied up in the visual raster buffer. Thevideo generator, implemented in discrete 74xx logic,interrupts the processor twice per video frame: once atthe end of the screen and once in the middle. There arethree input ports for reading switches and DIP settings.There is an output port that resets a watchdog timer(WDT). There are 10 output port bits that trigger 10 dis-tinct sound effects implemented with specialized analogcircuits. There is a 16-bit shift register mapped into portspace that helps draw the large number of game sprites.The entire 16-KB RAM and ROM of Space Invadersfits neatly in just half of the Propellers shared memory.The boot process (Boot.spin) loads the ROM from an SDcard and launches the other COGs I will discuss later.The project files for this article, which are available onCircuit Cellars FTP site, include all the Spin code Iused in the joystick, but they do not contain the SpaceInvaders ROM. You must own the original hardware inorder to legally download the ROM from the web. Ibought a board set for $50 on eBay years ago. The clas-sics still pop up there from time to time.There are several SD card projects available for down-load from the Propeller object exchange on the Parallaxsite. I have used this same driver (Disk_hdw.spin) in sev-eral projects now. It is an early derivation from TomasRokickis work.VIDEO (SIVideo.spin)The Space Invaders hardware produces a 256 224 pixelblack-and-white (actually black and CRT green) display.Invader machines released in the U.S. used color trans-parencies to tint areas of the display, but the pixels them-selves were either on or off.The Propeller chip has built-in hardware to generateNTSC or PAL composite video. The TV.spin object in thePropeller library generates four-color pixels on a 256 208display. My SIVideo.spin is a modification of TV.spin thatgenerates a black-and-white display from the Space Invadersraster format. The driver spends most of its time doublingpixels so that 0 from the memory buffer becomes 00going to the waitvid Propeller instruction and 1 becomes11. The process is surprisingly time consuming.The generated TV display is 16 rows shorter than thearcade display. I chose to chop eight rows from the top andFigure 1The core of this circuit is straight off the Parallax Propeller demo board schematic. I have built this old friend in several projects,but this time I built it on a 2 square board with surface-mount components.www.circuitcellar.comCIRCUIT CELLAR31March 2012 Issue 260eight rows from the bottom. Thearcade display reads 32 224 bytesbeginning at RAM address 0x2400. Mymodified display reads 32 208 bytesbeginning eight rows in at 0x2500(i.e., 0x2400 + 32 8).The arcade monitor is rotated 90counter-clockwise inside the cabinet.This provides more pixels up anddown than left and right, and wascommon in the arcade classics (e.g.,Pac-Man, Galaga, Frogger, etc.). ThePropeller hardware, as well as myprogramming prowess, lacks thehorsepower to rotate the raster bufferbefore display. I took the easy wayout and just turned the TV on itsside (see Photo 1)!The video driver also writes thecurrent row number to shared mem-ory. Another COG reads this valueand sends hardware interruptrequests to the CPU at the end andat the middle of every frame (seeFigure 2). The game code updatesobjects at the bottom of the screenwith the end-of-frame interrupt.Game objects at the top of thescreen are updated at the middle-of-frame interrupt. This keeps animage from moving in the middle ofbeing drawn, which would producean unpleasant flicker.PORTSThe arcade CPU reads the switchesand DIP settings from input ports 0,1, and 2. These are all binary inputsproducing 0 when open and 1 whenclosed (pressed). Bit 2 of port 2 isconnected to a tilt switch that trig-gers when the machine is rocked. Inthe early 1980s you would havefound the Space Invaders cabinetright next to the pinball machines.So a tilt switch, like those foundin pinball machines, would not haveseemed that out of place. If youshake, slap, or otherwise abuse an SIcabinet, you will get a Tilt messageand your game will end.The port COG (SIPorts.spin) mapsthe buttons and switches on the joy-stick to the port bits as the SI codeexpects them. The Reset button onthe stick is the coin bit for the game.Select and Start are player-2-startand player-1-start, respectively.Pressing both at the same time sim-ulates a tilt. Port 6 in the arcadegame is used to reset the WDT. Thecode simply ignores these writes.Ports 3 and 5 control individualsound effects. The port COG codeFigure 2The COGs communicate with one another through parameter blocks in sharedmemory. The 16-KB RAM/ROM of the emulated system lives in the Propeller sharedmemory too.Shared memory COG COGSIDCOGSIVideoSI RAM (8 KB)SI ROM (8 KB)CurrentRowPortValuePortAddressPortCommandSoundBitsSID registersInterruptCPU_8080SISoundDisk_hdwSIPortsConnect With Design Engineers From Around The Globe.Strategic Media Marketing [email protected] Reserve advertisingspace in CircuitCellar and CCNews Notes today!combines the bit values from these two ports and passesthem on to the audio system.Drawing a pixel image requires a lot of bit shifting.Imagine a single byte image with all 1s. This is a short,solid line eight pixels long. If the image is drawn at X=0,the 8 bits all fit in a single byte. Thats the easy case. Ifthe image is drawn at X=1, then the image must beshifted one bit to the right making a 16-bit value. Thefirst 7 bits fit in the first byte of screen memory and thelast bit shifts into the second screen byte.The Space Invaders game has up to 60 moving objectson the screen at the same time (55 aliens, the player, andfour shots). But the 8080 instruction set has no directsupport for 16-bit shifting. To aid with the rendering, thehardware maps a 16-bit shift register to ports 2, 3, and 4.You write image data into the shift register throughport 4. When you write to port 4, the most-significantbit (MSb) of the 16-bit value becomes the least-signifi-cant bit (LSb) and the new value you write becomes thenew MSb. You write the shift amount to port 2. Thevalue can be 0 to 7. You then read the shifted data from32CIRCUIT CELLARwww.circuitcellar.comMarch 2012 Issue 260port 3. If the shift value is 0, then you read the MSb ofthe 16-bit shift register. If the shift value is 1, then youread the seven lower bits of the MSb and the one upperbit of the LSb.The port COG (SIPorts.spin) implements the shift reg-ister logic. Interestingly, only the four shot sprites in thegame take advantage of the shift register. The aliens arealways drawn on a byte boundary and the shift value isalways 0.Ports are like memory in that they have uniqueaddresses and you read and write them. But, unlike mem-ory, they are triggered by the read and write process.When you read from memory, you read the last value youwrote. But, when you read from a port, the hardwarelatches in the values of switches and such. The portCOG waits for port requests from the CPU. The CPUwrites the request to memory and then waits for the portCOG to respond. The serial exchange takes longer thanan access to shared RAM. But the command/responsepattern is necessary to capture the access triggering ofport hardware.Listing 2These are the first eight entries in the 8080 instruction decode table. Each 4-byte entry contains three jump vectors (for Get,Operation, and Set) plus two parameter fields. The complete table consumes 1 Kb of shared memory.dispatch_table 29 26 18 9 0 yyy_xxx_cccccccc_bbbbbbbbb_aaaaaaaaa VECTOR-1 (a) VECTOR-2 (b) VECTOR-3 (c) PARAM-V1 (x) PARAM-V3 (y) O