cover1.qxp 2/2/2007 3:43 PM Page 2

#200 March 2007 w w w . c i r c u i t c

e CIRCUIT® l l a r . c o m

CELLARTHE MAGAZINE FOR COMPUTER APPLICATIONS ROBOTICS Robotic Arm Servo Control Rolling Robot Circuit Cellar: ThenWWW.GiURUMELE.Hi2.RO & Now

03>

7925274 75349 $4.95 U.S. ($5.95 Canada) cover1.qxp 2/2/2007 3:44 PM Page 3

007 CIRCUIT CELLAR (1988 to Present) —Steve Ciarcia describes how he used his HCS to save a life (“A Home Control Event Worth Remembering,” Circuit Cellar 199) “Inside the Box Still Counts” — This was the title of my very first Circuit Cellar INK —George Martin is back with a C language tutorial editorial 19 years ago. Two hundred issues later I still believe it. Like solder being my favorite programming language, I still believe that however appliance-like 2007 (“Hello World … Want Cookie,” Circuit Cellar 198) embedded control and personal computing implementations become, we can’t for- get that the process of achieving that goal isn’t instant. In order to create the —Ed Nisley provides tips for choosing voltage references sophisticated devices and technologies regarded as off-the-shelf, many people (“Voltage References,” Circuit Cellar 193) still have to maintain real expertise in rudimentary design skills. Basically, some- —Tom Cantrell covers using the ’Net as a long RS-232 cable body always has to know what’s inside the box. —Steve Ciarcia, “Inside the Box Still Counts,” Circuit Cellar 200, 2007 (“Device Surfer,” Circuit Cellar 192) —Atmel AVR Design Contest 2006, Sponsored by Atmel, 2006 2006 —DesignStellaris2006 Contest, Sponsored by Luminary Micro, 2006

—Jeff Bachiochi on VoIP (“A Fresh Look at VoIP,” Circuit Cellar 180) —Fred Eady explores embedded Wi-Fi (“Embedded Wi-Fi with TRENDnet,” Circuit Cellar 174) 2005 —M16C Design Contest, Sponsored by Renesas, 2005

—Steve Ciarcia comments on new technology: TiVo (“To TiVo or Not to TiVo,” Circuit Cellar 167) —Jeff Bachiochi covers USB in embedded designs (“USB in Embedded Design,” Circuit Cellar 165) —Wireless Design Challenge, Sponsored by Freescale Semiconductor, 2004 IT — 2004 Flash Nets Cash Design Contest, Sponsored by Zilog, 2004 —PSoC High Integration Challenge, Sponsored by Cypress MicroSystems, 2004 2004 —AVR 2004 Design Contest, Sponsored by Atmel, 2004

—Fred Eady on USB connectivity (“Mission Possible: Achieve Cheap USB Connectivity,” Circuit Cellar 157) —Motorola E-Field Sensor Contest & Flash Innovation 2003, Sponsored by Motorola, 2003 —Zilog Flash for Cash Z8 Encore! International Design Contest, Sponsored by Zilog, 2003 2003 —Renesas H8 Design Contest, Sponsored by Renesas, 2003

—Tom Cantrell on new sensor technology (“Sensors and Sensibility,” Circuit Cellar 148) —Jeff Bachiochi describes a smart brake light design (“Smart Auto Brake Light Eliminates Turn Indicators,” Circuit Cellar 148) —Mad Dash for Flash Cash, Sponsored by Microchip, 2002 2002 —PSoC Design Challenge 2002, Sponsored by Cypress MicroSystems, 2002

—Steve Ciarcia introduces the Electronic Edition (“Electronic Evolution,” Circuit Cellar 126) —Ultra-Low Power Flash MCU MSP430 Design Contest, Sponsored by Texas Instruments, 2001 —Design Logic 2001, Sponsored by Atmel, 2001 R 2001 —Driven to Design, Sponsored by Zilog, 2001

—Steve Ciarcia comments on Y2K, (“You’ve Got to be Y2Kidding,” Circuit Cellar 115) —Design2K, Sponsored by Philips, 2000 2000 —PIC 2000, Sponsored by Microchip, 2000

—Jeff Bachiochi on JTAG (“JTAG: Working with CoolPID,” Circuit Cellar 104) —George Martin’s first Lessons From the Trenches column (“Off-the-Shelf Data Acquisition Using Visual Basic,” Circuit Cellar Online) 1999 —Design99, Sponsored by Motorola, 1999

—Steve Ciarcia and Jeff Bachiochi design an entry and exit system (“Gotcha! Alarming the Alarm System,” Circuit Cellar 95) 1998 —Design98, Sponsored by Microchip, 1998

—Fred Eady on networking embedded and desktop PCs (“Sweet Solution,” Circuit Cellar 79) 1997 —Tom Cantrell describes micropower impulse radar (MIR) technology (“Radar Love,” Circuit Cellar 79)

—Steve Ciarcia describes an enlightening experience at the Trinity Robotics Competition (“Bots Got No Respect,” Circuit Cellar 71) 1996 —Ed Nisley updates his ImageWise receiver by adding an HCS TV display (“Firmware Furnace (Part 1): Getting Vid-Link in Sync,” Circuit Cellar 66)

—Fred Eady’s first article (“Take Your PIC: A Look at the PIC16Cxx Family,” Circuit Cellar 65) 1995 —Tom Cantrell provides a comparison of speed and handling tips and tricks (“A Saab Story: A Tale of Speed and Acceleration,” Circuit Cellar 57)

—Dave Tweed’s first article (“Designing Real-Time Embedded Software Using State-Machine Concepts,” Circuit Cellar 53) 1994 —Circuit Cellar’s 50th issue (September 1994)

—Steve Ciarcia on the race for PC power (“The Race for Power,” Circuit Cellar 39) —Tom Cantrell on LED technology (“Smart LEDs,” Circuit Cellar 31) WWW.GiURUMELE.Hi2.RO1993 —Circuit Cellar goes monthly (Circuit Cellar 31) —Steve Ciarcia describes a night of automated home control (“A Night in the Life,” Circuit Cellar 26) —Ed Nisley on IR home control (“Infrared Home Control Gateway,” Circuit Cellar 26) 1992 —Jeff Bachiochi on electronic identification technology (“Electronic Identification,” Circuit Cellar 24)

—Ed Nisley presents data for the Furnace Firmware Project (“The Furnace Firmware Project Concludes: Hard Data for Home Control,” Circuit Cellar 21) 1991 —Steve Ciarcia on portable PC technology (“Why Portable?,” Circuit Cellar 20)

—Steve Ciarcia comments on analog technology (“An Analog State of Mind,” Circuit Cellar 13) Without a continuous effort at understanding and improving present achievements, —Tom Cantrell reports on the Second Forum (“Earthshaking Chips,” Circuit Cellar 13) 1990 we cannot progress to higher levels of achievement. Circuit Cellar Ink is a publica- tion designed to increase that awareness. We must not ignore the fact that it is a —Ed Nisley on cache (“Cache Craziness,” Circuit Cellar 11) combination of people AND machines that creates intelligent personal systems. 1989 —Steve Ciarcia presents the results from the first reader survey (“First INK Reader Survey,” Circuit Cellar 7) Whether they be applied as toaster-like appliances throughout an industry, serve as a control system of a CAT scanner, or function as a video arcade game, the basic ingredients of computers are similar. It is the continual evolution of a computer’s —Jeff Bachiochi’s first article (“RS-232 Economic Tradeoffs: Board Space vs. Parts Count vs. Parts Co$t,” Circuit Cellar 5) concept, design, and application which ultimately results in the perfection of the truly 8 —Tom Cantrell’s first article (“RISC vs. Reality: An Exercise in Acronyms,” Circuit Cellar 1)

8 Intelligent Personal System. —Ed Nisley’s first article (“High Security on a Budget: Build a Video Hand Scanner/Identifier,” Circuit Cellar 1) 9 — Steve Ciarcia, “Inside the Box Still Counts,” Circuit Cellar 1, 1988 1 —Steve Ciarcia starts the ball rolling (“Inside the Box Still Counts,” Circuit Cellar 1) C2.qxp 2/2/2007 10:22 AM Page 2

Announcing the NetBurner PK70 EMBEDDED CONTROL PRODUCT KIT Create a finished product in one day

The design of a finished product

Aluminum Enclosure Customizable Logo Built-in Power Supply

The flexibility of a module

32-Bit Freescale ColdFire 147 MHz CPU 8MB SDRAM - 2MB Flash Memory SD/MMC Flash Card Support I2C - SPI - Address and Data Bus 10/100 Ethernet 3 UARTs

The powerpower of NetBurner’sNetBurner’s DevelopmentDevelopment Suite

NetBurner Eclipse IDE Flash File System WWW.GiURUMELE.Hi2.ROGraphical Debugger HTTP Web Server µC/OS RTOS TCP/IP Stack ANSI C/C++ Compiler and Linker E-Mail Deployment Tools FTP Example Programs PPP

Product No. | NNDK-PK70-KIT Information and Sales | [email protected] Web | www.netburner.com Telephone | 1 C2.qxp 2/2/2007 10:23 AM Page 3

Customize with NetBurner Personality ay Boards

Use a standard NetBurner Personality Board Analog to Digital Converter Board T Digital I/O ADC Combo Board Digital I/O Board

Or create your own board with a custom connector

Integrated MCF5270 based processor board with Ethernet

Ethernet Serial Power

Featuring WWW.GiURUMELE.Hi2.RONetBurner’s Eclipse IDE

ephone | 1-800-695-6828 M 1.qxp 1 than skin than deep. Bea CapSense. inputs inyourproduct.CapSenseenables: replaces buttons,switches,slidersandothermechanical CapSense PSoC solutiontocreateastylish,durableinterface. Maximize thedesignflexibilityandintegrationofCypress’s PSoC / 30 design toolsallowingcustomized,system-leveldesign. visualembedded Quick time-to-marketwithpowerful, etc. –allwiththesameCapSensechip. monitoring,motorcontrol,ambientlightsensing, battery Unique integrationofadditionalfunctions–LEDcontrol, detectors –onavarietyofconductivesubstrates. buttons, sliders,touchscreens,touchpadsandproximity – multipleinterfaces Single-chip implementationsupporting or module;youareincontrolofyourdesignatalltimes. through production.CapSenseisnotafixed-functionASIC Fast changestoyourdesignatanystagefromconcept / ® 2007 4:30PMPage1 -based CapacitiveTouch Sensing Cypress, theCypresslogo andPSoC areregistered trademarksof CypressSemiconductor Corporation. Allother trademarks arepro WWW.GiURUMELE.Hi2.RO ismore uty www.cypress.com/capseminar Register foraCapSenseNetSeminar: www.cypress.com/capexpress Download freePSoCExpress www.cypress.com/capchips Request freePSoCCapSenseICsamples: www.cypress.com/capkit Order adiscountedCapSenseDevelopmentKit: GET ST Applications enabledbyPSoC perties oftheirrespective owners. ©2007Cypress Semiconductor Corporation. Allrightsreserved. perties ARTED WITHCAPSENSENOW www.cypress.com/gocapsense Streamline yournextdesignwithCapSense: ® CapSense. ™ visualembeddedsoftware: 2.qxp 2/2/2007 3:11 PM Page 1

Link Instruments PC-Based Test Equipment Digital Oscilloscopes • 2 Channel Digital Oscilloscope • 500 MSa/s max single shot rate • 1Mpt sample memory NEW! 250 MSa/S (Dual channel) 512 Kpts 500 MSa/S (Single channel) 1 Mpts • Advanced Triggering • Only 9 oz and 7” x 3.5” x 1.5” • Portable and Battery powered • USB 2.0 • Advanced Math • FFT Spectrum Analyzer • $950 (DSO, Probes, Software & power supply)

500MSa/s 1Mpts

Windows Screenshot Logic Analyzers

• 40 to 160 channels • up to 500 MSa/s • Variable Threshold • 8 External Clocks • 16 Level Triggering • up to 512K samples/ch • USB 2.0 and Parallel Interface WWW.GiURUMELE.Hi2.RO• Pattern Generator option LA5240 (200MHz, 40CH) $1700 LA5280 (200MHz, 80CH) $2350 LA5540 (500MHz, 40CH) $2500 LA5580 (500MHz, 80CH) $3500 Windows Screenshot LA55160 (500MHz, 160CH) $7500

Link Instruments (973) 808-8990 17A Daniel Road East · Fairfield, NJ 07004 · Fax (973) 808-8786 www.Linkins4.com CS-Uversion-8.375x11.125_53.qxd3.qxp 1/31/2007 9:03 AM Page 12/14/06 1 2:58 PM Page 1 D F V

Drop-in Replacement for LCD Modules N The new family of U-Version modules is compact, low power and lower in cost with a

O custom designed chip. This new VFD technology has an 8 and 4 bit parallel interface I

and enables the replacement of LCD's with Noritake U-Version VFD modules. S

R LCD E V - U

VFD

UPGRADE Brightest Display NOW... Widest Viewing Angles Widest Temperature Range Fits Right In WWW.GiURUMELE.Hi2.RONo Programming Change Low Cost

www.noritake-elec.com/53 Noritake Co., Inc. 2635 Clearbrook Dr., Arlington Heights, IL 60005 phone 1-800-779-5846 e-mail [email protected] 200_masthead.qxp 2/2/2007 3:53 PM Page 4

TASK MANAGER

Issue 200 FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia Remember the days when you had to pull into a gas station and drop a coin in a pay MANAGING EDITOR MEDIA CONSULTANT phone to make an important call? Today you use your Bluetooth-enabled cell phone as C.J. Abate Dan Rodrigues you’re in transit. WEST COAST EDITOR CUSTOMER SERVICE Remember how you used to have to mark up an actual map before you took off on Tom Cantrell Debbie Lavoie a road trip? Today you simply log your destination on a web site and hit Print. Some of CONTRIBUTING EDITORS CONTROLLER you even have interactive navigation systems that tell you how to avoid traffic jams and Jeff Bachiochi Jeff Yanco Ingo Cyliax toll booths on the way to your destination! Fred Eady ART DIRECTOR KC Prescott Remember how you used to have to order all of your parts (from MCUs to LEDs) George Martin with a mail-in form or over the phone? Today you simply click a few buttons and every- Ed Nisley GRAPHIC DESIGNER Mary (Turek) Sobuta thing you need is shipped overnight. NEW PRODUCTS EDITOR John Gorsky I could go on and on for another six paragraphs. The point is, a lot of things have STAFF ENGINEER John Gorsky changed since 1988. But one thing hasn’t: a brand new edition of Circuit Cellar hits the PROJECT EDITORS Steve Bedford newsstands each month. And for those of you who have been subscribers since the Ken Davidson beginning, you have 200 great issues to prove it. David Tweed th This month we’re celebrating the 200 edition of Circuit Cellar. To do so, we’ve ASSOCIATE EDITOR packed this issue with great feature articles, columns, and more. For instance, check Jesse Smolin out our special foldout cover if you haven’t already.There, we provide you with a look at the history of Circuit Cellar. It’s amazing how writers like Steve Ciarcia, Tom Cantrell, ADVERTISING Jeff Bachiochi, and Ed Nisley have been so far ahead of the technological curve for so 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise many years. They’ve been covering the technologies of tomorrow in the pages of Circuit PUBLISHER Cellar ever since the Reagan administration! Sean Donnelly We also have two special feature articles this month. On page 40, Dave Tweed Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] describes many of the technologies that have been covered in Circuit Cellar. On page ADVERTISING REPRESENTATIVE Shannon Barraclough 72, Ed Nisley tells us about some of his all-time favorite projects. Remember the soda Direct: 860.872.3064, E-mail: [email protected] bottle launcher project from Issue 2? We still get letters and e-mails about that one! ADVERTISING COORDINATOR As usual, we also have a healthy batch of theme-related articles to keep you busy. Valerie Luster The Robotics issue is always a crowd pleaser. This month we present a variety of proj- E-mail: [email protected] ects that won’t disappoint. On page 14, Michael Hall, Aaron Patten, and Erin Simpson describe how they Cover photography by Chris Rakoczy—Rakoczy Photography designed and built a complete control system for a robotic manipulator arm.They updat- www.rakoczyphoto.com ed an old arm and designed a new control system that’s capable of complex, repeat- PRINTED IN THE UNITED STATES able actions. The system consists of a main manipulator arm and a teaching arm used CONTACTS to control it. SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] Ever wonder how moviemakers get their monsters to look so real? In “Animatronic Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, System Control,” Barry Stout and Eugene Zeldin describe how to build a controller for Hanover, NH 03755-5650 Address Changes/Problems: E-mail: [email protected] an animatronics system (p. 24). The system controls a robotic monster’s head, eyes, GENERAL INFORMATION and mouth. Although the controller was originally designed for use on the set of a hor- 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] ror film, you can build a similar system for any number of applications. New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION Jeff Bingham and Lee Magnusson’s inertial rolling robot is definitely a novel design 860.875.2199, E-mail: [email protected] (p. 34). A DC electric motor is attached to a pendulum and suspended inside an inflated AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article. ball. They describe everything from the H8/3664-based circuitry to the process of cutting the rubber ball and patching it up again. WWW.GiURUMELE.Hi2.ROCIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar To round off this group of robotics-related articles, Dale Wheat describes how he Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- designed his Servo Tester I and Servo Tester II systems. The latter features a second scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in servo channel and an Auto Sweep function. You can build a similar system and tweak U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call the code to suit your needs. 800.269.6301. These projects will keep your gears turning well into April and May. Go animate! Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

Before I sign off, let me leave you with a little bit of encouragement: you’re the engi- Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- neers whose designs will change the way people live, work, and interact in the 21st 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®. century. Work hard, read (Circuit Cellar, of course), and keep us up to speed on your 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 progress! 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 © 2007 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 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 81.qxp 12/5/2006 1:31 PM Page 1

Keil DevelopmentTools Only 4 Steps... help you create embedded applications quickly ...are required to generate efficient, reliable and accurately. Keil tools are easy to learn and use, yet powerful enough for the most applications with the μVision IDE and demanding microcontroller projects. development tools from Keil.

Step 1. Select Microcontroller and SpecifyTarget Hardware Use the Keil Device Database (www.keil.com/dd ) to find the optimum microcontroller for your application. Inμ Vision, select the microcontroller to pre-configure tools and obtain CPU startup code.

Step 2. Configure the Device and Create Application Code The μVision Configuration Wizard helps you tailor startup code to match your target hardware and application requirements. Extensive program examples and project templates help you jump-start your designs.

Step 3. Verify Program Execution with Components of Keil Microcontroller Development Kits Device Simulation High-speed simulation enables testing before hardware is available and helps you Keil makes C compilers, macro assemblers, with features like instruction trace, code real-time kernels, debuggers, simulators, coverage, and logic analysis. evaluation boards, and emulators.

Over 1,200 MCU devices are supported for: Step 4.WWW.GiURUMELE.Hi2.RODownload to Flash and n 8-bit - 8051 and extended 8051 variants Test Application n 16-bit - C166, XC166, and ST10 Once your application is runs n 32-bit - ARM7, ARM9, and Cortex-M3 in simulation, use the Keil ULINK USB-JTAG Adapter for Flash programming and final Download an evaluation version from application testing. www.keil.com/demo

800-348-8051 www.keil.com 200_toc.qxp 2/2/2007 3:54 PM Page 6

March 2007: Robotics FEATURES

14 Robotic Arm Control System Michael Hall, Aaron Patten, & Erin Simpson

24 Animatronic System Control Barry Stout & Eugene Zeldin

34 Inertial Rolling Robot Jeff Bingham & Lee Magnusson Control a Robotic Arm (p. 14) Effective Animatronic System (p. 24) 44 Generic Modbus Simulator (Part 1) Theory and Preparation Rolling Robot Design (p. 34) Servo Tester (p. 59 ) Aubrey Kagan

59 Servo Control Dale Wheat

ISSUE 200 SPECIAL FEATURES 40 Then and Now Dave Tweed

72 A Plethora of Projects Ed Nisley Past & Present Technology (p. 40) Favorite Projects (p. 72) COLUMNS 52 APPLIED PCs 75 FROM THE BENCH Build a PIC Platform Embedded USB Breakthrough Fred Eady Jeff Bachiochi 67 LESSONS FROM THE TRENCHES 80 SILICON UPDATE More “Hello World” Code Like the Wind World Tour Moving What You’ve Learned to the Hardware Tom Cantrell George Martin DEPARTMENTSWWW.GiURUMELE.Hi2.RO

4 TASK MANAGER 94 INDEX OF ADVERTISERS Issue 200 April Preview C.J. Abate 96 PRIORITY INTERRUPT 8 NEW PRODUCT NEWS Inside the Box Still Counts edited by John Gorsky Steve Ciarcia 93 CROSSWORD

6 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 10/4/2006 1:48 PM Page 1

Dream of Darkness, Wasteman!

WWW.GiURUMELE.Hi2.RO

What can AVR picoPower • True 1.8V supply voltage enabling operation of all features and core down to 1.8V do for your design? • Minimized leakage current enabling 100 nA Power Down sleep consumption • Sleeping brown-out detector enabling full protection with no power penalty • Ultra low power 32 kHz crystal oscillator enabling operation at only 650 nA npn.qxp 2/2/2007 3:55 PM Page 8

NEW PRODUCT NEWS Edited by John Gorsky DUAL 36-V LOW-LOSS CONTROLLERS The LTC4416 and LTC4416-1 are robust dual “ideal input supplies that must be quickly turned off. This fea- diode” controllers for driving small and large gate capac- ture is useful when protecting the load from a large input itance P-channel MOSFETs in power-switchover circuits. transient or preventing loading of the power supply when The device’s control circuitry allows two power supplies it is deemed undesirable. The LTC4416 and LTC4416-1 are to operate in tandem, ensuring a highly efficient O-ring guaranteed to meet performance specifications over a wide of these power sources. The 25-mV forward voltage of range of operating conditions including an ambient tem- the LTC4416 and LTC4416-1’s controlled PFET is signifi- perature range of –40° to 125°C and a voltage range of 3.6 cantly lower than a Schottky diode, thereby extending to 36 V. battery life while reducing power loss and heat. Applica- The LTC4416 and LTC4416-1 feature ultra-low 70-µA qui- tions include systems that typically take power from escent current (35 µA per channel), independent of the load multiple input sources, such as high-current power path current. In addition, the ICs use a strong gate drive for fast switches, uninterruptible power supplies, battery backup gate turn-on and turn-off times of 60 and 30 µs, respectively. systems, emergency systems The devices also provide with battery backups, logic- reverse battery-discharge pro- controlled power switches, tection and MOSFET gate-pro- and automotive and industri- tection clamp circuitry. al systems. Pricing for the The LTC4416 is designed to LTC4416EMS/-1 and work with slow-moving input LTC4416IMS/-1 starts at $2.45 supplies and provide a “soft- and $2.95 each, respectively, off” feature to minimize droop for 1,000-piece quantities. when the supply voltages change. The LTC4416-1 is Linear Technology Corp. optimized for rapidly moving www.linear.com

CURRENT SENSORS FOR AUTOMOTIVE BATTERY-MONITOR- RJ-45 BREAKOUT BOX ING APPLICATIONS The RJ-45-BOB is an RJ-45 breakout box that The HAB is a new family of current sensors for battery monitor- brings out all the connections to test points ing in automotive systems and similar applications. The 12 sen- and binding posts for the now common RJ-45 sors in the family offer primary current measurement ranges from connector found on late-model, mobile, and ±20 to ±120 A, a high accuracy of ±2% across the operating tem- amateur radios, as well as Ethernet and serial perature range of –40° to 125°C, and a choice of voltage or PWM cables, T1 lines, and a host of other interface outputs. applications. The sensors are based on open-loop, Hall-effect transducers that Features of the RJ-45-BOB include gold-plat- simplify both installation and servicing by removing the need to ed test points, binding post connections, and cut the cable carrying the measured current. They operate from a solder points for connection to custom test unipolar 5-V supply and provide a fully ratiometric solution for the equipment. It also offers a label area for each voltage output devices. Response time is less than 10 ms. RJ-45 pin. One side of the board has two RJ-45s A watertight housing and sealed connector provide full environ- in a “loop-thru” configuration while the other mental protection in under-the-hood applications. Principal appli- side has an RJ-45 in a “dead-end” configura- cations are expected to be in the measurement of battery-pack cur- tion. rent in elec- The unit costs $34.95 and quantity discounts tric, hybrid, are available. and conven- tional vehi- McKay Products USA cles. WWW.GiURUMELE.Hi2.ROwww.mckayproducts.com One hun- dred-piece pricing for the HAB-S is $27.50. Pric- ing for the HAB-V is $33.90.

LEM USA www.lem.com

8 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com npn.qxp 2/2/2007 3:55 PM Page 9

NEW PRODUCT NEWS DUAL-SUPPLY BIDIRECTIONAL TRANSLATOR The FXL2TD245 is the first dual-supply bidirectional translator on the market that’s configurable for both unidirectional and independent bidirectional voltage translation between two logic levels. In addition to offering designers unparalleled design flexibility in a wide variety of low-voltage applications, this translator helps save board space. The FXL2TD245 measures only 0.55 × 1.6 × 2.1 mm, which is 80% smaller than comparable dual-supply translators in SOIC packages. It also replaces two 1-bit components used in typical designs. This ultra-com- pact translator is ideal for use in cell phones, PDAs, gaming devices, and NEW MCUs PROVIDE ENHANCED other portable applications, although its wide voltage range (1.1 to 3.6 V) MEMORY AND PIN COUNTS accommodates the voltage requirements of a variety of consumer and NEC has added 16 new devices to its industrial applications. comprehensive lineup of 16- and 32-bit all In addition to performance and space improvements, the FXL2TD245 flash memory . These lat- bolsters system reliability. For instance, its 10-terminal MicroPak offers est microcontrollers offer up to twice the 35% more pad contact area than other leadless packages, which results memory and a significant increase in pin- in a stronger solder count options compared to previous devices bond between the in the line. Based on advanced 0.15-micron device and the circuit processes using SuperFlash, the new lineup board. The includes two 32-bit V850ES/JJ3 microcon- FXL2TD245 facili- trollers with up to 1 MB of flash memory, tates more robust and 14 new 16-bit 78K0R/Kx3 microcon- designs by providing trollers with up to 512 KB of memory and outputs that switch 144-pin packages. These devices are well to tristate if either suited for industrial and office applications supply voltage is such as, security systems, utility meters, equal to ground. It scanners, and printers. They are also well also offers built-in suited for consumer applications such as, power-off protection. digital televisions, projection televisions, The FXL2TD245 is and DVD receivers. priced at $0.85 each The new devices currently cost $13.50 in 1,000-piece quanti- for the V850ES/JJ3 microcontrollers and ties. $9 for the 78K0R/Kx3 microcontrollers in sample quantities. Fairchild Semiconductor Corp. NEC Electronics America, Inc. www.fairchildsemi.com www.am.necel.com

18-BIT DELTA-SIGMA ANALOG-TO-DIGITAL CONVERTER The MCP3421 is the highest resolution ADC available in a SOT-23 package ly, with the device’s onboard PGA, today. The low-power, 18-bit, Delta-Sigma ADC features an integrated voltage users can select the gains of ×1, ×2, reference and PGA on-chip, which reduces the need for external components ×4, or ×8 before the analog-to-digital and enables a smaller overall design footprint. With its 6-pin package, low- conversion takes place, enabling very power consumption, and high res- high-resolution conversion of even olution, the new ADC is ideal for small input signals. The integrated portable-measurement applica- voltage reference and oscillator lessen WWW.GiURUMELE.Hi2.ROtions in the industrial, medical, the need for external components, consumer, and automotive mar- resulting in simpler designs and a kets. smaller overall design footprint. The MCP3421 ADC uses an For designers wanting to evaluate I2C-compatible serial interface and the MCP3421 ADC in their applica- operates from a single power sup- tions, the MCP3421 evaluation board ply (2.7 to 5.5 V). The low-power (part number MCP3421EV) is avail- technology enables the device’s able for $15. The device is available in extremely low-power consump- a 6-pin, SOT-23 package for $1.71 tion of just 155 µA at 5 V of con- each in 10,000-unit quantities. tinuous conversion, which helps to extend battery life in portable Microchip Technology, Inc. measurement devices. Additional- www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 9 5.qxp 1/4/2007 11:35 AM Page 1

Low-Cost Embedded USB Silicon Laboratories’ extensive portfolio of USB MCUs and USB to UART Bridges include complete, low-cost development tools and drivers to make system design quick and easy. Software examples for real life systems are also available and include a mass storage device, USB audio and human interface device. The USB MCUs feature an on-board USB 2.0 function controller with an integrated transceiver that requires no external oscillator. On-chip resources include a high-speed 8051 CPU (up to 48 MIPS) with up to 64 kB Flash, multi-channel 10-bit ADC, voltage reference, internal oscillator, UARTs, SMBus, SPI, timers, counters and PWM generators.

USB to UART Bridge WWW.GiURUMELE.Hi2.RO• Single Chip (5x5 mm) • USB 2.0 Controller • UART Interface • Update RS-232 Designs

Product details: www.silabs.com/USB

MCUs TIMING POWER BROADCAST WIRELINE WIRELESS www.silabs.com npn.qxp 2/2/2007 3:55 PM Page 11

+++ NO ROYALTIES +++

NEW PRODUCT NEWS embeddedsoftware PROTOCOL TRANSLATION CARDS solutions The ProtoCarrier is a series of daugh- ProtoCarrier now enables manufac- ter cards that enable OEMs to quickly turers to add the power of ProtoCessor Eval versions and easily interface with legacy devices to its device without the need of available to modern open-protocol networks extensive board redesign. The Proto- without extensive board redesign. Pro- Carrier has either an RS-232 or RS-485 embOS ® toCessors are a family of industrial pro- (RTOS) port on the host side (OEM’s product) +++ 8/16/32 bits +++ tocol coprocessors that provide compre- and a ProtoCessor TTL socket on the Preemptive multitasking hensive protocol translation capabili- board that can accept any ProtoCessor Zero interrupt latency ties. With access to the extensive Field- chosen to meet their user’s specific Easy to use start project included Server Technologies driver library, Pro- need. FieldServer Technologies can Profiling support included toCessor can be embedded on a device preprogram the ProtoCessor to provide Object/source code available to enable the manufacturer to meet the complete industrial or building- interoperability needs of its customer. automation interoperability. The protocols available include Allen The ProtoCarrier with a ProtoCes- Bradley Ethernet/IP, BACnet IP, BAC- sor installed costs approximately $225 net MSTP, Modbus RTU, Modbus TCP, in volume. Metasys N2, DNP3, LonWorks, and a wide variety of legacy and proprietary FieldServer Technologies protocols. www.protocessor.com

® emWin (GUI) +++ 8/16/32 bits +++ ANSI "C" source code, no C++ required Supports b/w, grayscale and color 2D graphic library included Variety of fonts included PC simulation included Window Manager/Widgets (opt)

WEATHERIZED CONNECTOR emFile The new CONREVSMA015 reverse-polarity SMA connector is ideal for appli- (File system) +++ 8/16/32 bits +++ cations requiring an external water-resistant connection. The connector fea- ANSI "C" source code tures an integral rubber O-ring that compresses against the outside of the enclo- MS-DOS/MS-Windows compatible sure to prevent water or dust intrusion into the product’s housing. Its extra-long FAT12, FAT16 and FAT32 support ″ 0.47 tail is long enough to be used with the thickest outdoor-rated enclosures. Multiple media support Available standard for RG-174 coaxial cable, other cable types are available Non FAT file system available through special order. The CONREVSMA015 costs $3.04 in quantities of 1,000.

Connector City WWW.GiURUMELE.Hi2.ROwww.connectorcity.com

For ARM Chips: JTAG debug solution with flash programming

phone: 978-874-0299 www.segger.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 11 npn.qxp 2/2/2007 3:55 PM Page 12

Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. 2.4-GHZ TRANSCEIVERS RUN APPLICATION CODE A new feature permitting XE24S transceivers to run system calls, and User Code examples of common sys- remote monitoring applications on the transceiver’s com- tem functions. munications controller is now available. This feature The User Code feature targets applications that use the called “User Code” eliminates the need for a microcon- six I/O lines on the XE24S transceivers. These applica- troller at the remote node, reducing system cost and tions include remote monitoring applications, such as complexity. irrigation controls or fluid tank monitoring, plus auto- The XE24S transceivers use the Texas Instruments mated meter reading (AMR), security systems, and med- MSP430 F148 to control communications functions; ical diagnostics. however, these responsibili- The User Code develop- ties do not use this micro- er’s tools will be included controller’s full capabilities. at no extra charge in each User Code permits the user XE24S development kit. to tap into the controller’s Development kits are unused capabilities to run available for all variations his remote monitoring of the XE24S. Each devel- application. Note that 8 KB opment kit costs $295 and of flash memory space is includes the development reserved to store user-gener- tools, two transceivers, ated code. A User Code two serial development developer’s CD provides the boards, plus the required tools to use the MSP430 antennas and cables. The F148 controller without User Code Developer’s CD interfering with its commu- is offered separately for nications responsibilities. $49. The User Code Developer’s CD includes development Xecom, Inc. tools, a listing of available www.xecom.com

TWO- TO FOUR-CHANNEL CCFL CONTROLLERS The DS3992 and DS3994 are two- to four-channel con- reference voltage to determine the duty cycle for the trollers for cold cathode fluorescent lamps (CCFLs) that MOSFET gates. are used to backlight LCDs. The DS3992 supports a one- Each CCFL receives independent control, which lamp-per-channel configuration with fully independent results in equal brightness across all of the lamps and lamp control, while the DS3994 supports configurations maximizes lamp life and brightness. of one to four channels and allows multiple DS3994 con- Both devices operate from 4.5 to 5.5 V. Pricing starts at trollers to be cascaded. $0.60 for the DS3992 and $0.85 for the DS3994 in 1,000- The DS3992/DS3994 use a push-pull drive scheme to piece quantities. convert a DC voltage (5 to 24 V) to the high-voltage (600

to 1,200 VRMS and 300 to 1,400 VRMS, respectively) AC Maxim Integrated Products waveform that is required to power CCFLs. The push- www.maxim-ic.com pull drive scheme uses a minimal number of external components, which reduces component and assembly costs and makes the PCB design easy to implement. The push-pull drive scheme also provides an efficient DC-to- AC conversion and produces near sinusoidal waveforms. Each DS3992 and DS3994 channel drives two logic- level N-channelWWW.GiURUMELE.Hi2.RO MOSFETs that are tied between the ends of a step-up transformer and ground. The transformer has a center tap on the primary side that is connected to the DC supply. The DS3992/DS3994 alternately turn on the two MOSFETs to create the high-voltage AC waveform on the secondary side. By varying the duration of the MOSFET turn-on times, the controllers accurately con- trol the amount of current flowing through the CCFL. A series resistor on the low-voltage side of the CCFL enables current monitoring. The voltage developed across this resistor is fed to the lamp-current monitor input on each device. Then, the DS3992/DS3994 com- pare the resistor voltage against an internal

12 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 13.qxp 1/31/2007 9:01 AM Page 1

WWW.GiURUMELE.Hi2.RO 2703014Hall.qxp 2/2/2007 4:03 PM Page 14

FEATURE ARTICLE by Michael Hall, Aaron Patten, & Erin Simpson Robotic Arm Control System

Need a hand? In just 11 weeks, this team of designers turned a dysfunctional 20-year-old robot arm into a system capable of complex actions. Now you can build your own.

Have you ever wished you had a wanted to be able to record the main wrist-rotate, and tool-rotate joints third arm? We did, and now our dreams arm’s motions on a PC. Our primary have smaller motors, while the waist, have been realized. It is our hope that concern was real-time control. We shoulder, and elbow joints have larger you can learn from our experiences so wanted to implement a PC interface, motors. Due to the age arm’s age, we you too can gain a helping hand. With a using either CAN or serial communica- were unable to find any specifications Mircochip Technology dsPIC30F6015 tion, and then write a program to record for the motors. The first thing that we microcontroller, a few mechanical com- and play back the arm’s movements. needed to do was determine the power ponents, some DC motors, and a little Did we mention that we had only requirements for both motor types. To ingenuity, your very own third arm 11 weeks to complete this project? do this, we detached one of each motor will be pouring your drinks in no time. Armed with what little information from the arm and hooked them up to a we had, we got to work. DC-bench supply. Starting from zero, SYSTEM OVERVIEW we slowly raised the voltage and Our final project for Camosun Col- INITIAL FINDINGS observed the motors’ responses. lege’s Electronics and Computer Engi- The main arm has two types of Once we were satisfied with the no- neering Technology program was to brushless DC motors. The wrist-flex, load characteristics of the motors, we implement a complete control system for a robotic manipulator arm. Our goal was to update the electronics and design a new control system that would be capable of complex, repeatable actions. The system consists of the main manipulator arm and the teaching arm used to control it. Both arms are capa- ble of seven degrees of motion. We aren’t sure what the main arm was originally designed for, but it may have been a demonstration or proto- type model. We decided that each arm would have its own control system and would communicate serially. Photo 1 shows both arms and the completed control system. The main armWWW.GiURUMELE.Hi2.RO had been part of anoth- er group’s project back in 1986. Although a few scattered pieces of its control system were still around, the main arm hadn’t functioned in many years. We searched the Internet, but did- n’t have much luck finding information about either of the arms. All we could find out was that a now-defunct com- pany called RSI had built it. We wanted to be able to control the arm in real Photo 1—The finished system includes (from left to right) the teaching arm, controller boards, and the main arm. time with the teaching arm. We also Both arms are capable of seven degrees of motion.

14 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703014Hall.qxp 2/2/2007 4:03 PM Page 15

reattached them to entire system. This the arm and repeated was accomplished by the experiment. performing a continu- Because of the arm’s ity test between all of potential to cause dam- the points on both age or serious injury, arms. Once we knew we had to be very care- which pins on the ful. We made sure that motors corresponded the arm was clear of to which pins on the other objects and that connectors, we labeled no one was in its vicin- them. Looking back, it ity during operation. would have been a Through trial and error, good idea to redo all we found that the larg- the wiring when we er motors ran best at started because we about 12 V and drew experienced several approximately 500 to wiring failures. 600 mA during nor- mal operation. The CONTROL SYSTEM smaller motors ran Figure 1—A PIC18F2585 attached via headers P1 and P2 reads the values from the position sen- We looked at several best at 24 V and drew sors on the teaching arm. It then transmits the values serially to the main arm. microcontrollers before 150 to 200 mA. our search led us to Next, we had to determine the lay- Because nothing was color-coded or Microchip Technology’s 16-bit DSC out of the original wiring harness. documented, we had to map out the motor control family. We ended up

WWW.GiURUMELE.Hi2.RO

Figure 2—Take a look at the L298 motor driver. This circuit was used to control the four smaller motors. The PWM signal is applied to the ENABLE pins, and the direction is controlled using the two INPUT pins. This freed up PWM pins on the dsPIC30F6015.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 15 2703014Hall.qxp 2/2/2007 4:03 PM Page 16

Figure 3—Check out the VNH3SP30 motor driver. This circuit drives the three larger motors. For motor 1, applying a PWM signal to the M1_PWM input controls the speed. The M1_ INA, M1_INB, M1_ENA, and M1_ENB lines are used for direction and enabling the motor.

choosing the dsPIC30F6015, which is a final design. best at 12 V. The wrist-flex, wrist- 64-pin TQFP device. Its onboard PWM For initial testing purposes, we rotate, and tool-rotate motors have modules, ample program memory, and decided that the board should be able smaller motors that run best at 24 V. RAM were immediately attractive. It to fit on a standard breadboard using We decided on a pair of STMicro- has 16 channels of 10-bit A/D conver- headers. We figured we could then use electronics L298 dual full bridge driv- sion, which was more than adequate the same headers to interface the con- ers for the four smaller motors, but for reading the position sensors on the troller board to the motor driver board the three larger motors posed more of arm. The dsPIC30F6015 also has (see Figures 1, 2, and 3). a challenge. The stall current on these onboard support for all of our commu- We implemented the appropriate motors could approach 4 or 5 A, nication requirements. We were famil- circuitry to enable in-circuit program- which is more than the L298 is capa- iar with some of Microchip’s other ming, a MAX232 level converter for ble of. Although we intended to imple- processors, so we felt it was a solid serial communications, and a ment over-current protection, we choice. Microchip MCP2551 CAN driver. An wanted to be safe, so we began search- In order to designWWW.GiURUMELE.Hi2.RO our control sys- eight-pin header for a 4 × 4 matrix ing for another solution. tem, we needed a development board keypad and a 14-pin header for a stan- The SGS Thomson Microelectronics for the dsPIC. (Refer to the diagram dard LCD completed our com- VNH3SP30 H-Bridge motor driver on the Circuit Cellar FTP site.) The munication requirements. Other addi- proved to be a good choice. Designed for budget for the project did not allow tions included regulator and oscillator automotive applications, such as power for a commercial solution, so we had circuits. Photo 2 shows the completed windows and seats, they can handle a to develop our own. Our require- development board connected to the massive 30 A of output current and a ments included in-circuit program- motor driver board. maximum operating voltage of 40 V. ming capabilities, RS-232 and CAN The arm has two types of brushless For the position feedback poten- communication, and headers for an DC motors. We did some tests and tiometers on both arms, we chose the LCD and matrix keypad. We also found that the larger motors on the Bourns 6539S series. Although these wanted to incorporate the board in our waist, shoulder, and elbow joints run servo-mount potentiometers are not

16 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 39.qxp 1/3/2007 9:40 AM Page 1

2,600 NEW 2,500 NEW BOURNS 5,000 NEW MAXIM PARTS AMP PARTS PARTS Wow! Jameco just added 65,000 new major-brand products!

19,000 NEW 2,000 NEW 2,800 NEW TEXAS MICROCHIP MOLEX 2,900 NEW INSTRUMENTS PARTS PARTS VISHAY PARTS PARTS The industry’s fastest Check out these new growing product offering! 6,200 NEW 3,000 NEW and expanded lines: You know that Jameco’s catalog Aavid Thermalloy • always offers over 99% in-stock FAIRCHILD AVX AlcoSwitch • AMP • availability—the best of any elec- PARTS Amphenol Connex • tronic components distributor... PARTS Aromat • Atmel • And now, they have the Augat • Avago • AVX • fastest growing product offering Bourns • Buchanan • C&KSwitches • Comair Rotron • Condor Power in the industry! Supplies • CTS • Cypress • Dallas They’ve just added another Semiconductor • Elco • Fairchild • 65,000 new parts to their online Grayhill • Intel • Intersil • catalog; and it’s everything Keystone • Lumex • Lumileds • from ICs to passives, optos to Maxim • Microchip • Micron interconnects, power supplies Technology • Molex • to electromechanical. NXP/Philips • Panasonic • Power-One • Raychem • Service & Availability! Renesas Technology • As Design Engineers Sandisk • Siliconix • ST know, Jameco offers great Micro • Texas Instruments • service, selection andWWW.GiURUMELE.Hi2.ROToshiba • Tyco Electronics • same-day shipping! Vishay Intertechnology • Now you can get those Wakefield... same benefits for even Get it here. Right now: more great brands... Jameco.com/CCV

G r e a t P r o d u c t s . Awesome Prices. 2703014Hall.qxp 2/2/2007 4:03 PM Page 18

cheap, they provide stable and which data is collected, precise information about the processed, and transmitted by position of the arm. The the UART. manipulator arm already had limit switches installed to pre- MANIPULATOR ARM vent it from going out of range Once the teaching arm mod- or being damaged. ule was finished, we began When we were first present- writing code for the ed the idea of writing firmware dsPIC30F6015 on the main to control a robotic arm, we processor board. We used the honestly thought it would be a C30 compiler’s built-in libraries breeze. Three years of coding to control four of the seven embedded systems barely pre- PWM outputs, the ADCs, and pared us for the task, but we serial communications. hope that our experiences can Photo 2—Check out the completed controller boards. The core of our sys- The manipulator arm is also help you with your own tem is a dsPIC30F6015 driving L298N full-bridge drivers and VNH3SP30 H- equipped with six potentiome- mechatronics project. Bridge motor drivers. Serial and CAN communications, in-circuit program- ters. We chose to begin by set- ming, and current-protection circuits are also included. ting up the manipulator arm’s TEACHING ARM ADCs so that we could see the The teaching arm is fitted with six calculated at discrete time intervals. voltage feedback from each joint as we potentiometers. Each potentiometer is The final piece of the puzzle is a timer moved them manually. The mounted to a joint on the teaching interrupt that regulates the rate at dsPIC30F6015’s ADCs were more than arm, which represents a joint on the manipulator arm. The single-turn servo-mount potentiometers are Listing 1—The averaging filter is used to smooth the changing voltages of the potentiometers on the teaching arm. mounted so that the position of the wiper arm is dependent on the angle void Update_Average_Filter(void) { of its respective joint. Using the built-in libraries of the static int previous_result[CHANNEL_WIDTH];//An array containing the Microchip C18 compiler with the //last recorded set of positions ADCs of a PIC18F2585 microcon- int results[AVG_BUF_MAX][CHANNEL_WIDTH],//A two-dimensional array troller, we wrote code to record and //containing the last recorded set of positions, the width of transmit the voltages of the teaching //which is decided by "AVG_BUF_MAX" arm potentiometers to the manipula- result_difference[CHANNEL_WIDTH];//An array containing the tor arm via a serial link. We used a //differences between the previous elements of "results_averaged" running average filter to smooth the //and the current elements of "results averaged" voltages read from the potentiome- results_averaged[CHANNEL_WIDTH];//An array containing the averaged ters before transmitting them (see //results from all active analog-to-digital channels Listing 1). int temp1 = 0, temp2 = 0; //indexing variables Every time the ADCs are read, the for(temp1 = 0; temp1 < CHANNEL_WIDTH; temp1++)//for all channels index of a circular buffer is increment- { ed. This buffer is then used to calcu- previous_result[temp1] = results_averaged[temp1]; late the average voltage. It is a simple //save the last recorded averaged result for this channel task to derive the speed of any motion results_averaged[temp1] = 0; //clear the channel on the teaching arm. We did this by for(temp2 = 0; temp2 < AVG_BUF_MAX; temp2++) comparing the results of each A/D //for all values to be averaged conversion with the previous results { WWW.GiURUMELE.Hi2.ROresults_averaged[temp1] += results[temp2][temp1]; to produce a vector. //Sum the values We chose to implement this feature } in the same function as the averaging results_averaged[temp1] = results_averaged[temp1]/AVG_BUF_MAX; filter by simply subtracting the previ- //divide the sum by the buffer width ous set of positions from the most result_difference[temp1] = results_averaged[temp1] - recent set of positions. The resulting previous_result[temp1]; //save the difference between the current difference is proportional to the speed, //average and the last recorded average and its sign represents the direction of } the motion. In order for this difference } to represent a true vector, each set of //------position changes must be recorded and

18 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 19.qxp 1/31/2007 9:40 AM Page 1

WWW.GiURUMELE.Hi2.RO 2703014Hall.qxp 2/2/2007 4:03 PM Page 20

adequate for this project because they Listing 2—This function compares the argument Duty Cycle with the global variable Timer Period are intended for DSP and can handle to determine what value to write to the special function register PR1. This value determines when the timer up to 1 million A/D conversions per interrupt will occur. second. Using the built-in libraries, we configured the A/D module so six con- void SetPWM2(int Duty_Cycle) versions would take place each time { if(Duty_Cycle == 0) the Convert command was issued. { To use the ADC in this configura- LATEbits.LATE1 = 0; tion, we periodically called a function PR1 = 0; that would update a new set of posi- Timer1_Duty = 0; tions to the ADC buffer. Wherever the } most recent set of positions were else needed in code, it could simply be { read from the buffer using the if(Duty_Cycle > Timer_Period / 2){Duty_Cycle = Timer_Period / 2;} ReadADC10 function. We used the //If the desired duty cycle is greater than the maximum make it LCD to display the voltages of the the maximum potentiometers as we moved them so if(PR1 == 0){PR1 = Duty_Cycle * 2;} //If this channel of PWM is currently disabled: Enable it the potentiometers could be calibrat- Timer1_Duty = Duty_Cycle * 2; ed. This is done by temporarily //Load the PWM timer with the duty cycle removing the potentiometer so the } wiper arm can be moved independent- } ly from the joint, and then reattaching it once the desired voltage is aligned with the appropriate angle of the joint. the motor. Each time the PWM output controlled at the same time, the con- Each wiper arm was positioned so the is set, the direction pins are also set. trolling functions must poll the state voltage would be 2.5 V at the center of Since the dsPIC has only four built- of the joint and immediately update its range of motion. The same steps in PWM timers, we used timer inter- the PWM output, based on both the were used on the teaching arm so that rupts to produce the last three PWM current and desired states of the joint. any given voltage on the teaching arm signals needed (see Listings 2 and 3). The desired state of the joint is arbi- would be easily translated to a posi- The timer-interrupt and duty-cycle trated by the teaching arm. The cur- tion on the manipulator arm. update function are shown in Listing 3. rent state of the joint must be calcu- To use the built-in PWM timers of Note that it is important to temporari- lated based on the position feedback the dsPIC, we modified the sample ly disable any interrupts when doing provided by the potentiometer. The code (setDCMPWM) included with the an A/D conversion. speed of the motor can be set based on C30 libraries. Using this configuration, Since all seven joints have to be the vector generated by the teaching the process of setting a PWM output was reduced to a function call. Each time the function is called, the appro- Listing 3—This interrupt will occur at both the rising and falling edge of the PWM output. The next state of the priate PWM output pin, as specified by PWM output pin is determined based on the current state of that same pin. The duty cycle will be updated only the arguments of the function, emits a during the positive going transition of the PWM output. 20-kHz PWM signal with a duty cycle void __attribute__((__interrupt__)) _T1Interrupt(void) that is defined by the second argument. { The third argument determines IFS0bits.T1IF = 0; //Clear Timer1 interrupt flag whether or not the PWM output signal if(PORTEbits.RE1 == 0) //If the output is low can be modified once set. Since it must { be constantly updated, the third argu- Timer1_Previous_Duty = Timer1_Duty;//Update the off-time of the cycle ment is always zerWWW.GiURUMELE.Hi2.ROo. LATEbits.LATE1 = 1; //Set the output high and In order to control the direction of PR1 = Timer1_Duty; //Load the Timer with the On-Time of the the motors, two other output pins are //selected PWM Duty Cycle necessary. We used the differential } pair of each motor driver to specify else//PWMread5 = 1 //IF the output is high { direction. The PWM signal is then LATEbits.LATE1 = 0; //Set the output high and applied to the enable input of the PR1 = (Timer_Period - Timer1_Previous_Duty); //Load the timer motor driver. The direction of each //with the off-time of the selected PWM duty cycle motor is set by clearing or setting the } pins connected to the differential pair. TMR1 = 0; //Start the count from 0. Setting both direction pins to the } same state stops energizing the coils of

20 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 21.qxp 1/30/2007 3:16 PM Page 1

WWW.GiURUMELE.Hi2.RO 2703014Hall.qxp 2/2/2007 4:03 PM Page 22

Listing 4—This function compresses the range of a 10-bit number into the upper half of its range. arm or by the angular distance the joint has to move in order to get to the Int compressed10(int value) desired location. Refer to the Joint- { Control.doc file posted on the Circuit int compressed = value; //Store the original value Cellar FTP site for an example of a value = (1023 - value); //The 10-bit negative of value joint control function that determines compressed += (value >> 1);//Divide the new value by 2 and add speed based on the distance the joint //it to the original input has to travel. return(compressed); //the result is a number that begins at 511 Once this function was tested and //and increases at half the rate of the input until 1023 working, we modified it for the other } joints. On the line labeled //Set Motor Speed, the duty cycle is set based on the variable current_vector. In this example, it is set to the distance of the joint on the manipulator arm from its respective joint on the teaching arm. The magnitude function ensures that the value is a positive number. The compressed function, shown in Listing 4, is in place to ensure that the magnitude of the current vector is within the range that will move the motor. If the current vector is too small, the duty cycle will not be high enough to overcome the friction of the motor. The compression function adds half the inverse of its argument to its return value, so that any 10-bit value ranging from 0 to 1,023 will range from 511 to 1,023. Adding 25 to this ensures that all values will be able to move the motor in spite of its specific friction coefficient.

POTENTIAL IMPROVEMENTS With the deadline looming, we were making significant progress. Joint by joint, we were taking control! The Elec- tronics and Computer Engineering Tech- nology program at Camosun College had prepared us well. The arm followed the motion of the teaching arm, and it seemed to take on a life of its own! We overcame many challenges, but unfortunately, the system was not per- fect. We encountered several obsta- WWW.GiURUMELE.Hi2.ROcles, the first of which was the physi- cal condition of the arms. There were problems with the original wiring of both arms, so we spent a significant amount of time trying to solve them. Then there were mechanical issues to deal with. More than one joint suf- fered from looseness, which was sure- ly a sign of the arm’s age. There was also the problem of getting reliable data from the position sensors. Because the potentiometers relied on a

22 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703014Hall.qxp 2/2/2007 4:03 PM Page 23

friction fit, we found that they tended RESOURCES SOURCES to drift over time. It was very difficult Microchip Technology, Inc., to maintain accuracy when the data 6539S Precision servo-mount poten- “dsPIC30F6010A/6015 Data Sheet,” received from the pots varied. tiometer DS70150A, 2005,ww1.microchip.com/ Bourns, Inc. Looking back, we would recom- downloads/en/DeviceDoc/70150A.pdf. mend implementing a high-resolution www.bourns.com ———, “16-Bit Language Tools rotary encoder for the position sen- PIC18F2585 Microcontroller Libraries,” DS51456C, 2005, ww1.micro sors. You could also improve the Microchip Technology, Inc. chip.com/downloads/en/DeviceDoc/16bit design by devising a means to securely _Language_Tool_Libraries_51456c.pdf. www.microchip.com attach the shaft of the position sensor to the mechanical portion of the arm. ———, “dsPIC30F Family Reference L298 Motor driver and VNH3SP30 The tight time constraints for the proj- Manual,” DS70046E, 2006, motor driver ect did not allow us to implement all ww1.microchip.com/downloads/en/ STMicroelectronics of the features that we had planned. DeviceDoc/70046E.pdf. www.st.com We had hoped to record and play back the movements of the arm, but we were unable to implement the PC interface.

ARM CONTROL The 11 weeks flew by. After a lot of hard work, frustration, and late nights, we had a system that worked. We knew that this project would be chal- lenging, and we new that we would be testing everything that we had learned, but nothing beats hands-on experience. Although there is still room for improvement, we are pleased with the results. We learned a lot, and hopefully this article will help you with your own robotics project. I

Mike Hall ([email protected]) earned a diploma in Computer Engi- neering Technology at Camosun Col- lege. He works as a sound technician and hopes to find employment with an audio equipment manufacturer.

Aaron Patten ([email protected]) graduated from Camosun College with a diploma in Computer Engineering Technology and is currently working toward a degree in Computer Engineer- ing at the University of Victoria. Erin Simpson ([email protected] com) holds a diploma in Electronics Engineering Technology from Camosun College. She is a devoted kick boxer and is pursuing her electronics career with the Canadian Armed Forces.

PROJECT FILES To download code, go to ftp://ftp. circuitcellar.com/pub/Circuit_Cellar /2007/200.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 23 2703017stout.qxp 2/5/2007 4:43 PM Page 24

FEATURE ARTICLE by Barry Stout & Eugene Zeldin Animatronic System Control Barry and Eugene used their knowledge of robotics and a lot of creativity to design an H8/3687- based control system for a robotic monster that appeared in a horror movie.The system enabled them to control the monster with potentiometers, a touch screen, and buttons.

In 2003, Stephen Zimmer of Shad- out because he has been in the industry ished because the movie’s budget and ows Light Productions contacted me for 10 years. Most of my experience has timetable forced us to pass on several of (Barry Stout) about being part of a huge been with mechanical/electrical integra- the effects that we had hoped to use. For effort to make a horror movie on a tion and controller-algorithm design, so instance, we had originally planned to shoestring budget. He said the film our skills complement each other well. use flaming swords that ran on butane would require hundreds of special- In this article, we’ll describe the gas, but the budget forced us to use a effects shots and that he needed some Renesas Technology H8/3687-based computer-generated effect instead. assistance with the development of system that we developed to control But not all was lost. For the movie’s props. At that point in my career, I had an animatronics mask for the movie climactic scene, a 12′ monster attacks been designing motion control systems (see Photo 1). The system features an the leading actor. To make this scene for robots, printers, and RC cars for auxiliary circuit board, a power sup- work, the actor inside the monster several years. Because my other passion ply, and some servos. As you can see had to walk on stilts, while a fully is film, I bit at the opportunity. Fortu- in Figure 1, its potentiometers, touch animated head was mounted on top. nately, Stephen had already assembled screen, and push buttons enable us to To create this effect, we developed a a team of designers who were experi- control the mask. (Additional dia- body cast that eventually became a enced in makeup, prosthetics, mold grams are posted on the Circuit Cellar large Fiberglass mold. Between the egg making, and prop mechanics. FTP site.) This design rivals the ani- smell of the foam latex and the toxic I was interested in contributing as matronics controllers found on the odor of the Fiberglass, the makeshift much as possible to the project, so I sets of many big-budget feature films. special-effects studio was never the brought my business partner and long- same again. We are just grateful that time friend Eugene Zeldin into the mix. BUILDING A MONSTER we retained enough brain cells to Eugene has a lot of experience with During the first few months of the write this article. microcontroller coding and circuit lay- project, many of the crew’s dreams van- While the mask effects team was

a) b)

WWW.GiURUMELE.Hi2.RO

Photo 1a—This is an early prototype of the main controller board. The monster consists of an unpainted foam mask glued over a molded Fiberglass frame with servos attached to hinges and slides in the face. b—This is a prototype of the touchscreen’s conversion electronics mounted on the evaluation board’s LCD. The final design covers the light emitters and receivers, while shielding the crosstalk between the LEDs.

24 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703017stout.qxp 2/5/2007 4:43 PM Page 25

′ building a 15 oven to cook the User interface platform (HEW 2.2), which full body suit, we rushed to com- Mask included the compiler to program

plete the monster’s animatronics Microcontroller the microcontroller. In addition, controller (see Photo 1b). To fully we gathered up all the loose com- 1 2 3 4

animate the mask, the eyes, ponents such as breadboards, oscil- mouth, eyebrows, cheeks, and Touch loscopes, computers, ohm meters, screen nose had to be mechanically actu- Driver and a couple of power supplies. board ated. (Refer to the Animatronics After a quick blessing of the sidebar.) equipment, we were ready to go. Figure 1—The user interface sends commands to the microcon- Like all good engineers, we laid troller, which in turn sends signals wirelessly to the motor driver We had to burn the midnight out the necessary degrees of free- board that controls the servos. oil for a few days, but it wasn’t dom for each joint and formulated long before pieces of hardware the required electronics. Besides the transmitter out of your hands). and software were starting to come system’s cost, there were several other We decided to create a driver board together. We had a rudimentary PWM challenges to address: the monster had that would control the movement of the motor controller implemented in to be lightweight, battery-powered, array of actuators and an external con- record time. wireless, easy-to-use, and highly trol box that would act as a user inter- adaptable. Other fun features such as a face to the driver board. As a bonus, we CIRCUIT CARD low-cost touch panel, kinetic-metric wanted the driver board to have a built- After hours of fine-tuning the hard- inputs, and module coding were added in interface for host PC communication ware and software on those dreaded to the plan, but they were not our pri- or preprogrammed scripts. breadboards, we were ready to build a mary focus. In the beginning, we had to decide pilot board. Equipped with P-CAD, we For animatronics novices, kinetic- what we wanted to build. Being the finalized the schematics and created a metric inputs means that a person’s workhorse of the project, the motor net list for the layout. In order to cre- movements can directly control the controller became our highest priority. ate that actual circuit layout, we robot’s movements. In such a system, We then had to consider the user placed the components in their appro- a sensor that monitors the arm move- interface, options and features, power priate locations on the circuit board, ment of a puppeteer will send a signal requirements, the microprocessor, and routed a couple of the main power to the main processing unit. From software. traces and control signals, and then let there, the controller moves the robot’s Once everything was laid out, we the auto router go wild and crazy. arm in the same fashion. This is simi- were ready to start the architecture After a couple of attempts, we were lar to the way older movies were made and make high-level design decisions. satisfied with the auto router’s output. (e.g., Star Wars). The puppeteer would During this time, we chose the motors How could a computer program be attach cables to a monster’s joint and and controller circuitry, and we wrong? At this point, we cleaned up a then pull them. With modern-day ani- sketched the basic design on a napkin few of the routes and finalized the cir- matronics systems, all of the control during a healthy lunch consisting of a cuit board. is wireless. Controlling a robot is now lot of fried chicken. The next step was to generate all like controlling an RC car (but with- For this project, we used a Renesas the masks, copper pours, silkscreen, out your brother trying to pull the H8/3687 kit and a C development and various layers to bundle it in the

Animatronics Most moviegoers love special effects. This is also one project was to quickly build an affordable controller that of the reasons why American movie making has dominat- could remotely operate an animatronic mask. ed the world with high-budget effects that the independent Even though the history of animatronics started with a filmmaker cannot afford. preprogrammed mechanism, modern animatronics for In 1963, WaltWWW.GiURUMELE.Hi2.RO Disney spent hundred of thousands of movies resembles puppeteering, where the actions of a dollars to make controllers for his Tiki Bird and Abra- person are replicated in the monster. There are several ham Lincoln exhibit, which consisted of analog tape reasons for this approach, one of which is that pro- machines reading silver traces to activate pneumatic grammed actions may not provide the flexibility to make actuators. This marked the beginning of the field of ani- last-minute changes that the movie director might need matronics. to make. In addition, when an actor can mentally con- Much has changed about the way in which people make nect with the creature that will appear on screen, it movies, but one thing remains the same: high-quality spe- makes for a more believable performance. In comparison cial effects usually require a big budget. Fortunately, with to older methods of special effects, our controller needed the advent of microcontrollers, the cost of mechanisms to to be able to relay information from the user to the crea- control props has drastically decreased. The purpose of this ture electronically instead of with strings.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 25 2703017stout.qxp 2/5/2007 4:43 PM Page 26

proper format and send it off to a takes to make at least 10 custom cables meter to find the mysterious short, so board house. Now, we had about a per board. After another couple of days the first two questions were answered. week to work on the software and new and a few burns from the soldering iron, No hope for the last one. features while the boards were made. the boards and cables were ready. When the boards were finished Now came the moment of truth. MCU & FIRMWARE Eugene screamed, “The boards have Would the boards work? Would all of For a large project, we would nor- been delivered and they look awe- our effort pay off? Would the Cubs mally spec out the proper micro- some!” Remember, it’s the little win a World Series again? The easy processor that contained all the things in life. Of course, now came answer to all those questions was required functionality at the lowest another time-consuming task. We had “no.” Fortunately, a heat gun fixed a cost. However, for this stunt, consid- to stuff and solder two prototype few solder balls trapped under the con- ering the time schedule and the low boards and make all of the cabling. nectors. We then used a combination cost of the evaluation boards ($50), we Wow, we had forgotten how long it of Freon air and a Polar ToneOhm 550 just designed the main motor con- troller card to socket the evaluation board. Later designs incorporated just the microcontroller, but more about that later. As a good design note, always use optical isolators to buffer any signals going to motor drivers. When a driver melts, it commonly connects your voltage rails together and burns up your most expensive component in the circuit (it just knows which one). For bidirectional lines going to the microcontroller, you are probably fine. But, don’t forget that optical isolators need a lot of juice, so you can’t drive them directly from a microcontroller. After we picked the H8/3687, it quickly became apparent that we would need to scale back the design for this 8-bit microcontroller. This was not a 32-bit power PC processor clocking along at 1 GHz, which we had been accustomed to. We knew this was going to be a basic super-loop program, servicing the major firmware features and hardware interrupts. No real-time operating system, loads of RAM, or NAND flash memory for code execution and storage. So, we wrote several modules and ISR rou- tines to service the serial ports, motor controllers, LCD, and user interface. We wanted the code to run efficiently WWW.GiURUMELE.Hi2.ROand use as few system resources as possible.

USER INTERFACE An extremely important part of any project is the user interface. The end user rarely cares about the circuit board, processor, and the 1,000 hours of blood-and-guts work put in by the engineering staff (and, in most cases, neither does the project manager). The end user is more interested in ease of

26 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 27.qxp 2/6/2007 12:47 PM Page 1

Turn Digital Power into Real Power ries. dsPICDEM is a trademark of Microchip Technology Incorporated in the U.S.A. and other countries. Looking to bring the benefits of digital power conversion – including higher power density, lower cost features and accelerated innovation – to your product?

Microchip’s dsPIC®Digital Signal Controllers (DSCs) for Switch Mode Power Supplies (SMPS) and digital power conversion are designed for applications in AC/DC power supplies, power factor correction, DC/DC converters, uninterruptible power supplies, power inverters, digital lighting and advanced battery chargers.

GOING DIGITAL THE EASY WAY! microchip 1. Educate yourself Purchase and program your © 2007 Microchip Technology Incorporated. All rights reserved. 16-bit dsPIC® DSCs Learn the technical aspects of digital power and related development tools at.... DIRECT conversion and SMPS design with hands- www.microchipdirect.com FREE on training and web seminars from High Microchip. 10-bit, Speed Analog Flash 2 MSPS PWM Compar- 2. Accelerate your development Device Pins (KB) (CH) (CH) ators Speed up your design dsPIC30F1010 28 6 6 4 2 time with tools targeting digital power such as dsPIC30F2020 28 12 8 8 4 WWW.GiURUMELE.Hi2.ROthe dsPICDEM™ Buck dsPIC30F2023 44 12 12 8 4 Development Board. Visit our web site for more information about additional 3. Win stuff in our Digital Power Contest 16-bit devices supporting power conversion! Visit our web site and get coupons for discounted development tools when you REGISTER TO WIN a dsPIC DSC SMPS Development System. We are also giving away an Apple® iPod® mobile digital media player to one lucky winner! Visit our web site for complete contest information.

www.microchip.com/SMPS The Microchip name and logo, the Microchip logo and dsPIC are registered trademarks of Microchip Technology Incorporated in the USA and in other count Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs 2703017stout.qxp 2/5/2007 4:43 PM Page 28

use, whether the system can grammed one microcon- accomplish the required troller to set up and run the tasks, and its cost. user interface and send the We kept the first prototype control signals. The second clean and simple. We populat- microcontroller receives the ed a metal case with about a signal and controls the dozen potentiometers in a log- motors. Unfortunately, this ical layout. Most animatron- required another version of ics users prefer the old-fash- code. Of course, this was ion finger-numbing knobs, so kind of time consuming. We they can “feel” the monster. had to develop two boards So, we thought the poten- (master and slave) that used tiometers would allow the separate microcontrollers and user to dial in the settings of communicated wirelessly. the mask’s features, including Now came the fun part. the desired position, trim val- Actually, blowing things up ues, and speed limits. Poten- Photo 2—This is an example of screen output for the servo trim settings. In this is usually the most fun. In tiometers were chosen to be case, the user is setting the servo’s maximum return angle. this case, creating a user sturdy and heavy duty so they interface by displaying char- could stand up to tough use on a was fast approaching and our better acters to the low-cost 2 × 16 LCD movie production set. halves were getting impatient with us screen with buttons to select the It quickly became apparent that because of all the time we were options appealed to our creative sens- having the controller box physically spending on the project. Still, we had es. Remember: it’s the small things connected to the main motor con- gone too far to turn back. We had to that count. This also allowed for an troller board would limit the move- go wireless. easy-to-implement debugging and set- ments of the animatronics creatures. We used an off-the-shelf Reynolds up platform. Again, keeping things So, we decided to explore a wireless Electronics RS-232 transmitter receiv- simple is the key. You can squeeze a option. By this point, the end date er (TXLC-434/RXLC-434). We pro- lot of functions into menus, but then you must be willing to navigate vari- ous levels. We didn’t want that. Fur- thermore, we provided tools that used the PC’s serial port for additional We Listen. Think. And Create. enhancements, such as data logging, batch files, real-time feedback, and timed executions. Transversing the menus via the but- Distributed Digital Serial Industrial HMI I/O I/O I/O Computing tons was a bit of a pain, so we decided to upgrade to a touchscreen. We felt the user would appreciate this feature. SeaLINK Ethernet Serial Servers Offer: SeaLINK Ethernet serial However, we quickly realized the cost • 1, 2, 4, 8, and 16-Port Models for such an interface would be prohibi- servers are the fastest, • RS-232, RS-422, RS-485, and Optically tive; plus we already had mounted the Isolated Versions LCD screen. most reliable way to • Included Software Enables Virtual COM connect serial devices Port Operation After hours of scribbling, arguing, • Easy Installation and Confi guration and eating a lot of junk food, we set- to your network. • DIN Rail or Table Mount Design tled on a new direction. We decided to WWW.GiURUMELE.Hi2.RO• Extended Temperature Option Available transform our boring LCD screen into FCUS an amazing touchscreen through opti- On Success cal tripping sensors. Unfortunately, this used the last of the microcon- troller’s unused inputs and outputs. To achieve this goal, matching LEDs (Fairchild QED123) and phototransis- tors (Fairchild QSD123) were placed around the LCD. Now, when you press on the Plexiglas shield protect- ing the LCD, your finger trips one of the photodetectors, mimicking a but-

28 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703017stout.qxp 2/5/2007 4:43 PM Page 29

ton being pressed (see Photo 2). In addition, optional lines were set Photodetector Figure 2 shows the hardware lay- 12 mm 60 mm aside for stepper motor control.

out for the touchscreen with an 12 mm The headaches and addiction to example of a menu choice on the raw cookie dough began when Choose Run Mode: 20 mm 32.5 mm LCD. Finally, the phototransistor Man Auto Script PC when we started designing the feeds its signal to the buttons on closed-loop controllers. As you the microcontroller’s board. This know, the primary key to any LED 10 mm allows you to push the buttons or 55 mm closed-loop system is plenty of caf- the screen. Pure genius! We know. feine, while the other key aspect is Figure 2—Your finger will trip the path from the LED to the pho- clean feedback. If you’ve ever used CREATING MOTION todetector, simulating a touch on the screen. a microphone on stage, then you’re The actuator controllers form probably familiar with the term the true heart of the project. While open-loop controllers are for stepper “feedback.” In our monster’s case, there are many solutions on the mar- motors, solenoid switches, and off-the- feedback is good. Fire isn’t. For the ket for moving facial joints, such as shelf servos. Consequently, if you take sake of simplicity, feedback came eyebrows and jawbones, most don’t apart a servo, you will find a hidden from an inexpensive Agilent (Avago have the power and speed for lifelike closed-loop controller, which trans- Technologies) quadrature optical movement. Take for instance the lower lates a reference signal to the desired encoder (150 LPI). The HEDS-9700 jaw of the monster. To make it lifelike, rotation. Therefore, in order to control provided excellent reliability, low the jaw needs to snap closed in certain custom components like our high- noise, and good repeatability over dif- cases and appear as if it is talking or torque motors, the main board would ferent environmental conditions. growling in others. An off-the-shelf be the closed-loop controller for the servo could satisfy one requirement but high-speed or high-strength actuators. MOTOR DRIVER not the other. Although servos can be On the simple side, the open-loop For driving the motors and sole- used for other moving parts, such as the controllers consisted of buffered digi- noids, we used STMicroelectronics’s eyebrows, the mouth, eyes, and horns tal signals from the microcontroller. L6206 dual driver ICs, which can drive need more flexibility in control. This Straightforward PWM signals sent the 1-A motors at 30 V. These provided an was a good reason to create this large needed reference signals to the servos. excellent response time while keeping project and ignore our significant others. We first counted the degrees of free- dom (DOF) of each joint and quantified the needed motions. In short, the robot needed eight servos, four high-speed motion feedback controllers, and one solenoid controller. Although hydraulics and pneumatics would have been great solutions, the actor didn’t want a large gas or oil tank attached to his body. (Ah, actors. Typical.) We also knew that actors know little about electricity, so we kept it that way and moved on. For anyone familiar with the film industry, flexibility is a key to suc- cess. We had to be able to actuate numerous facial joints and not shock the actor. Fortunately, the needed cir- cuitry and softwareWWW.GiURUMELE.Hi2.RO fell into place. Note that the producer usually tries to pick someone from the SFX staff to wear the suit. Just look polite and run like hell. The shoots are long, the suits are hot, and you know about electricity. Enough said.

CONTROLLERS Basically, the controllers fell into two buckets: open and closed loop. For those non-controller junkies out there,

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 29 2703017stout.qxp 2/5/2007 4:43 PM Page 30

thermal requirements at a minimum. National Instruments, but the dSpace about 20 min. of the motors shaking To efficiently use the timers to drive card was already sitting in the better the monster to find the sweet spot. the motors, we had two timebases. computer. Hooking up the actual The generic algorithm technique was The servos needed a 50-Hz chopping motors and optical encoders to the finally dropped in the final hour for a frequency with a duty cycle of 5 to dSpace board gave us a good feel for the more straightforward routine that runs 10%, which correlates to 0 to 270° of system and provided us with reference the motor at fixed duty cycles and travel on most standard off-the-shelf data. Taking the simulation offline, we measures the response time of the sys- timebases. On the other hand, the DC could compare the output from the tem. Furthermore, our procedure sets motors controlling the eyes and horns perfect controller to the output from the Kp value, assuming a loop time of were set to 20 kHz, mostly to avoid the microcontroller’s emulator to veri- 1 ms to provide 50% of the maximum the audible range of the human ear. In fy the algorithm implementation. performance of the system. It uses half this case, the limits on the duty cycle the value for Ki that causes instability. came from thermal constraints. TUNING THE CONTROLLER It’s not pretty, but neither is a robot The H8/3687 microcontroller made After verifying that the integer math shaking its hinges loose for 20 min. it easy to hang several timer trigger came close enough to the floating-point Because the controller uses velocity points off one base time, saving on the dSpace controller for government work, as feedback (differentiating the posi- usage of independent timers. In the the next step was tuning the real sys- tion), Kd would just be multiplying case of the servos, the pulses can be tem. Most practical engineers would noise so it was dropped out. The actu- triggered sequentially to minimize just hook everything up and tune away al algorithm used feed-forward terms, power spikes, because the individual by hand. While some of that always split gains, and many signal filters— duty cycles are low. happens in the end, we took the chal- the secret is in the sauce. For special lenge of developing an automated tun- effects work, this is pretty high-tech, CREATING CONTROLLER CODE ing system. Why? Because we could. so we patted ourselves on the backs With the hardware in place, the true The first pass simply involved the and moved on. fun begins. (But it still isn’t as much microcontroller logging in the encoder fun as blowing stuff up.) When people position along with the motor com- IT’S ALIVE ask us what is the field of controls in mand to a host computer, which Putting together a project like this is terms of engineering, we tell them it’s processed the data through the serial challenging. You need a good plan and the art of moving actuators (motors, port. However, this proved only that the proper resources to get the job done. solenoids, etc.). For us, it’s also the art of the serial port was hogging all of the In the end, the electronics finally writing and debugging the code to move microcontroller’s possible bandwidth came together in perfect harmony and the motors, in addition to the electrical when active. Pass two involved mak- everything worked as we had planned. and mechanical designs for the system— ing the serial-communication code The motors hummed away while the the joys of a two-person team. more efficient and passing less data. solenoids opened and closed. We con- Not straying too far from the indus- trolled the system from our wireless try, the main controller algorithm was IMPLEMENTING THE CONTROLLER controller panel. Unfortunately, the PID based. We simulated the controller Hooking up the optical encoder, producers of the movie shrank the in a real-time environment and applied motor PWMs, and the microcontroller budget even further, which shrunk the genetic algorithms to tune the system. to a National Instruments 6602 (mul- monster from 12′ to 6′. The monster’s In a perfect world, the controller tiple high-speed timers) card through head became the actor’s head. Thus, algorithms would miraculously appear LabView provided more bang for the we didn’t need to control its eyes and in the code bug free. What happens in buck. (The LabView solution was mouth. We had two days to activate the real world is that the compiled code quite a bit more expensive than the the eyebrows and horns using a frac- finally works after days of debugging. previous solution.) A genetic algo- tion of the space originally planned. Then comes the big question. Is it real- rithm running on the PC tuned the We pulled it off using RC parts, but ly working correctly? In other words, controller through trial and error by our grand controller system was just because the WWW.GiURUMELE.Hi2.ROmouth moves, it does- taking advantage of the serial port shelved until the next movie. That’s n’t mean the controller works correctly. from a National Instruments DIO card show business for you. The first step is to verify that the (high-speed digital interface). The During the last few years, we’ve controller algorithm is in a “perfect” thought was to eventually put the updated our designs and used them in environment, where you are not limit- genetic tuning algorithm in the micro- other projects. In order to control mul- ed by integer math, bandwidth limita- controller, so it could tune itself. Plus, tiple robots, we came up with a modu- tions, and I/O problems. Luckily, we it just sounded cool. Even though Lab- lar design. Each motor board drives already had a dSpace 1103 board, View did a fine job of finding optimal fewer motors, but the system can which allowed MATLAB Simulink parameters for the very nonlinear sys- adapt to more situations. The micro- models to be compiled and run in real tem by applying advanced algorithms controllers can reflash certain areas of time. We could have used the fine found in my thesis on robotic control their own memory to remember set- suite of real-time products from (so you know they are good), it took tings, even if the power cycles.

30 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 31.qxp 1/30/2007 4:37 PM Page 1

PIC24 MCUs B6TS – Capacitive Touch Sensing ICs

Highly integrated family of 16-bit PIC® MCUs Capacitive touch sensing IC developed to be designed to meet the demanding needs highly tolerant of its working environment of real-time control. Common attributes with adaptive features such as self- among all PIC24 MCUs include reliable and teaching, auto threshold, and intelligent flexible flash memory, pinout, software and filtering to meet the demands of most peripheral compatibility, as well as common applications today. development tools.

mouser.com/microchip/a mouser.com/omron/a

Serial ATA Cable Assemblies

Cable assemblies with positive locking latches that ensure cable connection. Features high-speed Easy Ordering In Nanoseconds data transfer at 300MBps, can be hot swapped without shutting down or restoring system, built-in RAID support, 26AWG wire size, 1.5A max. current, and 40V max. voltage.

mouser.com/molex/a

Non-Isolated SMT and SIP DC-DC Converters

Open-frame NEWEST Products construction and small footprint enable designers to develop NEWEST Technologies cost-and space-efficient solutions. Features The ONLY NEW Catalog Every 90 Days programmable output voltage, remote on/ off, output overcurrent protection, and a temperature range of -40˚C to +85˚C.

mouser.com/tycopowersystems/a

For over 40 years engineers have relied on Mouser as their source for electronic components. RGB LED Light And now it’s easier than ever to order from our Engine catalog via phone or online — in nanoseconds. That’s why we deliver the ONLY 1,800+ page Light engines with catalog of the newest product information 4 times independent color WWW.GiURUMELE.Hi2.ROcontrol for dynamic a year. And with daily updates to over 740,000 products on-line, you can depend on Mouser to or preset pre-set color save you critical time to market! display. Features Experience Mouser’s time-to-market advantage! round footprint for design flexibility, 350mA drive Our vast selection of the NEWEST products, The Newest Products currents, three channel control with independent NEWEST technologies, new catalog every 90 For Your Newest Designs input/output, -4,000V HBM, and an isolated metal days, no minimums, and same-day shipping on base that makes wiring in series or parallel on a most orders, gets you to market faster. We make it common heat sink possible. easy to do business with Mouser!

mouser.com (800) 346-6873

mouser.com/lamina/a

The NEWEST Semiconductors | Passives | Interconnects | Power | Electromechanical | Test, Tools & Supplies from Mouser Electronics

Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners. 2703017stout.qxp 2/5/2007 4:43 PM Page 32

We’ve also been working on differ- ed all the B.S.E.E. courses as well. For business laser printers. You may con- ent kinetic-metric approaches, like the past nine years, he has worked for tact him at [email protected]. touch pads. Our goal is to create a Lexmark, doing mostly motion control suite of building blocks that can adapt work. In the last three years, he has PROJECT FILES to any situation when time and flexi- taken the system engineer role for con- bility is of extreme importance. sumer products. To date, he has been To download code and additional files, Film crews still use and prefer ani- awarded 11 patents with 16 more pend- go to ftp://ftp.circuitcellar.com/pub/ matronics systems even though com- ing in the fields of controls and sen- Circuit_Cellar/2007/200. puter-generated effects are increasing sors. During the past decade, Barry in popularity. That’s our story and has helped with dozens of independ- SOURCES we’re sticking to it. ent films. You may contact him at DS1103 PPC Controller If you know of a film crew that [email protected]. dSpace needs an inexpensive custom anima- www.dspace.ltd.uk tronics system, point them in our Eugene Zeldin ([email protected]) direction. We’d be happy to start a holds a Bachelor’s degree in Electrical NI PXI-6602 Counter/timer module new design, so long as they don’t want Engineering from the University of National Instruments Corp. www.ni.com to shrink the monster on us. I Illinois—Champaign/Urbana. With many different engineering interests, H8/3687 Microcontroller Eugene has held a variety of positions, Renesas Technology, Inc. Editor’s note: For more information including manufacturing engineer, www.renesas.com about this project, visit www.circuit project engineer, hardware engineer, TXLC-434 RXLC-434 RF transmitter cellar.com/renesas/winners/3340.htm. software engineer, technical lead engi- and receiver modules neer, and consultant on various proj- Reynolds Electronics Barry Stout holds a Master’s degree in ects in many fields: consumer www.rentron.com Mechanical Engineering from the Uni- (Motorola), industrial (GBC), and med- versity of Illinois—Champaign ical (Baxter Healthcare, Jeron). For the L6206 Dual driver ICs /Urbana focusing on controls and pro- past four years, he has worked at Lex- STMicroelectronics gramming. During this time, he complet- mark developing firmware for high-end www.st.com

April 14 & 15, 2007

Join robot enthusiasts of all ages as WWW.GiURUMELE.Hi2.ROthey gather and compete at the 14th annual Fire Fighting Robot Contest. Feel the heat of competition in one of five divisions, and see how an exciting Robotics Symposium and Olympiad help spark the flame of robot innovation.

www.trincoll.edu/events/robot

32 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 33.qxp 1/30/2007 1:54 PM Page 1

focus more on your goals and less on your code NEW!! PICC18 TM with OMNISCIENT CODE GENERATIONTM

TM PICC-18 PRO ANSI C COMPILER*, based on the PICC-18TM PRO is packaged with… reliable PICC-18TM Standard compiler, the PICC-18 TM TM PRO comes with ... HI-TECH PRIORITY ACCESS (at no extra cost): HI-TECH Software's 12 month web access to updates OMNISCIENT CODE GENERATIONTM andpriority technical support from arguably the Extracts information from multiple source files at the industry's best team of C compiler engineers. one time, allowing more intelligent state-of-the-art code generation that ... HI-TECH SATISFACTION GUARANTEE HI-TECH Software offers a 30 day money back ! Optimizes the size of each pointer variable in your guarantee. If for any reason you are not completely code based on its usage. satisfied with our product, simply contact us and we'll ! Eliminates the need for many non-standard C qual- refund the purchase price. ifiers and compiler options. ! Produces more optimal interrupt context switching code. ! Customizes the functionality of the included printf library function. ! Is simple to use. WWW.GiURUMELE.Hi2.ROCome and see us at Booth 937 * Can run on multiple platforms including Windows, Linux and Mac OSX. April 3-5, 2007

Introductory Offer: Save $300. Find out more or download a fully functional demo at http://www.htsoft.com/products/picc18procompiler.php

HI-TECH Software proudly supports the Microchip brand with industrial-strength software development tools HI-TECH Software LLC and C compilers. 6600 Silacci Way Gilroy, CA 95020 USA PICC-18TM is licensed exclusively to HI-TECH Software by Microchip Technology Inc. Ph:800 735 5715 Web: http://www.htsoft.com 2703016Bingham.qxp 2/2/2007 4:13 PM Page 34

FEATURE ARTICLE by Jeff Bingham & Lee Magnusson Inertial Rolling Robot Jeff and Lee’s H8/3664-based rolling robot is capable of inertial movement. A DC electric motor is attached to a pendulum and suspended inside an inflated ball, which provides the driving force.

We live in miraculous times. In pendulum inside of a sphere. With 2 continuous drain current were select- today’s world, it is now possible for degrees of freedom, it drives and tilts ed because of their low on-state resist- you to design and build devices that the ball (see Figure 1). With this geom- ance and their ability to handle even 20 years ago would have bor- etry, the robot can reach high speeds, extreme currents without a heatsink. dered on science fiction. Wheeled steer, and jump. In addition, it doesn’t The motor has a stall torque of only robots are now relatively common, get stuck when it flips over. As a toy, it 2 A, but you can upgrade to a larger and for the individual looking for exhibits enough entertaining motion to one if you want. The average voltage novel projects, new types of motion be quite endearing and very robust. As to the motor is varied by switching are often sought. a project, it offers an exciting venture between high and low states of the H- In this article, we’ll outline a into mechanical and electronic design. bridge at a high frequency (10 kHz). mobile robot design that adds a twist The robot’s electronics perform two This is accomplished by pulse-width to simple rolling (see Photo 1). We’ll main functions, actuation for motors modulating the voltage signals to the also discuss the electronics, software, and sensors for feedback. There is motor. The MOSFET H-bridge is driven and mechanical issues that we actuation by means of both a bidirec- by the two International Rectifier encountered. We hope that you enjoy tional brushed DC motor and a digital IR2184 Half-bridge MOSFET drivers. this robot as much as we have! proportional servo motor (see Figure 2). The IR2184 is designed for automotive The two motors provide motive force use and will operate with 10 to 25 V. ELECTRONICS and turning ability, respectively. Thus, the same 12-V source from the The robot employs a single driven The robot has a pressure sensor and batteries is used for both the gate-drive a motor-current sensor, although the supply to this driver as well as the volt- latter was not enabled in the current age supply for the MOSFET H-bridge. a) software design. The main processor is The MOSFET driver has only a sin- a Renesas Technology H8/3664 micro- gle IN command, which makes for controller (see Figure 3). We used a convenient interfacing. The driver protoboard for ease of construction. will turn on the high-side MOSFET The DC drive motor is powered by a for a logic level of 1 and the low side 12-V battery source consisting of 10 for a logic level of 0. This behavior is NiMH batteries. The servomotor and optimal in an H-bridge circuit with an the remainder of the electronics are inductive load, because the current powered by a regulated 5-V source. b) WWW.GiURUMELE.Hi2.RODRIVE MOTOR We used a brushed DC drive motor that has a+ and a– inputs. Forward drive is produced by connecting the positive input to the motor-voltage supply and the negative input to ground. Reverse drive is produced by switching the two inputs. Power Photo 1a—The robot’s inner core consists of an elec- amplification and bidirectional rota- tronics assembly and a mechanical drive assembly. b— tion is accomplished by means of a The robot’s spherical shell is an inflatable playground Figure 1—The robot was designed with CAD software ball. The inner core is suspended via a drive axle from MOSFET H-bridge. International Rec- to ensure the precise fit of components. In this view, the two plastic caps. tifier IRL3103 MOSFETs with 64 A of the spherical shell is cut away to show the robot core.

34 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703016Bingham.qxp 2/2/2007 4:13 PM Page 35

will automatically continue through the low side of the bridge (see Figure 4). How- ever, by turning on the low- side MOSFET, current can be carried more efficiently through the MOSFET, rather than through the parallel diode. Even though the IR2184 can be connected to the microcontroller directly, a buffer circuit is used to pre- vent damage to the micro- controller in case of miscon- nection. The buffer circuit also performs convenient logic functions so that only one PWM channel and one I/O port are necessary on the microcontroller. Table 1 is a truth table for this logic circuit, which uses a 7404 inverter and two Figure 2—The H8/3664 microcontroller connects to several components that provide control and sensing for the robot. The circuit 7402 NOR gates. Thus, the is basic and easy to connect to most other microcontrollers as well. logic circuit sends the PWM signal from one driver to the other, depending on the value at the motor instead of a 12-V motor. The structure can sense the environment. I/O port. The opposite driver is sent a motor worked well for a while, but it When the ball hits a barrier, it can be logic level of 0. eventually burned out. Be sure to pur- picked up as a pressure transient. A Hall effect current sensor (Allegro chase a 12-V motor for this electrical The absolute pressure sensor meas- ACS706) is set up in series with the design. ures pressure with respect to a perfect motor in order to measure motor cur- vacuum. Thus, the sensor reads both rent for control purposes. The sensor’s SERVO MOTOR atmospheric and ball pressure. Since connection is relatively straightforward. The servo motor is a standard atmospheric pressure at sea level is It outputs a voltage corresponding to remote-control hobby servo motor. It 14.7 psi and the ball may be inflated the motor current offset at 2.5 V for zero has a built-in position feedback loop, with 1 psi, the sensor has only a small current, with a sensitivity of 130 mV/A, based on an internal potentiometer, range that it can sense. However, and has a range of ±15 A. The sensor is which enables its position to be com- because impacts of the ball produce connected directly to an ADC port, but manded directly. both positive and negative changes in it is not enabled for control in software The servo is an extremely easy com- pressure, the sensor is effective at at this time. ponent to interface with a microcon- detecting collisions. This sensor is easy We were accidentally shipped a 6-V troller. Power is supplied with a 5-V to interface with the microcontroller:

source and control is pro- VOUT from the sensor is connected vided through a 50-Hz directly to an ADC port. Decoupling PWM signal. The PWM and filtering capacitors are recommend- Current feedback signal is connected to ed in the MPX5100A’s datasheet. ADC the FTIOB output port PWMWWW.GiURUMELE.Hi2.RO Motor (amp) Drive (motor) on the H8/3664 through SOFTWARE a 7404 inverter, which is The software provides the basic H8/3664 PWM used as a buffer. drivers necessary to read sensor infor- Servo (motor) mation and to control the two motors. PRESSURE SENSOR The drivers are set up to run in inter- ADC Pressure (sensor) We used a Freescale rupt loops or operate continuously. Semiconductor (Continuous conversions are set up for MPX5100A absolute the A/D sensor readings.) Communi- Figure 3—The H8/3664 microcontroller interfaces with PWM output to a pressure sensor (with a cation with these low-level drivers is drive motor and a steering servomotor. There is input from a pressure sen- sor and a current sensor on the drive motor, which interfaces through the range from 0 to 16.7 psi) available via function calls. Applica- microcontroller’s ADC port. so the inflated ball tion functionality is available by pro-

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 35 2703016Bingham.qxp 2/2/2007 4:13 PM Page 36

approximately 10 kHz. This is included to ensure that the servo is implemented on the H8/3664 not overdriven. microcontroller using Timer V. A/D conversion for the pressure Since Timer V does not have a sensor is accomplished in the adc.c buffered register for changing file that’s available on the Circuit the duty cycle of the PWM, an Cellar FTP site. Only one channel is interrupt is set up on compare used (AN0) in order to store the match to update the value in value of the current pressure. The the compare register and elimi- ADC is set up to run in continuous nate the possibility of erro- operation, and the current value from Figure 4—During the PWM on state, current passes through the neous pulses being generated. the pressure sensor can be read at upper-left MOSFET and then the lower-right MOSFET.When the any time. PWM switches off, current continues through the motor inductance and then through the lower-left MOSFET.To reverse the motor’s SERVO MOTOR CONTROL direction of rotation, the opposite side of the H-bridge is switched. The servo motor is con- MECHANICAL COMPONENTS trolled by pulse-width encoding In this article, we present our at a rate of 50 Hz. The pulse for parameters for constructing this robot; gramming the desired robot behavior standard hobby servos ranges between however, customization is the spice of in the main function and calling low- 1 and 2 ms with 1.5 ms corresponding life. In order to modify this robot, you level driver function calls. to the neutral position. should keep a few things in mind. The For our robot, the main function Timer W on the H8/3664 microcon- ideal implementation of this robot has contains a simple sinusoidal trajectory troller is set up to overflow at a fre- its weight as far away as possible from of the drive motor and the steering quency of 50 Hz, or a 20-ms period. the robot’s driven axle. This allows servo motor, followed by a straight The period in terms of Timer W the robot to convert a maximum trajectory. This trajectory demon- counts is 49,152. The compare-match amount of momentum or torque into strates some basic capabilities of the register is set up in buffered PWM rolling, because the robot essentially robot. Details about the low-level driv- mode, so the PWM-output signals can moves based on the “falling” of the ers and the complete source listing are be generated without concern for the pendulum. If the pendulum rotates too posted on the Circuit Cellar FTP site. timing of writing to the compare-match far, the ball will counter-rotate, so bal- We experimented with the pressure register. The new value will be auto- ancing motor torque and pendulum sensor, but it was not used in the appli- matically loaded at the beginning of torque is important (see Figure 5). cation due to the difficulty of debug- the PWM cycle, eliminating the chance Simulating the robot’s motion can ging. Sample code is provided, which for making writes at the wrong time also help. Using the motion equa- should theoretically enable the robot to and causing erroneous PWM-signals. tions in Figure 6, different physical switch from a straight trajectory to a In terms of Timer W counts, 1 to 2 ms parameters and motor-control scenar- sinusoidal trajectory when an obstacle corresponds to a GRB value ranging ios can be modeled to determine the is hit and thus change direction. from 2,458 to 4,915, with a neutral optimal design. These equations can position of 3,686. Limit checks are be solved using any numerical solver DC DRIVE MOTOR CONTROL and plotting the output. In order The code for the DC drive motor to model the motion in the tilt

and the steering servo motor both use j direction (the plane perpendicu- PWM. They’re both in the pwm.c file lar to rolling), the same equa-

on the Circuit Cellar FTP site. g tions can be simplified and used. Iw, mw i The brushed DC motor must However, the simplest and most have variable speed and torque important analysis of the tilt

rw capabilities, and it must operate Ia, mw motion is the turning radius: bidirectionally. The motor current- rW rTURN = ly uses voltage control, but it has ra tan()ϕ WWW.GiURUMELE.Hi2.ROθ the capability to use current con- a trol. Current control hasn’t been where ϕ is the tilt angle of the implemented in software. The pendulum. These two-dimensional

torque in a brushed DC motor is Gear ratio r simulations should be more than proportional to the current through adequate for predicting the robot’s the motor (related by the motor’s basic motion. Im, θm

torque constant), so it may be Motor Arm advantageous to use current control MANUFACTURING if you want to control torque. We used off-the-shelf mechanical Voltage control is achieved by a Figure 5—Driving the internal pendulum causes the robot sphere components for this design. Most of PWM signal to the motor at to rotate. the parts can be purchased at your

36 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703016Bingham.qxp 2/2/2007 4:13 PM Page 37

local hardware store. PWM (TMOV port) I/O (P72 port) PWM1 PWM2 Once you cut the shafts to size, The mechanical components 0010carefully round the ends with a that you must build must consist 1000file. Any raised burrs will make it of several plates, which when 0101difficult to slide anything onto assembled make up a pendulum 1100the shaft. Finally, use a die to and the inner-workings of the thread the drive shaft, you should Table 1—A logic circuit provides an interface to a single PWM out- ″ rolling robot. The pendulum is put and a single digital I/O port on the microcontroller. In this truth need to thread only about 1 on essentially a box with a series of table, TMOV and P72 are the outputs on the H8/3664 microcon- either end of the shaft. threaded holes that are used to troller. PWM1 and PWM2 are the inputs to the H-bridge. The final step is to cut two attach the drive motor and servo- holes into the rubber kick ball. mechanism. screws used in the project. First, determine an axis through the The first step is to cut out the rough The brackets used to attach the ball. This can be accomplished by shapes of the different plates that servo pushrod should be made slightly deflating the ball and folding it into make up the pendulum and a custom different than the other plates. First, quarters. The points of the quarters universal joint. The method of creat- cut out a strip of 18-gauge sheet should approximate the location of an ing these plates depends on the mate- metal, drill the holes, and then bend axis through the ball. Next, inflate the rials you work with. We chose alu- the bracket. The part is small enough ball. Using a compass, trace two cir- minum, which requires machining so that drilling the holes before bend- cles on the ball and use the lock ring with a water-jet or milling cutter. ing makes the manufacturing process from the drain assembly to determine However, the body could just as easily much easier. the necessary diameter of the circles. be made from polycarbonates or The pushrod itself is easily made by Lastly, deflate the ball and use a pair acrylics and cut out with a scroll saw. cutting a short length of threaded rod of scissors to cut out two holes defined Once you cut out the parts, you and connecting two pushrod clevis by the circles you have drawn. Make must drill holes to attach the drive pins. The next step is to cut the shaft- sure you don’t cut the ball’s plug; other- components. Next, tap the drilled ing to length in order to create a drive wise, it will be impossible to inflate. holes. Taps can be purchased as a set shaft, gear shaft, and a support shaft. or individually at your local hardware There are several ways to accomplish ASSEMBLY store. Make sure the taps match the this. The simplest is to use a hacksaw. Once the mechanical parts are man-

Save Up To 60% On Electronic Components

Exciting New Mini-Boards Wide Range Including, • Real Time Clocks (DS1307) • Memory Cards ONLY • Power Supplies $6.90 • DC Motor, Stepper Motor and More

Powerful New ATMega Controller • Includes ATMega128 Microcontroller • High-Speed Operation • Heaps of I/O • In-Circuit Programming ONLY $28.90 • Ideal EmbeddedWWW.GiURUMELE.Hi2.RO Controller

Save Heaps on Components We carry a wide range of Integrated Circuits, Microcon- ONLY trollers, Capacitors, LED's $4.90 and LCD's. All at very competitive prices. We are your one-stop shop for Microcontroller Boards, PCB Manufacture and Electronic Components. www.futurlec.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 37 2703016Bingham.qxp 2/2/2007 4:13 PM Page 38

be placed on the pulleys and ten- ⎡ 2 ()θ ⎤ α&& ⎡−− ()θ ⎤ Ia + maa r + I m maaw r rcos + I m ⎡ ⎤ mgraasin ⎡T ⎤ sioned. Then the slide plate (M27) can ⎢ ⎥ ⎢ ⎥ = ⎢ ⎥ + ⎢ ⎥ ()θ ()2 &&θ θθ& 2 () T ⎣⎢mrraawcos + Im I w + m a + m w r w + Im ⎦⎥ ⎣ ⎦ ⎣⎢mrraaw sin ⎦⎥ ⎣ ⎦ be tightened down. Any electrical connections can be made and the pendulum subassembly Figure 6—Ia is the moment of inertia for the pendulum. ma is the mass of the pendulum. ra is the length of the pen- . .. can be inserted into the ball by slight- dulum. θ is the angular position of the pendulum. θ is the angular velocity of the pendulum. θ is the angular accel- ly stretching the opening. Then the eration of the pendulum. Iw is the moment of inertia for the wheel. mw is the mass of the wheel. rw is the radius of the . .. universal joint assembly can be insert- wheel. α is the angular position of the wheel. α is the angular velocity of the wheel. α is the angular acceleration of ed and the drive shaft with the miter the wheel. Im is the inertia of the motor. T is the applied torque. g is the gravitational constant. gear can be attached. At that point, the universal joint plate can be con- ufactured and the circuit has been (M16) to the universal joint plate nected to the bearing blocks on the built, you can assemble the compo- (M29). As an additional step, you pendulum along with the servo nents and finish the robot. Assembly might want to preassemble the miter pushrod bracket. is relatively straightforward. After gears (M20), drive shaft (M15), and The final step is to insert the rubber examining the exploded view, drawing it gear shaft (M19) to check the toler- gaskets and the flanged ends of the should be an easy task to determine how ance of the gears and set the align- drain bowls into the ball and bolt the the pieces fit together (see Figure 7). ment of the bearing blocks. Once driveshaft to the sink drains with lock The only difficult part of the assem- clearances are checked, the assembly nuts. Next, tighten the sink drain bly process involves inserting the can be returned. lock rings firmly to the ball and apply mechanical parts in the rubber ball, The pendulum subassembly can be Teflon tape to the sink-drainpipe con- because some assembly must take finished by attaching the remaining nections. Finally, flip on the power place inside the ball. We recommend side plate (M26). In addition, one of switch with a screwdriver, tighten fully testing the electromechanical the bearing blocks can be attached to both end caps, inflate the ball, and assembly before attempting to place it the back plate (M1) by using the sup- stand back! (Drawings of each step are inside the ball. port shaft (M28) with two washers and posted on the Circuit Cellar FTP site.) It is easiest to start by assembling two collars. Another bearing block can three sides of the pendulum subassem- be attached to the front plate (M18) FINDINGS bly (M1, M18, and M26). The flanged with one miter gear (M20), two wash- The rolling robot was an intriguing bearings (M17) can be loosely fitted ers, the driven sheave (M14), and the and difficult project to work on. The into the front and back plates, while gear shaft (M19). Attach the battery mechanical design is novel and non- the back plate spacer (M2) and servo boxes with Velcro. The belt (M7) can trivial. However, we found that the motor can be tightly secured to the back plate. The servo arm is near the bottom of the pendulum. One end of the servo pushrod can be attached to the servo arm at this time and the other end can be attached to the servo pushrod-bracket (M25). The motor subassembly can be put together by attaching the motor to the motor plate (M22) and the motor plate to the sliding plate (M27). Next, a flanged bearing is loosely installed. Then the bore reducer () is inserted on the motor shaft, a washer is placed on it, and the powerWWW.GiURUMELE.Hi2.RO sheave (M23) is pressed and tightened onto the bore reducer and motor shaft. After check- ing that the motor is free to rotate, the flanged bearing can be tightened down. The motor subassembly is attached to the pendulum subassem- bly by loosely connecting the slide plate (M27) to the pendulum front plate (M18). The next step is to attach two bear- Figure 7—This figure shows an exploded view of the mechanical components of the rolling robot. Numbers in the top ing blocks and the electrical housing half of the bubbles correspond to the parts list that can be downloaded, while numbers in the lower half specify quantity.

38 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703016Bingham.qxp 2/2/2007 4:13 PM Page 39

resulting unique motion available lot of fun building ours, and the PROJECT FILES with this robot was worth the effort. resulting product is a very interesting To download the code and additional With that being said, we learned a few accomplishment. Just remember us files, go to ftp://ftp.circuitcellar.com/ things that might be helpful in build- when you take over the world with pub/Circuit_Cellar/2007/200. ing a similar rolling robot. your rolling robot army. I The biggest difficulties were caused by the tight working area inside the RESOURCE rubber ball and not having powerful Jeff Bingham ([email protected]) has Freescale Semiconductor,“MPX5100A enough drive components. While a B.S. in Mechanical Engineering from Datasheet,” 2005, www.freescale.com assembling the robot inside a rubber Idaho State University and is pursuing /files/sensors/doc/data_sheet/MPX5100 ball through small openings is possi- his Ph.D. in the same field at the Mass- .pdf. ble, debugging is nearly impossible. achusetts Institute of Technology. In Thus, during the debugging process, his spare time, he likes to build things, use a hamster ball or some other clear such as small autonomous rolling SOURCES sphere that allows easy access to the spheres. ACS706 Linear current sensor components. Allegro Microsystems, Inc. It is also important to ensure that Lee Magnusson ([email protected]) www.allegromicro.com the components used match both the has a B.S. in Mechanical and Materi- mechanical and electrical require- als Engineering from Rensselaer Poly- MPX5100A Absolute pressure sensor ments. Initially, we burned out the technic Institute and an M.S. in Freescale Semiconductor, Inc. drive motor because we were shipped Mechanical Engineering from the Mass- www.freescale.com a 6-V motor, instead of the 12-V motor achusetts Institute of Technology. His IR2184 and IRL3103 Half-bridges that we expected. With a little interests include electromechanical International Rectifier patience and some elbow grease con- modeling and design. Lee currently www.irf.com struction of the robot should go works in the MIT Biomechatronics Lab smoothly. (http://biomech.media.mit.edu), H8/3664 Microcontroller We hope that this article encourages where he designs the latest in active Renesas Technology Corp. you to build a similar robot. We had a powered prosthetics. www.renesas.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 39 2703020tweed.qxp 2/5/2007 8:55 AM Page 40

ISSUE 200 SPECIAL FEATURE by Dave Tweed Then and Now

Dave traces the 200-issue history of Circuit Cellar. Embedded applications have come a long way since 1988.

It’s always fun to take some time out that wasn’t directly accessible. It was Fast-forward through the next 12 to remember how things used to be, very difficult to determine whether any years, which saw the rise and fall of and to see how they’ve changed over given capacitor canister had blown fuses. the 8080 and CP/M machines, along the years. The 19 years that Circuit It occurred to him that the phase with many other TV-based computers Cellar has been in existence as an inde- relationships among the three currents and game consoles and the eventual pendent publication (not counting in the three leads would change in var- rise of the IBM PC (see Photo 1). In Steve’s BYTE column) have seen the ious recognizable patterns, depending early 1988, there were about 8 million embedded computing field—and indeed, on which fuses were conducting cur- DOS machines deployed, mostly the microcontroller itself—grow from a rent. It also occurred to him that one 8088/86 (IBM PC and PC/XT, along tiny niche market into a major industry. of these new-fangled with compatible systems from other We’ve had over 800 authors (829 as would be a good way to monitor the manufacturers) and 80286 (PC/AT) of October 2006) contribute articles to zero crossings at the outputs of the based. The 80386 had been available these pages, not to mention the count- current transformers and report the for a few months (at 16 and 20 MHz) less advertisers over the years, and this problems. I helped him develop the and the 68030 was just being intro- represents a significant cross-section of software to accomplish this, written in duced by Motorola. Note that 1,200-bps the industry from which we can draw 8008-machine language (numbers, not modems were pretty much state of the some lessons and maybe even make assembler mnemonics) and entered art, but within a year, 9,600-bps units some predictions about the future. into the machine via the front-panel were available. Microsoft Windows If you have been active in this field toggle switches. It was extremely sim- didn’t exist yet, at least not in usable since the 1980s, you’ll resonate with ple by today’s standards, but it form (version 3.1 appeared in 1992). the following ramble through the nonetheless represented an example of This was the era of 1-Mb DRAM memory banks; if not, maybe you’ll a real-time, microprocessor-based chips and 256-Kb SRAMs. Desktop learn something new! embedded computer system. CPUs operated at frequencies in the 10- My own involvement with to 20-MHz range. Photo 2 shows embedded computers began the evolution of the associated around 1976. The father of one mass storage technology. of my high school classmates was an electrical engineer, and BIRTH OF CC INK he had built himself one of the It is instructive to go back and 8008-based “Mark8” comput- look at the first issues of Circuit ers from the plans published Cellar Ink, published bimonthly in Radio-Electronics magazine in 1988. The first issue dealt in July 1974. WWW.GiURUMELE.Hi2.ROalmost exclusively with video He was involved in the power projects, including a motion-trig- industry, and one of the prob- gered multiplexer from Steve Cia- lems he faced had to do with rcia, a hand scanner for security three-phase power factor correc- applications by Ed Nisley, and a tion capacitors. It seems that video format converter from these were packaged three to a Mark Voorhees. The exception container, connected in delta Photo 1—Personal computing in the 1980s. On the left is my CP/M machine, was a discussion about RISC CPU fashion, with just the three which is based on the J.B. Ferguson “Big Board.” A spare CPU board sits in architectures by Tom Cantrell. leads at the corners of the trian- front of the keyboard. On the right is the Zenith Data Systems PC (an IBM The second issue focused on PC/XT clone) that replaced it. To the left of the CP/M monitor is a KIM-1 board, gles brought out. Each capacitor a 6502-based single-board “system” that was popular with hobbyists. It includes more fundamental data-acquisi- had a series fuse for protection a hex keypad and display, along with a monitor program in PROM to operate it. tion issues, including tempera-

40 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703020tweed.qxp 2/5/2007 8:56 AM Page 41

ture and high-resolution storage, usually in the timing. Issue three explored form of a prepackaged PCB X-10 power-line communi- module that takes care of cations, video signal timing, the low-level details of and software emulation (bit- interfacing to high-per- banging) of UARTS. formance chips. In issue 4, Steve and Ed In 1988, nearly all embed- teamed up for a scanning ded firmware was stored in ultrasonic sensor using a UV-erasable programmable stepper motor. Tim McDo- read-only memory (PROM) nough and Dennis Grim chips. These chips contained wrote an article about a arrays of bits that could be stepper motor-based robot flipped one way (typically 1 arm. Ed also wrote an arti- to 0) electrically, but required cle about making use of the exposure to ultraviolet light IBM PC joystick port. in order to flip them the Issue 5 covered a broad Photo 2—This collection of disks (sitting on top of the CP/M disk drive cabinet shown in other way (0 to 1). Any modi- range of topics, including the Photo 1) shows the advances in magnetic disk storage. From left to right across the bot- fication to the firmware tom are a 14″ platter and an 8″ platter. The former shows evidence of a head crash debut of Jeff Bachiochi’s about halfway out. To the right of these is the ubiquitous 3.5″ hard drive, which comes in required getting a freshly- “From the Bench” column, capacities of hundreds of gigabytes these days. Below that is a 4-GB “” that erased chip out of the eraser, in which he discussed RS-232 fits in a compact flash memory slot. From right to left across the top are 8″, 5.25″, and programming it, swapping it ″ interfaces. Also, a 10-MHz, 3.5 floppy disks. with the chip in the target, 8-bit ADC was presented, and then putting the old chip along with more about the X-10 system troller that integrates most of that on- in the eraser. and Steve’s Remotely Operated Video- chip. The embedded applications Some microcontrollers were available based Electronic Reconnaissance appearing in the pages of Circuit Cellar with on-chip UV-EPROM, but these (ROVER) system. were mostly based on 8051-architecture tended to be quite expensive and still Issue 6 was the final issue in 1988. It chips, Z80/64180-based boards, and in a needed to be removed from the target included articles about the ROVER soft- few cases, the 68000 (see Photo 3). circuit for erasing and programming. ware, fiber optics, an update on the Over the years since then, the 8-bit One of the biggest fundamental changes ImageWise video digitizer, and a com- microprocessor has been almost com- for embedded firmware was the develop- plete 6809-based data acquisition system. pletely replaced by increasingly power- ment of the electrically erasable PROM I should note that a significant portion ful single-chip microcontrollers, which chip, known as EEPROM or flash PROM, of each of these issues was devoted to now have CPU cores of 8, 16, or 32 bits the latter referring specifically to chips in engineer-to-engineer communications, and operate at clock rates into the hun- which the minimum erase size is larger both in the form of letters to and from dreds of megahertz. Microprocessors than a single address—either a “sec- the Circuit Cellar staff and reprints of are still used in the larger embedded tor” or the entire chip. selected conversations pulled from the systems that need huge amounts of Finally, in-circuit reprogramming Circuit Cellar BBS. We’ll come became a possibility, and micro- back to this topic later. controllers with on-chip code memory became much more THE TECHNOLOGY BASE widespread. Indeed, a signifi- There were very few outside cant fraction of Circuit Cellar advertisers in that first year, so, articles today are devoted to the to get a broader feel for the gen- topic of chip programming eral level of the available tech- hardware and software. nologies at the time,WWW.GiURUMELE.Hi2.RO it’s helpful Gate arrays existed in 1988, to look at some of the other but they were relegated to high- journals from the same year, volume applications by the high such as BYTE and Dr. Dobb’s nonrecurring engineering (NRE) Journal. (Finally! Being a maga- costs. Programmable logic for zine pack rat pays off!) low-volume applications was Obviously, the key element in Photo 3—The evolution of the underlying technology is shown by this col- limited to PROMs, programma- an embedded computing appli- lection of chips. At the upper left are the Intel 8008 and 8080A. In the ble logic devices (PLDs), and pro- cation is the processor itself, group at the upper right are the single-chip Intel 8748 microcontroller grammable array logic (PAL). across the top, a 2764 UV-EPROM on the left, and a Hitachi HD64180 which might be a microproces- CPU chip in a PLCC package. Across the bottom is the Motorola All three types of devices sor that requires external mem- MC68000 CPU in its enormous 64-pin DIP package. Clockwise from there share a common architecture. ory and I/O, or a microcon- is the newer MC68020 in a pin-grid array package. The difference is in which parts

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 41 2703020tweed.qxp 2/5/2007 8:56 AM Page 42

of the architecture are field-program- using up valuable chip real estate that Chief among these, of course, is the mable. The architecture is a set of could be better used in other ways. issue of programming languages. Back input pins that drive an array of AND The PAL contains a programmable in 1988, assembly language was king, gates. The outputs of the AND gates AND array, but a fixed OR array, in but nearly every microprocessor had form an array of intermediate signals which groups of pterms are OR’d some sort of dialect of BASIC avail- that drive a second array, this time of together for a particular output. At able as an interpreter as well. C com- OR gates. The intermediate signals are this point, on-chip flip-flops were pilers were also becoming available for often called pterms (product terms), incorporated into some devices, with most of the small processors. C++ was because the AND operation is some- feedback directly into the AND array, just starting to make an appearance times referred to as a Boolean product. and now you could build simple one- (for larger computers), but did not yet The outputs of the OR gates are the chip self-contained state machines. have any significant “mind share.” outputs of the device. The PAL proved to be extremely The other big development tool for In a PROM, the AND array is fixed popular and has evolved into the com- an embedded system is the debugger. in the form of the internal address plex programmable logic device In 1988, this was mostly accomplished decoder, which has the further restric- (CPLD) we know today. However, by either ad hoc means—if the code tion that only one pterm (a word CPLDs still make certain assumptions gets *here*, blink this LED—or by the select line) is active at a time. about the ratio of internal logic to use of in-circuit emulators. The latter Nonetheless, useful logic can be (and external I/O, and this trade-off isn’t were usually expensive, and required was) implemented using PROMs to always appropriate for certain applica- that the target chip be removed and drive the registers of state machines. tions. The field-programmable gate replaced with a cable connected to a The PLD is the most general device, array (FPGA), which first appeared in fairly large box containing a special in which both the AND array and the the early 1990s, has evolved as an version of the chip, or some other OR array are programmable. alternative approach that fits the other implementation of the architecture. The PLD had a relatively short life- end of that spectrum very nicely. The JTAG interface standard was time, however, because manufacturers adopted by the IEEE in 1990. Original- soon realized that the full generality of DEVELOPMENT TOOLS ly intended as a means for testing having every pterm available to every Let’s talk a bit about the develop- chip-to-chip connections through a output was rarely used, and it was ment tools for embedded computing. PCB, it was sufficiently general that

WWW.GiURUMELE.Hi2.RO

42 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703020tweed.qxp 2/5/2007 8:56 AM Page 43

features relating to the chips them- RF have brought the cost of RF spec- machines in question to begin with. selves could be added as well. It took a trum analyzers and other instruments Contrast this to the situation today. few years to catch on, but by the late down to the hobbyist range. The pro- ARPANET has evolved into the Internet 1990s, many chips could be debugged liferation of communication interfaces we know and love/hate today, and there and/or programmed through their has brought about the need for devices are virtually no barriers to access for any- JTAG interfaces. I think it took a that can convert from pretty much one, be they technically inclined or not. while for the manufacturers to realize any one protocol to any other. BBS machines have disappeared, that the investment of chip area Although GPS has actually been oper- although I hear there are still a few devoted to these functions was well ational from the early 1980s, it has been diehards out there. Usenet news and e- worth it down the road in terms of only in the last 10 years or so that the mail list servers still exist but most convenience to the design engineer, receiver technology has dropped in price unmoderated groups have been inundat- which translated into more design-ins (and size) to the point where it is suit- ed with so much off-topic content that and ultimately greater sales volumes. able for mass consumer applications. they’re virtually useless. Even chip vendors who did not Nowadays you can get an OEM receiver The advent of the World Wide Web adopt the JTAG standard came up module for a few tens of dollars. and the underlying HTTP servers has with their own low-pin count inter- The other big wireless technology created a new form of group communica- faces for debugging and programming kicker has been the wireless telephone tion, the “web forum,” which relies on a their chips. Today, it’s practically a.k.a. “cell phone,” named for the more-or-less graphical user interface to unheard of NOT to do in-system pro- honeycomb-like arrangement of the convey the same kind of information as gramming and debugging. terrestrial base stations, known as before. Frankly, I don’t see the point, and “cells.” Although the underlying tech- even with broadband Internet access, I EMBEDDED APPS nology is highly proprietary, many find that the real-time interaction with Let’s take a second look at the kinds embedded applications have been able the forum server via a web browser is of applications that Circuit Cellar to make use of it by treating it as a orders of magnitude slower than reading addressed back in 1988. They can best “black box.” The suppliers of OEM locally-cached news and e-mail messages be described as an interrelated mesh interface modules have been able to using my mail-client software. involving video signals, home control, take advantage of the technology general data collection, and communica- advances that are driven by the mar- SKILLS IN DEMAND tions. Communications consisted prima- ket for consumer cell phones. Well, I hope this wander down rily of RS-232 asynchronous serial links. memory lane has been at least enter- Interestingly enough, if you look at the NETWORKING taining, if not somewhat instructive. I articles published by Circuit Cellar in I alluded to engineer-to-engineer com- think it’s interesting to note what has- 2006, there’s a very similar pattern. Video munications earlier. In 1988, this con- n’t changed in the last 19 years, along projects still deal with NTSC signals, sisted of bulletin board systems (BBSs), with all of the new opportunities that although there’s a smattering of informa- and for those who had access to it have arisen. I think it’s clear that if tion related to higher-resolution computer through work or school, Usenet-based you have the ability to put hardware displays. Ethernet, USB, and various wire- newsgroups, and e-mail lists. and firmware together, there will less technologies have largely supplanted A BBS was typically a PC of some sort always be a need for your skills. I RS-232 for communications, enabled by connected to one or more phone lines via the availability of single-chip implemen- modems. Users would dial into the tations, although we still run articles machine periodically to download new Dave Tweed has been developing dealing with bit-banging asynchronous messages and upload their own respons- hardware and real-time software for serial interfaces on small microcon- es. The signal-to-noise ratio tended to be microprocessors for more than 30 trollers. The latest tricks involve bit-bang- very high, since everyone participating years, starting with the 8008 in 1976. ing video and USB interfaces. had to have sufficient motivation and dis- His system design experience includes Home control and basic data acquisi- cipline to participate in the first place. computer design from supercomputers tion, including weatherWWW.GiURUMELE.Hi2.RO monitoring, Usenet was based on (mostly) Unix- to workstations, microcomputers, continue to be perennial favorite topics. based minicomputers and larger systems DSPs, and digital telecommunications The issues related to driving and using that phoned each other up periodically systems. Dave currently consults for stepper motors are still revisited from using a protocol known as UUCP (Unix- various companies in projects involv- time to time. to-Unix CoPy) to exchange mail and ing embedded DSPs and FPGAs. You That’s not to say there isn’t a much news traffic. Some machines had full- may reach him at [email protected]. broader range of topics that has been time access to a high-speed network enabled by all of the new chips that known as ARPANET, but the concept are available now. MEMS sensors for remained the same. Again, the value of RESOURCE acceleration, rotation, and pressure the messages tended to be high, since D. Tweed, Circuit Cellar Ink Index, have appeared in all kinds of applica- you had to have certain technical qualifi- www.dtweed.com/circuitcellar/index. tions. Mixed-signal chips for audio and cations in order to get access to the htm.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 43 2702019Kagan2.qxp 2/5/2007 9:56 AM Page 44

FEATURE ARTICLE by Aubrey Kagan Generic Modbus Simulator (Part 1) Theory and Preparation

Aubrey introduces the topic of a Modbus implementation on a PC. He covers the Modbus protocol and an approach for documenting the register set of a Modbus slave and even a family of slaves in Excel.

In the industrial world, there are with creating a Modbus interface for would use a 16-bit register) as well as many data-transmission standards that two products. In both, I needed to sim- relays and proximity sensors. The have endured. The 4- to 20-mA cur- ulate a controller in a way that I could master controller reads and writes to rent loop and the Modbus communi- send the same communication again these registers when the slave is cations protocol are two examples. It and again, while trying to debug the addressed over the serial network. is not only resistance to change that software. In its simplicity, Modbus Each product has a different inter- maintains their popularity. They are categorizes the I/O space as single-bit face, so I needed to create a technique simple to understand, error resistant, digital (coils) registers or as 16-bit reg- for the user to enter the memory map and enjoy a huge installed base. And isters. Interpretation of holding regis- on the PC and then interpret this probably just as important, they are in ters and input registers (16 bit) is left data in order to access the target the public domain. to the slave’s designer. They could be device over the Modbus. The slave’s The Modbus concept, originally used for ADC values (obviously this registers are normally presented as a developed by Modicon, table to document the allows a master controller address space for the net- to interact with a remote Slave address Function code Data byte CRC work integrator. slave over an RS-232 serial (1 byte) (1 byte) (function dependent) (2 bytes) One look at the details line to read and modify on the Datagrid class of Function code 01HEX Start Number of coils/inputs/registers industrial inputs and out- Read coils address 2 bytes Visual Basic, and I decided puts. The concept has 2 bytes that Excel contained Function code 02HEX been expanded and stan- Read discrete inputs everything the project

dardized to use modems Function code 03HEX needed for the register and RS-485 communica- Read holding registers table entry along with the

tion, allowing longer dis- Function code 04HEX added bonus of user famil- Read input registers tances of communication iarity. In addition, the few

and multiple remote con- Coil Data bytes followers of my publica- Function code 05HEX trollers. address FF00HEX to energize output, 0000HEX tions will tell you that I Write single coil 2 bytes to de-energize output In this series of articles, have more than a passing I will describe how to cre- Register Data bytes interest in Excel. Of course Function code 06HEX address 16-bit Data ate a universal ModbusWWW.GiURUMELE.Hi2.ROWrite single register 2 bytes it would have been possi- simulator residing on a ble to create the serial con- Coil start Number Data bytes Function code 0F PC. To do so, I will build HEX address of outputs Bits formatted into bytes trol within Excel, but the Write multiple coils on the concepts that I first 2 bytes 2 bytes seed for this project is a presented in “Visual Basic dedicated test jig that runs Register Data bytes 2005 and the Serial Port” Function code 10HEX start 16-bit value for each register on a PC that doesn’t have Write multiple registers address Number of bytes = number of registers × 2 (Circuit Cellar 197, 2006), 2 bytes Microsoft Office. in which I described the creation of serial port Figure 1—Take a look at the construction of the master transmission frame. The data field MODBUS PROTOCOL communications using content depends on the function code. There are other codes in the Modbus specification, The Modbus serial pro- but I have not considered them in this article. All 16-bit addresses and data are sent with Visual Basic 2005 Express. the most significant byte first. However, the CRC is transmitted with the least significant tocol standard allows for I have been involved byte first. the communications to be

44 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2702019Kagan2.qxp 2/5/2007 9:56 AM Page 45

in ASCII format or trans- generating the CRC. I Slave address Function code Data bytes (function dependent) CRC mitted in 8-bit bytes (RTU (1 byte) (1 byte) in 2-byte multiples (2 bytes) strongly recommend that format). The ASCII format you study the documents is optional, but all Modbus for a deeper understanding Function code 01HEX Number of Data bytes units must be capable of Read coils bytes of data Bits of data compressed into of the Modbus. For this supporting the RTU format. following 8-bit bytes application, I implemented Function code 02HEX Thus, I am going to consid- Read discrete inputs the most common function er only the RTU format. codes: 1 to 6, 15, and 16

The serial port hardware Function code 03HEX Number of Data bytes (all numbers are decimal Read holding registers bytes of data 16-bit values interface has several param- following Number of bytes = number of unless otherwise indicat- eters associated with it: the Function code 04HEX registers × 2 ed). The other codes are for Read input registers data rate, the number of more complex products. If stop bits, and parity. Confi- you need them, you could Coil Data bytes dence in the integrity of Function code 05HEX simply use this program as Write single coil address FF00HEX to energize output, 0000 HEX the message is provided by 2 bytes to de-energize output a basis to implement the depending on master’s command a 2-byte cyclic redundancy extra functionality. check (CRC) that is Register Data bytes attached to the end of the Function code 06HEX MODBUS ADDRESSING Write single register address 16-bit Data (same as in master’s transmission frame; so, 2 bytes command) The different categories strictly speaking, parity is of the Modbus register

not required. Function code 0FHEX Register Data bytes space and their address Write multiple coils address Number of outputs The maximum length of a 2 bytes 2 bytes allocations are shown in Modbus packet is 256 bytes. Function code 10HEX Table 1. Different function Write multiple registers The specification requires codes are used in order to 3.5 transmission bytes differentiate between the between Modbus packets. Function codes Exception code register ranges. The master 81HEX, 82HEX, 83HEX, 01–Illegal function But in this example, the 84HEX, 85HEX, 86HEX, 02–Illegal data address must select the correct 8FHEX, 90HEX 03–Illegal data value interframe delay is not an MSB indicates Modbus 05–Acknowledge function code based on the slave exception to a issue because we will be particular function address being accessed. sending a single command Modbus system designers and waiting for a response. Figure 2—This is the slave response packet. As in the master’s transmission, the content typically arrange all the User interaction is unlikely of the data field is context-dependent. If the slave takes exception to the master’s request, remote’s locations in a sin- to be faster than the few it issues an exception response, which it indicates by setting the most significant bit of the gle memory space. Depend- function code. Although the acknowledge is not (strictly speaking) an exception, it is treat- milliseconds required. ed in the same way. All 16-bit addresses and data are sent with the most significant byte ing on the function access, The Modbus transaction first. However, the CRC is transmitted with the least significant byte first. an offset would be added to consists of a master sending the address. a packet to an addressed Let’s assume that there slave and then waiting for a response. ed as shown in Figure 1. The response was a coil at address 1, an input status When a slave receives a command, it packet from the slave is shown in Fig- register at address 2, an input status responds, provided the address match- ure 2. Refer to the documents listed in location at address 3, and an input reg- es and the CRC is correct. If there is the Resources section of this article ister at location 4. The aforemen- an error in the instruction, it responds for more information about the differ- tioned transformation would make the with an exception message indicating ent instructions and their responses, addresses 1, 10002, 40003, 30004. the problem. In some cases it may including a step-by-step description of When the command is translated into take some time for the slave to com- plete the instruction. In this case, the Register range Modbus func- Read single Read multiple Write single Write multiple exception code is an “acknowledge.” WWW.GiURUMELE.Hi2.RO(decimal) tion access code code code code In a normal operation, if the transmis- 0–10000 Coil (bit access) 11515 sion fails either through a lack of 10001–30000 Input status 2 2 N/A N/A response or an exception response, it is (read only) up to the master to act on this by (bit access) reporting a problem and attempting a 30001–40000 Input register 4 4 N/A N/A retransmission. Because this applica- (read only) (bit access) tion is only intended for development, only single transactions are generated 40001– Holding register 33616 and monitored. (bit access) The generic transmission packet Table 1—Check out the Modbus functional allocation. The Modbus address space is divided into single bit and from the Modbus master is construct- word types and read only and read/write.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 45 2702019Kagan2.qxp 2/5/2007 9:56 AM Page 46

get into the operational details of the Excel worksheet and the Visual Basic code, I supplied an executable file along with the ADAM1 worksheet and an Excel template in addition to some user instructions. They are in the ModbusExecutable.zip file posted on Circuit Cellar’s FTP site. Read the user’s guide before installing the application. Keep in mind that I have not had many oppor- tunities to test this with different ver- sions of Windows and Excel, so there may be some compatibility issues.

EXCEL USER INTERFACE Before you use the Excel files posted on the Circuit Cellar FTP site, you should open them with your version of Excel and save them. Some weird problems occurred between the Mod- Photo 1—Take a look at the setup for the ADAM-4017+. Note the hidden lines from rows 17 to 206, which are blank and bus test application and Excel when have been hidden to compress the image to show here. Read-only addresses are placed in read/write memory space. the files had been processed by a dif- ferent version of Excel. the transmission frame format, the Table 3 shows the different types of I decided to allow for a product fam- first address would be 0 (Modbus cre- modules included in this application. ily approach to the Excel interface so ates an offset of 1 from the official that a group of products could appear address to the accessed address) fol- EXECUTABLE FILE in a single workbook. Excel lends lowed by 1, 2, and then 3. Remember For those of you who don’t want to itself to tabbed operation, so each that the function codes will be member of the family occupies different. a tab. In fact, the ADAM-4024 Address (decimal) Description Access Groups of similar locations occupies two tabs because 1 Digital input 0 (bit) Read only are typically collected together there is an overlap of the ana- 2 Digital input 1 (bit) Read only to allow the use of the group log and digital address spaces 3 Digital input 2 (bit) Read only functions that enable access to (see Table 2). 4 Digital input 3 (bit) Read only multiple locations of the same I allowed for 256 address type with a single command. spaces within a Modbus map. 40001 D/A output 0 (16-bit word) Read/write Thus, all coils are normally There are cases in which more 40002 D/A output 1 (16-bit word) Read/write grouped together, all holding are required and can be easily 40003 D/A output 2 (16-bit word) Read/write registers, and so forth. This added by expanding the table. I 40004 D/A output 3 (16-bit word) Read/write convention does not actually should mention that the work- appear in the Modbus specifi- sheets are protected (without a 40201 Output 0 configuration (16-bit word) Read/write cation and is not applied uni- password) to prevent erroneous 40202 Output 1 configuration (16-bit word) Read/write versally. modifications to the formulas. 40203 Output 2 configuration (16-bit word) Read/write Products like the Advantech Any changes to the worksheet 40204 Output 3 configuration (16-bit word) Read/write ADAM-4024 four-channel ana- like copying or writing to a log output module (one of the protected cell requires the WWW.GiURUMELE.Hi2.RO40211 Module name 1 Read only modules that I experimented worksheet to be unprotected 40212 Module name 2 Read only with) allow the memory (click Tools, Protection, and 40213 Version 1 Read only spaces to overlap since they 40214 Version 2 Read only Unprotect Sheet). After mak- use different function codes 40215 Communications safety enable Read only ing modifications, I recom- (see Table 2). The user inter- 40216 Communications safety flag Read only mend that you protect the face presented in this article 40217 Channel enable Read/write worksheet again. allows for this overlap, as you To create a worksheet from will see later. For develop- Table 2—Here you see the Modbus register map of the ADAM-4024 analog a blank template (supplied ment, I used members of the output module. Note that it also has four digital inputs that overlap the D/A with the files), consider Photo outputs. There are several read only registers in the 40000 register space. It Advantech ADAM family of doesn’t really matter whether my interpretation of the Modbus convention is 1, which was derived from the Modbus interface modules. correct.You still have to be able to interface to this device. ModbusTemplate.xls work-

46 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 5.qxp 10/26/2006 11:22 AM Page 1

PC Oscilloscopes & Analyzers

DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

DSO 2.0

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, ExternalWWW.GiURUMELE.Hi2.RO 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. 2702019Kagan2.qxp 2/5/2007 9:56 AM Page 48

of 1 to 4, where 1 is within the address space 1–10000, 2 is equivalent to the address space 10001–30000, 3 relates to address space 30001–40000, and 4 is of course for 40001 and up. If there is no address entry in column D, the corre- sponding cell in column E is blank. This is realized with the following for- mula in cell E8:

=IF(D8=””,””,(IF(D8<10001,1,IF (D8<30001,2,IF(D8<40001,3,4)))))

This is copied to each of the cells in this column in the table. The next column (F) generates the actual address that will be used in the Modbus message sent through the serial port. Cell F8 contains the formula:

Photo 2—The user interface derives information from the Excel worksheet in Photo 3. Note how the address gaps =IF(E8=””,””,CHOOSE(E8,D8-1,D8 have been compressed. The addresses and the descriptions have been imported directly from the Excel worksheet. In addition, I also clicked on Load Profile for Turn on D0. The value on the far right of the line for address 17 has -10001,D8-30001,D8-40001)) been as a result of a Load Profile action. Based on the value of a cell in column book. You can add or remove work- and 40002 and then clicking and drag- E, the associated cell in column E con- sheets (each represented by a tab) by ging the autofill handle to get to tains the address of column D modi- right clicking on the tab and select- 40008. fied for transmission. ing the appropriate menu item. You You can take a second approach: The individual and block write and should also rename the tab to the enter 40001 in cell D8 and then enter block read commands are derived in a name of the product. This is the “=D8+1” in cell D9. You can then copy similar fashion in columns G, H, and descriptor that will be loaded into this cell down to D15. There are sever- I. For instance, cell G8 contains: the user interface as you can see in al other options. Imagine the work you the list box in Photo 2 (just beneath would have to do if you were to use the =IF($E8=””,””,CHOOSE($E8,5,”n/ the ADAM-4056S Modbus tab). If Datagrid control in Visual Basic. You a”,”n/a”,6)) you add any worksheets, copy the must enter only those addresses that range A1: S263 from the first sheet you want the Visual Basic interface to As you can see in cell D3 to the new sheets. recognize. Even if there are large gaps, (f=COUNT(B:B)), there are a number of In an unchanged template, cell D1 is as there are in this example, they must Excel formulas that count different blank, as are columns C and D from be filled in their correct location. I things. However, I also wanted to row 8 and down. First, you enter the wrote the code in the Visual Basic user know where the last entry in column Module address in cell D1. Entering a interface to allow for the compression D was in order to aid processing when description in column C, such as “Ana- of the display. An address is combined I access the table from Visual Basic. log Input 1” is purely descriptive. It is with the associated description to cre- Excel doesn’t have a formula to calcu- helpful when selecting a location to ate a single line (see Photo 2). Also note late that, so I wrote my own function access, but it has no influence on the the dashed lines (“------”), which indi- (see Listing 1). You can find this in the results of the worksheet. This text cate the display compression. Excel Visual Basic workspace accessed appears in the largeWWW.GiURUMELE.Hi2.RO list box on the Once you enter the address in the using + within Excel. Modbus tab of the user interface, as Excel worksheet, the interface type in Photo 3 shows the worksheet for a seen in Photo 2, where it reads “Digital column E automatically reflects a value module with digital outputs. The Input 0,” and so on. setup procedure for the Excel For every valid address, you worksheet is identical to the digi- must fill in the Modbus address Module identification Description tal input in Photo 1. In order to in the corresponding cell in col- ADAM–4017+ Eight-channel analog input (16-bit ADC) allow certain predetermined umn D. For a block of addresses, ADAM–4024 Four-channel analog output (12-bit DAC) actions, I provided for several you don’t need to individually Four digital inputs profiles to store the associated enter each address. You can use ADAM–4051 16-channel digital inputs output patterns. Simply add a Excel’s autofill feature by filling ADAM–4056S 12-channel digital outputs name for the profile (without car- in the first two addresses 40001 Table 3—These Modbus modules are set up in ADAM1.xls. riage returns, line feeds, etc.)

48 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 49.qxp 2/6/2007 1:58 PM Page 1

WWW.GiURUMELE.Hi2.RO 50.qxp 2/2/2007 12:37 PM Page 1

The premier conference and exhibition for PCB engineering, design and manufacture professionals

CONFERENCE: MARCH 25-30, 2007 EXHIBITION: MARCH 27-28, 2007 Santa Clara Convention Center in Santa Clara, CA

Get ready for an amazing conference! • Over 35 Professional Development and Technical Conference courses— 43% of them new to PCB West!

• 14 “FREE Tuesday” courses—12 of them new!

• Keynote Address by Mentor Graphics’ WWW.GiURUMELE.Hi2.ROHenry Potts! Gold Sponsor: • Opening Night Extravaganza! • Exhibitor Presentations, giveaways and more!

Media Sponsors: Download your copy of the 2007 conference brochure today at www.pcbwest.com. 2702019Kagan2.qxp 2/5/2007 9:56 AM Page 51

Cells is the only option checked. It is important to note that the Visual Basic application opens a second copy of Excel. Any changes made to the workbook since the last save will not appear in the user interface. Any sub- sequent changes, no matter how often the workbook is saved, will not appear until the user reloads the workbook.

GAINING ACCESS Up till now, all that I have discussed has been theory and preparation. The next step is to access the contents of the Excel worksheet from within Visu- al Basic. Unfortunately, I will have to leave you in suspense until next month, when I’ll also describe how to send and receive Modbus messages Photo 3—This is the worksheet for the ADAM-4056S, a digital output module. I hid some rows (37 to 216) again to from the PC. Stay tuned! I compress this picture.

Aubrey Kagan is a professional engi- starting in cell J7 and on (see Photo 3). profiles as you like. The number of neer with a B.S.E.E. from the Tech- These will be shown in the user inter- profiles is maintained in the cell D5 nion—Israel Institute of Technology face for user selection. The user inter- that contains the formula: and an M.B.A. from the University of face program will import the associat- the Witwatersrand. He works at ed inputs. If a cell is empty, no value =COUNTA($7:$7)-8 Emphatec, a Toronto-based design is imported into the user interface. house of industrial control interfaces The profiles can be overlaid, as you which counts all the nonblank and switch-mode power supplies. In will see later. entries in row 7 and removes the addition to writing several articles for In the UI, if I select Turn On D0 and eight columns used for features other Circuit Cellar and having ideas pub- click Load Profile, followed by a click than profiles. In case you haven’t lished in other periodicals, Aubrey on Turn on D1 and a second click on guessed, Photo 2 shows the user wrote Excel by Example: A Microsoft Load Profile, then both values will be interface with the selection of the Excel Cookbook for Electronics Engi- imported to the user interface and be worksheet in Figure 2. neers (Newnes, 2004). able to be used for a block write. The Once you finish working on the 255 in the top right-hand corner of the worksheet, you should protect it again large list box in Photo 2 is a result of a if you previously unprotected it. Click PROJECT FILES Load Profile of Turn on D0 in the Pro- Tools, Protection, and Protect Sheet To download the code, go to ftp://ftp. file list box. You can have as many and then ensure that Select Unlocked circuitcellar.com/pub/Circuit_Cellar/ 2007/200. Listing 1—You can find the last entry in the column. This is accessed by the =LastEntry($D:$D)for- mula in cell D4. The function looks at each of the cells in column D, starting at the bottom and working its way RESOURCES up until it finds an entry. Because this function works on every page (the range is valid an all worksheets), the switch between worksheets can sometimes lead to an incorrect value in D4. The way to solve this is to add the Modbus-IDA, Modbus Application Calculate procedure to the SheetActivate event as seen at the end of this listing. The upshot is Protocol Specification, V1.1a, 2004, that everything is recalculated at every tab selection change. www.modbus.org/docs/Modbus_ WWW.GiURUMELE.Hi2.ROApplication_Protocol_V1_1a.pdf. Dim iI As Integer For iI = Range(“d3”) To 1 Step -1 Modbus.org, “MODBUS Over Serial If Cells(iI + 7, 4).Value <> “” Then Line: Specification & Implementation Exit For Guide,” V1.0, 2002, www.modbus.org End If /docs/Modbus_over_serial_line_V1.pdf. Next iI LastEntry = iI End Function SOURCE Private Sub Workbook_SheetActivate(ByVal Sh As Object) ADAM-4024 Analog output module Calculate End Sub Advantech www.advantech.com.tw

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 51 2703012eady.qxp 2/5/2007 9:57 AM Page 52

APPLIED PCs by Fred Eady

Build a PIC Platform Microchip Technology’s PIC18F97J60 microcontroller will be a great fit for many of your remote control and automation applications. But you might find it difficult to work with due to its TQFP packaging. Fred has the perfect solution: build up your own PIC18F97J60 platform.

The Microchip Technology out about any of the PIC18F97J60 maybe I should use the term “design PIC18F97J60’s datasheet comprises 472 parts. Take a look at Photo 1. You trade-off” instead. If you have designed pages. If you read through the first cou- can’t plug any of them into a socket, around the ENC28J60 stand-alone part, ple of pages, you’ll notice that the because every PIC18F97J60 family you know that a logic level translation PIC18F97J60 actually comes in a trio of member is packaged in a TQFP. That is required if you want to run some of flavors. The PIC18F97J60 is the largest means you will just have to build up a the PIC microcontrollers as full-speed of the group, hosting 100 pins, 70 of PIC18F97J60 platform of your own. hosts to the ENC28J60. ENC28J60 which are capable of some kind of I/O However, before you start the design devices at revision levels below B5 have operation. The PIC18F97J60’s little and build process, let’s find out why a SPI clocking restriction that requires a brother, the PIC18F87J60, comes fitted we want to do this. minimum SPI clock speed. To meet the in an 80-pin TQFP. The baby bear SPI clock speed requirement, many of PIC18F67J60 is contained within the PIC18F97J60 the PIC microcontrollers must run at a smallest 64-pin TQFP. The PIC18F87J60 Designed as a logical extension of voltage level that enables the PIC sys- offers 55 usable general-purpose I/O the Microchip Technology ENC28J60 tem clock to generate a SPI clock fast pins, while the smaller PIC18F67J60 stand-alone Ethernet engine, the weighs in with 39 free I/O pins. PIC18F97J60 is a single-IC combina- Each member of the PIC18F97J60 tion of the ENC28J60 and a PIC18 family is stocked with 3,808 bytes of microcontroller. Everything you’ve SRAM and an 8-KB chunk of Ethernet come to know and love about PIC TX/RX buffer memory. Program flash microcontrollers is part of the memory capacity ranges from 64 KB PIC18F97J60. As you would expect, in the PIC18F66J60, PIC18F86J60, and the PIC18F97J60 parts can run a bit PIC18F96J60 to a maximum of 128 faster than most other PIC18 parts, KB of program flash memory in the with a maximum clock speed of PIC18F67J60, PIC18F87J60, and 41.667 MHz. PIC18F97J60. If 64 KB is not enough The PIC18F97J60’s main reason for flash memory and 128 KB is way too existence is to solve some of the origi- much, you can opt for the nal ENC28J60’s problems that PIC18F66J65, PIC18F86J65, or stemmed from simple physics. There’s PIC18F96J65, allWWW.GiURUMELE.Hi2.RO of which carry 96 KB only so much Ethernet data that you of program flash memory. can pump over a SPI in a given amount For program flash memory or SRAM of time. The PIC18F97J60 eliminated requirements outside of the standard the SPI bottleneck by incorporating the PIC18F97J60 family limits, you can ENC28J60 on-chip with the PIC18 choose to hang some external memory microcontroller. In the case of the from the pins of the PIC18F96J60, PIC18F97J60 family members, the inte- PIC18F96J65, or PIC18F97J60. The only grated ENC28J60 engine’s memory area Photo 1—Here’s a reconnaissance satellite view of all other real advantage of using the high- and SRAM buffers are directly accessi- of the current PIC18F97J60 family members. I was end PIC18F97J60 part is an extra serial ble by the PIC18F97J60’s PIC18 micro- tempted to design around the 64-pin part, because it is much easier to handle. However, that would not help port and a few more ADC inputs. controller subsystems. those of you who may wish to use the extended func- There’s one thing I haven’t called “Problem” may be a bad word, so tionality of the full-blown 100-pin PIC18F97J60.

52 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703012eady.qxp 2/5/2007 9:57 AM Page 53

Figure 1—This is a boilerplate that I’m sure you’ll be embellishing with your own set of peripheral devices.

enough to provide reliable data flow cation around the PIC18F97J60 family tem clock circuit is attached to the between the ENC28J60 SPI and the of devices. Don’t get me wrong; there PIC18F97J60’s OSC1 and OSC2 pins. host PIC’s SPI portal. Most of the cur- are still plenty of applications in The PIC18F97J60 requires a single 25- rent crop of standard PIC LF devices which the new ENC28J60 silicon can MHz crystal if the Ethernet functions cannot acquire their full clock speeds provide a best-fit solution. Everyone of the PIC18F97J60 will be utilized. I at voltages less than 4.5 VDC. Since in the world doesn’t use PIC micro- decided to go ahead and include the 32- the ENC28J60 is a 3.3-VDC part with controllers in embedded Ethernet kHz clock circuitry as well. I’ve found non-5-V-tolerant digital outputs, the applications. However, no matter that having a real-time clock available ENC28J60 designer is forced into a which microcontroller host you pre- to the embedded Ethernet application design trade-off, which runs the PIC fer, it can be attached to an is very handy. microcontroller at 5 VDC and buffers ENC28J60. You’ll also need to incor- There are five PIC18F97J60 oscilla- the ENC28J60’s digital outputs with porate an ENC28J60 if you are work- tor options that are common across an external piece of buffer silicon. ing on embedded Ethernet applica- the PIC18F97J60 family of devices. All of the ENC28J60’s SPI design tions with the Microchip dsPIC line of PIC18F97J60 high-speed (HS) crystal trade-offs have been addressed in the microcontrollers. So, even though the modes include the use of either a new B5 ENC28J60WWW.GiURUMELE.Hi2.RO silicon. There is no PIC18F97J60’s grass looks greener, standard crystal, as we have done in longer a clocking minimum-speed there is a reason Microchip still our PIC18F97J60 design, or a ceramic requirement for the ENC28J60. makes the ENC28J60 available. oscillator. To mix things up, you can However, if you choose to use a PIC The PIC18F97J60 is actually very enable the PIC18F97J60’s phase microcontroller that cannot attain easy to bring up in the hardware sense. locked loop (PLL) circuitry and invoke full-speed operation at 3.3 VDC, you Figure 1 shows that the microcontroller HSPLL mode. The PIC18F97J60’s PLL will need to buffer the ENC28J60 digi- personality of the PIC18F97J60 needs subsystem consists of a 5× PLL that is tal outputs if you run the PIC host at no more than any other PIC microcon- sandwiched between a PLL prescaler 5 VDC. troller requires. Each of the and a PLL postscaler. Both the The ultimate workaround to all of PIC18F97J60’s power pins is bypassed prescaler and postscaler can be config- the ENC28J60 design trade-offs is to with a 0.1-µF capacitor. A standard PIC ured to divide by two (1:2) or divide design your embedded Ethernet appli- microcontroller crystal-controlled sys- by three (1:3). The postscaler can also

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 53 2703012eady.qxp 2/5/2007 9:57 AM Page 54

be configured out of the circuit (1:1). To enable the PIC18F97J60’s inter- thinking big, I decided to try to lay the As I mentioned earlier, you must nal 2.5-VDC voltage regulator, you PIC18F87J60’s 80-pin TQFP pads down

supply a 25-MHz clock source to the must tie the ENVREG pin to VDD. inside of the PIC18F97J60’s 100-pin PIC18F97J60, because you are intending Otherwise, you must provide a source TQFP-pad layout. That too was a “no to use the PIC18F97J60’s Ethernet capa- of power for the PIC18F97J60’s core go,” as the PIC18F97J60 and the bilities. Disabling the 5× PLL and the externally. Since you will be running PIC18F87J60 don’t match up in other postscaler will automatically disable the PIC18F97J60 at 3.3 VDC, I prefer places as well. They also have the same the prescaler and provide a 25-MHz tying the ENVREG pin, a 1-μF filter incorrect transposition of the Ethernet clock frequency to the PIC18F97J60’s capacitor, and a 0.1-μF bypass capacitor differential signals over general-purpose

internals. To obtain the maximum to the PIC18F97J60’s VCAP pin over the I/O signals between the intertwined clock frequency of 41.6667 MHz, you incorporation of an external 2.5-VDC pair of pad layouts. So, I scrapped the must enable the 5× PLL, disable the power supply circuit. idea of multiplexing the PIC18F97J60 PLL postscaler, and configure the PLL To keep the cost of the project family of devices on a single PCB. prescaler for a 1:3 operation. If you do down, the PIC18F97J60 and associated After a short moment of reflection, I the simple math (5 × 25 MHz/2) with circuitry will be mounted on a simple decided that if I wanted to design for the prescaler set for 1:2 and the double-sided PCB. When I do these the PIC18F67J60 64-pin part or the postscaler disabled, you’ll see that the types of projects, I try to put myself in PIC18F87J60 80-pin part, having the resultant frequency is well beyond the the reader’s shoes. I try to include PIC18F97J60 100-pin part on the board PIC18F97J60’s operational capabilities. enough flexibility in the project to allow would work out just fine. The The minimum clock frequency that the reader to be able to adapt the project PIC18F97J60 designer does not have to can be sustained with the 5× PLL to his or her needs. My original idea was use the capability of the 100-pin part enabled is 3.8889 MHz (i.e., 5 × (25 to include pads for both the 64- and 80- that does not exist in the lower-pin- MHz/3)/3). Disabling the 5× PLL and pin variants of the PIC18F97J60 on the count devices. Thus, the 100-pin maxing out the postscaler and same PCB. That would have allowed the PIC18F97J60 was in and the prescaler values, yields a minimum reader to use either of the parts and it PIC18F97J60 device family pad multi- clock frequency of 2.7778 MHz. would have eliminated the need to pro- plexing was out. External Clock (EC) and ECPLL duce multiple PCBs for each The PIC18F97J60 Ethernet interface modes, which accept the externally PIC18F97J60 family device. circuitry is identical to that of the generated incoming raw-clock signal If you’ve ever played around with 64- ENC28J60. The PIC18F97J60 Ethernet through the OSC1 pin, will work in and 80-pin TQFP pad layouts, you interface design is built around the Bel the clock frequency domain exactly know that you can place the 64-pin pad Fuse BM0810-1X1T-06 10/100Base-TX like the HS and HSPLL modes. The layout neatly inside of the 80-pin pad AutoMDIX belMag, which includes fifth PIC18F97J60 clocking mode is layout. That works only if both the 64- integral indicator LEDs. The LEDs are Internal Oscillator mode (INTRC). and 80-pin TQFP pads are pitched iden- simply indicators as far as the One of the five PIC18F97J60 clocking tically. All of the PIC18F97J60 family PIC18F97J60 is concerned. Remember: modes, which becomes the primary members’ pads are pitched identically the ENC28J60 uses the indicator LEDs clock, is selected using the FOSCX at 0.5 mm. The difference in the 64- to determine portions of its duplex trio of configuration bits. All of the and 80-pin TQFP packages is simply configuration at power-up. The PIC18F97J60’s configurable oscillator four extra pins per side. If you were lay- PIC18F97J60 multiplexes the Ethernet components (5× PLL, prescaler and ing down a standard PIC microcon- indicator LEDs with general-purpose postscaler) are set up by the bits you troller in the 80-pin package and did I/O pins on PORTA and you can code into the PIC18F97J60’s OSC- not hardwire any of the I/O, you could forego the Ethernet indicator func- TUNE register. easily place a 64-pin pad package with- tions and use the PORTA, RA0, and There’s nothing new in the in the 80-pin pad package and just RA1 pins for I/O purposes. PIC18F97J60’s MCLR circuitry. The ignore the two general-purpose I/O pins Another difference is the external bias PIC18F97J60’s ICSP programming/ at each flat corner when the smaller resistor. For the PIC18F97J60, it is speci- debugging interfaceWWW.GiURUMELE.Hi2.RO is no different package was installed. fied as 2.26 kΩ. The value of the exter- than any other PIC. Outside of the Unfortunately, in the case of the nal bias resistor varies from revision PIC18F97J60’s Ethernet interface, PIC18F97J60, the Ethernet differential level to revision level on ENC28J60 there is only one other design that you inputs and outputs ride on two of the parts. The bias resistor is essential to the must take care of. The PIC18F97J60 corners in the outermost pin posi- operation of the PHY module’s internal contains an internal 2.5-VDC voltage tions. The PIC18F67J60’s 64-pin pack- analog circuitry and it influences the regulator to provide power to the age’s Ethernet-differential pins shift TPOUT signal amplitude. Messing with PIC18F97J60’s microcontroller core into the general-purpose I/O pins of the value of the bias resistor can poten-

from the PIC18F97J60’s 3.3-VDC VDD the PIC18F87J60 80-pin package. That tially cause the Ethernet transmit supply. The PIC18F97J60’s internal alone should have been enough to waveform to violate the IEEE 802.3 2.5-VDC voltage regulator is con- squash the dual-IC pad idea for the specification. So, you want to use what trolled by the ENVREG pin. PIC18F97J60 project board. Of course, Microchip Technology specifies.

54 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703012eady.qxp 2/5/2007 9:57 AM Page 55

I’ve pretty much nit- STMicroelectronics or Sipex picked all of the part, which makes it easy to PIC18F97J60 hardware par- acquire from many sources in ticulars, as it pertains to this magazine. Five 0.1-μF putting things on a PCB capacitors plus one of the with solder. So, let’s turn 3232 variants are all it takes our attention to the rest of to put the PIC18F97J60’s seri- the supporting circuitry. al port in place. I also wres- tled with whether or not to ESSENTIALS replace the traditional nine- Some of you may remem- pin shell connector with ber that some time ago I header pins. I hate making up built an ASIX Ethernet NIC little cables for this and that, development board that and I’ll bet you do too. The used 0603 passive devices. I nine-pin shell connector for swore that I would never the RS-232 port stays. I also ever again put my eyes and Photo 2—There’s nothing more satisfying than bringing up a design from fiberglass went with the standard RJ-12 and copper. I’ve included enough accessibility to the PIC18F97J60 to allow you to hands into so much trouble. jack for the ICSP portal as write your own drivers and application or use the prefab Microchip TCP/IP stack. However, I’m finding that I well. That allows me to use can squeeze 0603 packages into tight is effectively like chiseling on a round the Microchip MPLAB ICD 2 right out places where the 0805 just can’t go. rock. A complete TCP/IP stack for the of the box. So, here we are, back in 0603 land. PIC18F97J60 is free on Microchip’s web I have a lot of experience providing The driving force behind the essen- site. All you have to do is conform to embedded Ethernet devices via my tial supporting circuitry is the firmware some of the hardware conventions that online store. I’ve noticed that many of that will run on the PIC18F97J60. are specified in the Microchip TCP/IP you have the need for HTTP capabili- Reinventing the wheel is not some- stack’s compiler.h file. ty. The new Microchip TCP/IP stack thing any of us want to do. Writing An RS-232 serial port is a must-have. has enhanced its HTTP firmware. To PIC18F97J60 driver code from scratch The MAX3232 can be had as an take full advantage of the TCP/IP

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 55 72.qxp 10/26/2006 11:13 AM Page 1

PC/104 Single Board Computers

Low Price, Low Power, High Reliability 200 MHz ARM9 using Linux development tools Power as low as 1/4 Watt

5 boards, over $ 99 2000 configurations qty 100 Fanless, no heat sink

SDRAM - up to 128MB $129 qty 1 Flash - up to 128MB onboard

TS-7200 10/100 Ethernet - up to 2 shown with optional A/D converter, Compact Flash and RS-485 DIO lines - up to 55 NEW! 2 USB ports SD card option COM ports- up to 10 options include: onboard temperature sensor, A/D Converter 8 channel 12 bit, Extended Temperature, Programmable FPGAs VGA video Battery Backed Real Time Clock, USB Flash 256 M (with ARM Tool Chain), USB WiFi Linux, Real Time extension, NetBSD

Off-the-Shelf Solutions ready to design into 133 MHz 586 your project using DOS development tools Power as low as 800mA $229 qty 100 Fanless, no heat sink

SDRAM - up to 64MB $259 qty 1 COM Ports - up to 4 ports

Ethernet Ports

DIO Channels - up to 40

TS-5600 Shown with optional flash modules, PCMCIA II adaptor A/D, RS-485 and Merlin cellular modem Compact Flash adaptor

options include: USB Ports (Except on TS-5300) RS-485 Half and Full Duplex, A/D Converter up to 8 Channels at 12 bits, DAC up to 2 Channels at 12 bits, Extended Temperature WWW.GiURUMELE.Hi2.ROsee our website for 33 MHz 386 configurations

Over 20 years in business Custom configurations and designs w/ Open Source Vision excellent pricing and turn-around time Never discontinued a product Most products stocked and available Engineers on Tech Support for next day shipping

Design your solution with one of our engineers (480) 837-5200 73.qxp 10/26/2006 11:15 AM Page 1

New Products and PC/104 Peripherals

Tiny WiFi Controller Intelligent Battery Back-up boots Linux in 1.1 seconds $119 200 MHz ARM9 qty 1 Run your system for days $249 with no external power source qty 1 Up to 128MB Flash

Up to 128M SDRAM

802.11g WiFi

SD Flash Card socket

1 external USB port

1 10/100 Ethernet

Rugged aluminum enclosure 3 TTL serial ports measures 1.1” x 4.9” x 3.1”

ZigBee Wireless low power wireless, simple serial interface, range up to 1 mile

33.6K baud, 56K baud, AT commands, caller ID, cellular using Modems GSM and CDMA technologies

Non-volatile Memory up to 2MB, 10 year lithium battery

Serial Ports up to 4 serial ports with optional RS-485, opto-isolated available

8 channel 12-bit A/D converter, optional 2 channel 12-bit DAC, 12 bit A/D, DAC A/D jumpered for 0-2.5V, 0-10V or 0-20mA

Philips SJA1000, opto-isolated, up to 1 megabit/sec CAN Bus Controller selectable termination resistor, Ocera Linux driver

32 inputs, 32 outputs, 200 mA drive, optional 512 Kbyte or 1 MB 64 Digital I/O battery-backed SRAM, stack up to four boards, RoHS compliant

WWW.GiURUMELE.Hi2.ROsee our website for more boards and option details

Technologic SYSTEMS We use our stuff. Visit our TS-7200 powered website at www.embeddedARM.com 2703012eady.qxp 2/5/2007 9:58 AM Page 58

stack firmware, you’ll need to add a accommodate any 5-VDC devices you reviewing the Microchip TCP/IP Stack SPI-driven EEPROM in the form of a may need to incorporate into your Version Log to get the lowdown on Microchip 25LC256. The EEPROM design. what the new version of the TCP/IP can be used to hold web pages. If There are some portions of the stack will do. HTTP is not in your application mix, Microchip TCP/IP stack that require the EEPROM can be used to store you to enter a function block by press- A NEW GENERATION anything you want. ing a button attached to PORTB on Folks who build boats like to name Every device on the PIC18F97J60 the PIC18F97J60. In return, the func- them. I build embedded Ethernet project board is powered by 3.3 VDC. tion block may return a status via the devices and I like to name them as However, since the PIC18F97J60’s RS-232 port or an LED. So, to make well. So, the PIC18F97J60 project inputs are 5-V tolerant and you may sure you can fully use these functions, board from this moment on will be need to use a 5-VDC-powered device, I I added some blinking lights and push known as the “Packet Whacker NG” threw in a dual-voltage power supply to buttons to the design. I recommend (see Photo 2). NG is short for “new generation.” The Packet Whacker NG is very easy to build. You may think that the 100-pin PIC18F97J60 will present an assembly problem. However, with the right soldering tools, you can mount the PIC18F97J60 by hand. If hand sol- dering fine-pitch TQFP parts is not in your job description, an assembled Packet Whacker NG can be had at www.edtp.com. I’ll also kit the Whacker NG for those of you who have the tools to handle the mounting of the PIC18F97J60. Once you see the Packet Whacker NG TCP/IP stack’s activity light blink, you’ll realize that the Packet Whacker NG isn’t compli- cated, it’s embedded. I

Fred Eady ([email protected]) has more Professional Featu res – Exceptional Price than 20 years of experience as a sys- tems engineer. He has worked with computers and communication sys- 34 Channels sampled at 500 MHz tems large and small, simple and complex. His forte is embedded-sys- Sophisticated Multi-levelTMulti-level Triggering tems design and communications. Transitional Sampling //Timi Timing and State RESOURCE Connect this indispensable tool to your PC’s Microchip Technology, Inc., USB 1.1 or 2.0 port and watch it pay for itself within hours! “PIC18F97J60 Family Datasheet,” DS39762A, 2006, ww1.microchip.com 500 MHz Sampling / Timing Mode (Internal clock) Interpreters for I2C, SPI and RS232 /downloads/en/DeviceDoc/39762a.pdf. 200 MHz SamplingWWW.GiURUMELE.Hi2.RO / State Mode (External clock) Integrated 300 MHz Frequency Counter Multi-level Triggering on Edge, Pattern, Event +6V to -6V Adjustable Logic Threshold Count, Group Magnitude/Range, Duration etc. supports virtually all logic families Real-Time Hardware Sample Compression Full version of software free to download SOURCES Qualified (Gated) State Mode Sampling Mictor adapter available Packet Whacker NG www.pcTestInstruments.com EDTP Electronics, Inc. www.edtp.com Visit our website for screenshots, specifications and to download the Microchip TCP/IP Stack, PIC18F97J60 easy-to-use software. family of Ethernet enabled microcon- Intronix Test Instruments, Inc. Tel:(602) 493-0674 Fax:(602) 493-2258 trollers, and MPLAB ICD 2 www.pcTestInstruments.com Microchip Technology, Inc. www.microchip.com

58 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703015Wheat.qxp 2/5/2007 10:06 AM Page 59

FEATURE ARTICLE by Dale Wheat Servo Control First used in remote-controlled airplanes, servo motors are not just built for flight. Dale explains how he used them in custom projects and award-winning robots.

From flying model airplanes to driv- in the more rugged models. Stopping right out of the box and before we ing miniature robots, hobby servo there would leave you with a very useful “improve” it in any way. There are motors have many uses, and they are subassembly, but you’d have to design almost always three wires trailing simple to control with just about any and build your own motor driver circuit- away from the body of the servo. microcontroller. In this article, I’ll ry and some sort of control function. These provide power, the control sig- describe the basics of servo control Let’s all wish really hard and poof! nal input, and a ground line common and give you detailed examples of how A magic chip arrives that does all that to both. We’ve already covered the I have used them in successful com- for us and does it really well. The power requirements, leaving only the mercial designs, custom projects, and chip, an integral part of every hobby control signal to describe in detail. We even award-winning robots. servo, is electrically connected to a will get to that shortly, I promise. Originally designed for actuating potentiometer that is mechanically As shipped, the servo is mechanical- control surfaces on remote-controlled connected to the output shaft and pro- ly constrained to rotate approximately model aircraft, hobby servo motors vides position feedback. This feedback 180° and no further. The normal range have many applications in automation, along with motor back-EMF forms a of operation is typically only 90°. Vari- robotics, and entertainment applica- control system that gives proportional ous attachments to the output shaft, tions. They are available in many sizes, error correction, thereby driving the which are also called “horns,” are nor- from many manufacturers, and they all motor to the desired position. If the mally linked to wire rods and linkages operate in basically the same way. Reli- motor is a little to the left of where it that actuate various control surfaces of ability, low cost, and standardized is supposed to be, the control system model airplanes, steering mechanisms packaging are the driving factors drives it a little bit back to the right of wheeled land vehicles, or even rud- behind their success, and make these until it gets close enough and stops. If ders of model ships. Just a little move servos winning choices for a variety of it is a long way from being correctly this way or that is all that is required. other small motion control projects. aligned, it gives a proportionally Several servos are usually used in con- In May 2003, I made a technical pres- greater push. Now you see why it is junction with multichannel radio units entation for the Dallas Personal Robotics called a servomechanism, servo to accomplish the complete control Group (DPRG) on using low-cost hobby motor, or just “servo,” for short. apparatus. If your motion-control servo motors in robotics. I also presented Most common servos are powered by requirement is for a short, fixed amount the group with a method of “hacking” a small DC voltage, which was tradi- of motion along a curve or a linear them for continuous rotation as drive tionally supplied by rechargeable batter- range, almost any servo can be used as mechanisms. I prepared a detailed “How ies. Almost all servos are designed to is. But continuous rotation can only To” document based on that presenta- operate from 4.8 to 6 V, corresponding to be achieved by physically modifying tion and it has been published online at four- or five-cell NiCd or NiMH battery the servo, which most certainly will www.dprg.org/projects/2003-05a. It goes packs. Some higher-performance exotics void any manufacturer’s warranty. into general detailWWW.GiURUMELE.Hi2.RO about how the servo are happy with higher voltages. The cur- To control the position of the servo- motors work and specifically how to rent draw can be surprisingly high, espe- output shaft, a pulse signal is sent to modify one particular model, the TS-53 cially when a motor is stalled and can the control input line at a regular from Tower Hobbies, for continuous easily exceed one or more amps in very interval. The width of the pulse deter- rotation. Later in this article, I will bad situations. A positive temperature mines the desired position of the shaft. explain more about continuous rotation. coefficient (PTC) thermistor, which is The standard specification is for the also called a “resettable fuse,” in series pulse width to vary between 1 and 2 ms, WHAT’S INSIDE? with the power lead can be a lifesaver with a resulting rotation to the right and There’s much more than you might in an unexpected or extended stall. left, respectively. This range usually rep- suspect inside that small plastic box. resents a 90° arc. Most servos will also There would have to be a motor, natural- THE CONTROL SIGNAL accommodate signals outside this ly, some gears, and maybe some bearings Let’s look at a typical hobby servo, range, up to the mechanical limits of the

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 59 2703015Wheat.qxp 2/5/2007 10:06 AM Page 60

motor (i.e., approximately 180°). A pulse Listing 1—This C code snippet initializes the ATmega8’s Timer/Counter1 for PWM duty using Fast PWM mode width of 1.5 ms should put the output and configures the I/O ports as outputs. Servo output pulse widths can now be indicated using microsecond shaft near the center of its travel. granularity, giving 1,000 steps of positional information in the standard 90° range of motion. The interval between the pulses is tra- DDRD = 1<

COMPUTER CONTROL and could potentially develop a mechan- ified for continuous rotation. Some Generating an appropriate servo ical fault if forced beyond the extremes. vendors, such as Gordon McComb’s control signal with a microcontroller What if you have more servos to Budget Robotics, sell premodified ser- is not difficult. Using more advanced control than available PWM channels? vos for a very reasonable premium. peripheral hardware, such as timers Have no fear. I have a trick or two up The basic alteration involves removing and PWM, makes it trivial. my sleeve for that very situation. Shift a the mechanical connection to the posi- The first example uses an Atmel single digital one through an 8-bit shift tion feedback potentiometer, effective- ATmega8, which is a low-cost part register whose outputs are connected to ly removing the rotational constraint, based on the AVR RISC architecture. as many as eight servos. The shift regis- and either removing the potentiometer Any other AVR with an available 16-bit ter can be in external hardware with from the circuit or calibrating it so that timer will work identically. Initializing only a clock and a data line coming motion correction stops when the null the timer to the proper waveform from the microcontroller, or it can be spot is reached. The null point is mode, which can be either “fast PWM” implemented in software by using a reached when the input control signal’s or “phase and frequency correct hardware output port. A timer interrupt pulse width is exactly 1.5 ms long. PWM,” tells the appropriate output pin begins the sequence based on the servo The servo doesn’t know it has been to “clear on match, reset on overflow,” update frequency. Another timer is pre- snipped and tries to faithfully fulfill and then set the PWM period to 20 ms set for the width of the first servo pulse its duties as best it knows how. This based on the system clock and the and when it expires a pulse is sent to now consists of traveling to the left or timer prescaler used. That sounds like the shift register, shifting the one down the right until the input control signal a lot of work, but it boils down to very through the bits. The next servo’s pulse- jibes with the reported position, as little actual code (see Listing 1). width is programmed into the timer and revealed by the now-disconnected and This works for a system running at the process continues until all eight centered feedback potentiometer. In 8 MHz and provides two channels of positions have been output. This is a some cases this will never happen and PWM signal for controlling two separate much simpler algorithm for multiplex- the servo goes merrily along, spinning servos. To adjust the position of the ser- ing servos than turning them all on at forever, which is exactly what we vos, write to the PWM compare registers once and updating them all simultane- want it to do. To cause the servo to with the desired pulse width in ously. It also mimics the method used cease spinning, we can either send out microseconds and then go do more to transmit up to eight servo positions a control pulse that corresponds with important things. The PWM peripheral over a radio link. I used this method to the null setting of the position feed- hardware will do everything else. No control the two servo drive motors in back potentiometer or simply stop interrupts or further updates are required. my robot, “The Purple Prowler,” which sending pulses. The major difference WWW.GiURUMELE.Hi2.ROwon three awards in the DPRG Robo- between the two techniques is that OCR1A = 1000; //servo A = 1ms, move right rama 2005b: First Place in Quick Trip sending the null position pulse width OCR1B = 2000; //servo B = 2ms, move left and T-Time and Second Place in Line will cause the motor to hold its position Following. The additional servo outputs if deflected, which is a form of braking, This implementation gives position- controlled a gripper mechanism for col- and cessation of control pulses will al granularity of 0.1% or 1,000 steps lecting cans, but it has never been as cause the motor to go limp or coast. within the normal 90° range of motion. successful at that task as fellow DPRG Expanding the range of 1 to 2 ms to 0.5 member David Anderson’s talented THE SERVO TESTER to 2.5 ms will increase the range of robot, SR04. In describing the hacking procedure motion to 180°, or 2,000 steps, given to the DPRG, it occurred to me that the previous example. Note that not all CONTINUOUS ROTATION to properly set the feedback poten- servos can reach these mechanical limits Most, but not all, servos can be mod- tiometer to a useful null position

60 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703015Wheat.qxp 2/5/2007 10:06 AM Page 61

would require an accurate reference signal. I suggested a simple “servo tester” circuit be built using a low- pin-count microcontroller, such as the Atmel ATtiny11, and I offered to make it available to DPRG members. Thus the Servo Tester Mark I was born (see Photo 1). I hand-crafted several of these units using homemade PCBs and I distrib- uted them to the servo hackers in the club. The main feature was a Center button that would reset the microcon- troller to emit a calibrated 1.5-ms pulse. During the modification process and with the victim servo’s insides Figure 1—Using the versatile PWM peripheral subsystem of the ATtiny26, the Servo Tester II provides two chan- hanging out, the feedback potentiome- nels of rock-steady servo control pulses. Each channel can be moved left, right, or back to the center, as well as set ter was adjusted until the motor to Auto Sweep mode. stopped, indicating the precise center of the range. The prototype units also system is shown in Figure 1. The full hacked servos is that the speed of rota- sported Left and Right controls that source code is available on the Cir- tion is directly, if not linearly, propor- moved the servo in each direction. cuit Cellar FTP site. Assembled and tional to the variance of the control These would let the user test the oper- tested versions are available from signal from the center null position. If ation of both hacked and unmodified several retailers. a properly calibrated hacked servo is servos. The ATtiny11 has a timer One nice feature of the Servo Tester II given a series of pulses of exactly 1.5 ms, peripheral but lacks a PWM subsys- is the Auto Sweep mode, where the it doesn’t move and resists strenuous- tem, so the output pulses were gener- servo is exercised back and forth con- ly if forced off its mark. Should the ated in code and not exactly certifica- tinuously. Jumpers enable operation in pulse width widen ever so slightly, the tion-lab quality. normal and extended range of motion output shaft will begin to rotate slow- modes. The Center button survives ly in a counter-clockwise direction, as THE SERVO TESTER II from its predecessor and performs the seen from the face of the motor. Cor- The Mark I became popular enough same function. respondingly, a narrower pulse width to deserve a second thinking about The ATtiny26 does not have the 16-bit will cause the shaft to begin to rotate and this lead me to develop the artful- timer resolution available to the clockwise. The farther from the mid- ly named Servo Tester II (see Photo 2). ATmega8, which was used in the pre- dle position it gets, the faster the out- As its name might suggest, it had two vious example’s code. It turns out that put shaft will rotate, up to a point of just about everything. the humble 8-bit timer is perfectly about a quarter of the way from each I based the system on the Atmel capable of putting out precise and limit, where full speed is achieved. ATtiny26, a 20-pin AVR microcon- rock-steady servo control pulses, albeit This varies nonlinearly with different troller with a versatile PWM subsys- at a lower granularity. Since the update models of servos. Without some sort tem. Since two channels of PWM out- interval period is reduced from 20,000 of velocity feedback, however, it is puts were available, two distinct servo to 256 counts, a corresponding increase impossible to determine or predict the channels were included. Each had two in step size is realized. The total range exact speed. connectors, so that a total of four ser- of possible positions declines from vos could be attached at once. I don’t 1,000 in normal range to 17. This is ROBO SERVO know if anyone besides me has ever plenty for the Servo Tester II. Servos have many uses in robotics, found a use for WWW.GiURUMELE.Hi2.ROthe “four-servo” con- which is one of my areas of interest. figuration, but it’s there if anyone SPEED CONTROL Unmodified servos are excellent for ever thinks of a good application. The One interesting characteristic of moving arms and actuating grippers, while continuous rotation servos are perfect for small robot drive wheels. Listing 2—This is a very short but complete PBASIC program for the BASIC Stamp BS2 that drives a two- wheeled robot in a forward direction. Variations in motor characteristics, wheel diameter, and battery voltage Even a robot of little intelligence can will conspire against linear perfection. drive around quite elegantly using servos. I put this to the test in the fall of main: PAUSE 16 2006, while preparing an entry for the PULSOUT 15, 250 ‘ left wheel counter-clockwise (< 1 ms) PULSOUT 14, 1500 ‘ right wheel clockwise (> 2 ms) DPRG Roborama 2006b, a series of GOTO main robotics contests held at the Museum of Nature and Science in Dallas,Texas.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 61 2703015Wheat.qxp 2/5/2007 10:06 AM Page 62

Value Pulse length Resulting motion ing a Velocity Equals Zero command, you a long pulse for counterclockwise 1 Short (< 1 ms) Clockwise will find that on a flat surface, the effect motion. The short pulse can be ridicu- 0 None Stop is decidedly similar. So you have a veloci- lously short, as it need only be long –1 Long (> 2 ms) Counterclockwise ty setting of zero for both the left and the enough to trigger the internal one-shot right motors to accomplish the goal of timer within the servo circuitry. Tog- Table 1—Simple motion control for driving small robots can be implemented using these values to represent not going anywhere. Next, you consider gle an output line high and then forward, reverse, and stop. Servos can accept control all the other possibilities, most of immediately low again and you’ve signals that are significantly outside their normal opera- which involve detectable motion on the completed the task. The long pulse is tional range. This characteristic makes it very easy to part of the robot. similarly crude but must not last over- control them using almost any microcontroller. To go forward, it would seem the long—“over” being defined in terms of thing to do would be to make the wheels nearing the expiration time of the con- Using only donated parts from various roll forward and the robot should follow. trol signal repetition rate. Anything DPRG supporters (including Jon What you have to remember is that due over 2 ms and less than around 10 ms Williams formerly of Parallax and now to the orientation of the drive wheels will suffice. These values, along with EFX-TEK, Mike Dodson of Modern and the location of the servos with stop, are summarized in Table 1. Assemblies, and others), I put together a respect to the wheels, the two control A complete, if brief, PBASIC program theoretically simple robot. I used a pro- signals must be exactly out of phase to for the Parallax BS2 that will drive a totype Parallax robot chassis, the vener- produce forward motion. Some roboti- two-wheeled robot forward in a mostly able Board of Education sporting a vin- cists would solve this “problem” by sim- straight line is presented in Listing 2. tage BS2-IC, some bumper switches, and ply reversing the sign of the velocity on This example assumes the left servo a line sensor of my own devising. I orig- one wheel; or worse yet, some would motor is controlled by P15 and the inally wanted to prove some mathemat- swap the wires on one of the motors and right by P14. These happen to be the ical concepts concerning navigation be done with it. I find that it makes lines I chose for the DPRG Yellow using differentially configured drive sys- more sense mathematically to treat Robot because they were conveniently tems, but I got caught up in the com- them as 180° out of phase with respect brought out to servo headers on the petitive whirlwind that happens before to each other. For example, to move for- Board of Education. The magic numbers every big robot contest at the DPRG. ward, the left wheel must rotate count- in the PULSOUT command are derived Now that the trophies are on the er-clockwise, while the right wheel must from the peculiar granularity of the BS2- mantle (yes, the humble DPRG Yel- rotate in a clockwise direction. Do the specific PBASIC interpreter, resulting in low Robot placed in three of the four opposite, of course, to go backwards. If 0.5- and 3 ms-pulses, respectively. The competitions in which it competed), I both wheels are spinning clockwise, the constant 16 in the PAUSE command is can reveal some of the surprisingly robot spins in place to the left or coun- the remainder of the time that needs to simple techniques used to run the ser- terclockwise if viewed from above. be eaten up in the update interval after vos with no sophisticated timing capa- the pulses have been emitted and a lit- bilities available whatsoever. A SIMPLE SOLUTION tle more for program execution. Your This implies that each motor must homework is to figure out how to drive KEEP IT SIMPLE be able to be directed to spin in either in reverse, with extra credit for discov- First, let’s greatly oversimplify the a clockwise or a counterclockwise ering the secret of spinning in place. requirements. I find it always helps to manner. This is mechanically possible implement expectation-management with servos, and it turns out to be TRICKERY practices early on in a project. Keep easy to do with even the most simplis- One side effect of the simple drive- those expectations down there—way tic of microcontrollers. Forget preci- forward code previously listed is that down. Now for the most part, you can sion timing pulses. All you need is a both motors are triggered at almost the assume that the robot is either moving short pulse for clockwise motion and same time. By staggering the triggering or not. If it is moving, it is going straight ahead, backwards, or spinning left or right in place.WWW.GiURUMELE.Hi2.RO This requires Listing 3—This C loop is a complete FreeRTOS task that generates a forward-reverse-stop control signal for a three speeds for each of the two servo without using any special timers or PWM hardware. The value of the servo_speed global variable is motors: full forward, full reverse, and used to determine the direction (see Table 1). a complete stop. There are logically for(;;) { nine possible combinations, four of if(servo_speed) { which involve pivoting on one wheel. PORTC = 1; // start servo pulse Starting with the simplest option, the if(servo_speed < 0) vTaskDelay(mainSERVO_LONG_PERIOD); // extend it by 2 ms famous play dead trick, recall that a servo PORTC = 0; // end servo pulse will stop doing anything if you cease to } provide control pulses. By not emitting vTaskDelay(mainSERVO_UPDATE_PERIOD); any sort of signal, you are telling the } servo to stop. While not exactly mandat-

62 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703015Wheat.qxp 2/5/2007 10:06 AM Page 63

either of the bump switches detects a “AVR_ATMega323_WinAVR” example wall collision, then rotating left in place provided in the FreeRTOS download. for a fixed period of time, and finally The first task merely toggles a flag resuming the forward arc to the right. back and forth every 2 s for testing pur- This works three out of four times poses. The second task outputs a long, but gets hung up on the outside cor- short, or no pulse depending on the ners from time to time. To arc to the current state of the flag (see Table 1). Photo 1—The Servo Tester Mark I was a simple design right, the left motor goes forward at Each task is implemented as a con- to provide a calibration signal for modifying servos for full tilt and the right motor goes for- tinuous loop and has no knowledge of continuous rotation. It can also be used to test unmodified ward at approximately half speed. the operation of any other task, except servos for proper operation. I built several units until it became apparent that a more versatile and accurate ver- Have a look at the source code and try for the value of the global variable sion would be required. to figure out how the other contests servo_speed. FreeRTOS supports fared. There are some obvious and of the motors, the peak power draw can some not-so-obvious improvements be theoretically cut in half. This is a that can be made. I usually think of big deal for battery-powered robots, these on my way home from the con- especially on game day. This was test, of course. The complete PBASIC accomplished by implementing a state code that was actually used during the machine that kept track of which competition is available for download. side’s turn it was to trigger and run- ning the loop at twice the normal fre- MORE COMPLEX SOLUTIONS quency. I then added another layer of The same long, short, no-pulse algo- trickery by omitting every other con- rithm for servo control can also be easily trol pulse to achieve half-speed opera- implemented in more sophisticated sys- Photo 2—The Servo Tester II added a second servo tion. This was required in my solution tems, using multithreading techniques. I channel and an “auto sweep” function. This device is available assembled and tested. Figure 1 and the full to one of the contest challenges: wall used Richard Barry’s FreeRTOS real-time source code are available for download if you’d rather following. The robot proceeds by arc- kernel to create two independent tasks build your own, which will allow you to add or change the ing forward and to the right, until on an Atmel ATmega32 based on the functionality to suit your needs.

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 63 2703015Wheat.qxp 2/5/2007 10:06 AM Page 64

more elegant forms of inter-process smiling faces on the next crop of mowing two acres of grass and in the communication (IPC), but I just want- robots! Even a little block that runs winter enjoys not mowing it. In 2005 ed a simple example. The servo update around and bumps into things all day and 2006, Dale was the president of task is composed entirely of an end- long is more interesting than some- the Dallas Personal Robotics Group less loop (see Listing 3). thing that sits on the bench and dis- (http://dprg.org), one of the nation’s Bit zero of port C is the servo out- plays π to a bazillion digits. Weld oldest personal robotics interest groups. put, having been previously initialized some wheels to the bottom of your PC as an output at some point not illus- and see what happens. How about a PROJECT FILES trated. The mainSERVO_LONG_PERIOD truly “mobile” phone? I’d love to hear and mainSERVO_UPDATE_PERIOD about your servo-based projects. I hope To download the code, go to ftp://ftp. constants are defined as 2 and 20, this little introduction helps get your circuitcellar.com/pub/Circuit_Cellar/ respectively. While this works and projects moving. Drop me a line if you 2007/200. illustrates the latitude available with have any questions or comments, and the servo update period, a more robust thanks for reading this far! I RESOURCES implementation would adjust the D. P. Anderson, “My Robots,” 2006, update period, depending on the Author’s note: Assembled versions of www.geology.smu.edu/~dpa-www/ length of the output pulse, to keep the the Servo Tester II are available from myrobots.html. overall update interval constant. Note BG Micro (www.bgmicro.com) and that this works well enough for full E-Clec-Tech (www.e-clec-tech.com). R. Barry, “FreeRTOS,” 2006, forward and reverse on modified ser- www.freertos.org . vos, but it lacks the resolution and Dale Wheat ([email protected]) is Dallas Personal Robotics Group, repeatability needed for positional sta- an old-fashioned tinkerer, inventor, http://dprg.org. bility with standard servos. musician, philosopher, and student of the human condition. He has no for- GO ANIMATE mal professional education. He enjoys SOURCE Now you have several methods at reading science fiction short stories ATmega8/32 and ATtiny11/26 your disposal for animating your proj- and playing a variety of musical Atmel Corp. ects. Let’s see some waving hands and instruments. In the summer, he enjoys www.atmel.com

WWW.GiURUMELE.Hi2.RO

64 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 12/4/2006 11:56 AM Page 1

WWW.GiURUMELE.Hi2.RO 66.qxp 1/30/2007 1:51 PM Page 1 CC_U128_printer.pdf 1.29.07 14.10.34

Y

WWW.GiURUMELE.Hi2.RO 2703013Martin.qxp 2/5/2007 1:41 PM Page 67

LESSONS FROM THE TRENCHES by George Martin More “Hello World” Moving What You’ve Learned to the Hardware As promised, George continues showing you how to use C language for embedded system design. This time he delivers cleaner code, more functional requirements, and interrupts.

Last time, I started exploring how to bilities. Typically, when an interrupt ware (more expensive), while other use the C programming language for occurs, normal program execution stops versions will only have software rou- embedded system design (“Hello after the completion of an instruction, tines for multiply (slower, but cheap- World … Want Cookie,” Circuit Cel- and the address of the next instruction er). The code for both looks the same. lar 198, 2007). I created a program that is saved. The status of the CPU is also When a multiply instruction is turns on light on when an input saved (typically on a stack), and then encountered, it’s either executed in switch is pressed and turns it off when program control is also transferred hardware or a software exception it’s released. It used no interrupts, just through a memory location known as (interrupt), or it is generated and the brute force. I also promised a cleaner, an interrupt vector or an interrupt vec- multiply is carried out in software. faster version. Well, this month I’d like tor table. The address of the interrupt The next level of detail necessary to to add more functional requirements, routine is fetched using the table entry understand interrupts is that when an introduce interrupts, and implement that is assigned to the interrupt that interrupt occurs, the address of the all of this on a real CPU. Oh yes, I’ll just occurred. Interrupt processing is next instruction is saved on the stack, also clean up that code as promised. If started at the location pointed to by the CPU flag resister is also saved, and you’re new to C, I recommend that you that vector. Interrupt processing typically the IE flag is cleared. So you start with that previous article. continues until a return from interrupt the user can execute the interrupt-rou- Using the C language, we covered instruction is encountered, and finally tine code. When interrupt processing declaring variables, sizing variables, pro- the status of the CPU is restored and is complete, you execute a return cedures, #defines, pointers, if-else normal program execution continues from interrupt (RETI) instruction. The statements, true and false, bitwise logic from the program instruction whose flags are restored and that saved next operations, and for(;;) loops. Also, I location was saved on the stack. instruction is executed. Any of the recommended B. Kernighan and D. That’s the two-cent version of inter- shared processor (or system) resources Ritchie’s The C Programming Language rupts. There are a few more details (actu- that you touch during interrupt pro- as your first language reference. We ally many more) that we’ll get into in cessing must be saved and restored. A ended that article with a program that future articles. There are several types of typical shared resource you are likely operates a light whose output state is nonmaskable interrupts (NMIs), hard- to use is a CPU register. If you write derived from a switch input. ware, and software. NMIs are just that. the interrupt code in C, then the lan- They can’t be ignored or masked. Hard- guage and the compiler will know REAL TIME ware interrupts can have several which registers were used and Before we get to real hardware, let’s sources and they each typically have a save/restore them for you. If you write add a real-time requirement. Say out- priority level. Higher priority interrupt the interrupt in assembly language, put light one is to blink at a slow rate routines can interrupt lower priority then you’re on your own. when no switchWWW.GiURUMELE.Hi2.RO is pressed and at a interrupt routines. There is also an If you get an interrupt and would fast rate when any of the switches are interrupt enable (IE) flag in one of the like other interrupts to interrupt your pressed. How many switches are CPU’s registers. Once this flag is set, work then just reenable the IE flag. Or there? Marketing will get back to us all interrupts are active. If this flag is you can use the priority mechanism on that issue, but the completion date cleared, only the NMI is active. Soft- built into the processor and let the for this project can’t slip. ware interrupts are just that, generated hardware sort it all out. The class of processors we’re dealing by a software instruction. These are My model for working with inter- with has some sort of timer/counter useful for debugging or implementing rupts is to think of the interrupt rou- hardware. Perhaps only one or several. features in software if no hardware sup- tine as a separate entity. Anything it Timers and interrupts go hand in hand port is provided. The multiply instruc- needs, such as variables, cannot be shared with our real-time requirements. tion is a good example. Some versions with the noninterrupt portion of the code These CPUs also have interrupt capa- of the CPU will have dedicated hard- and vice versa. At first, it seems like a

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 67 2703013Martin.qxp 2/5/2007 1:41 PM Page 68

major restriction, but as you will see, Listing 1—This routine reads the ADC, restarts the ADC, and manages the timers. it’s the safest way to get really stable operation out of a complicated system. //**************************************[ interrupt ]**** ( 1) // ( 2) REAL MICRO // Timer interrupt service routine ( 3) Well, it’s time to get into a real // ( 4) micro. Let’s start with the Texas // This should be at a 3640 Hz rate = 0.274725274 usec ( 5) Instruments MSP430. That’s a family // ( 6) //******************************************************* ( 7) of low-power (really low) 16-bit __interrupt void TimerISR(void) { ( 8) microcontrollers. I’ll let you search ( 9) on Texas Instruments’s web site for inpt = ADC10MEM; // Read & restart the A/D (10) the MSP430 and get showered with // another conversion (11) information. The project I’m going to (12) use to describe my code uses a part MSec10Timer++; // Increment a counter (13) in the MSP430x11x2 family. Search if (MSec10Timer > MSEC10_TIMER) { // 10 ms (14) the site for the datasheet if you want MSec10Timer = 0; (15) all the details, but you won’t need timer2++; (16) them for a bit. You will also find that StateTimer++; // inc the State Timer (17) manufacturers have a range of offer- } (18) (19) ings and alter the content and pin } // end of __interrupt void TimerISR(void) { (20) count to match up to specific user requirements. Let’s start by looking at code exam- ples for an interrupt that I’m using in are incremented. The details of this modern CPU, it’s the only way. Some a digital filtering project. Listing 1 is timing are explained a little later. of the constants are defined for the the timer/interrupt code. The keyword The next thing you need to do is particular CPU and some of the con- __interrupt (double underscores) insert the location of this interrupt stants I defined. The code fragment in defines the procedure voidTimerISR routine into the interrupt vector table. Listing 4 is at the beginning of each (void) as an interrupt routine to the Listing 2 is the code fragment for that file that referenced these defines. compiler. I’m using the IAR compiler table. This is from an assembly lan- The C header file is a file that is and we’ll talk more about that later. guage routine. Hey, wait a minute. included right where it’s found in the Just 20 lines of C code and that’s it for Isn’t this all about using C and not C source file. It’s just as if you cut and the interrupt routine. The variable assembly language? Yes it is, and for pasted the header file into the source input is defined as an INT16 (16-bit those with at least brown belts in C, file. These header files contain infor- integer) and is read each time this rou- Dan Saks wrote about how to do inter- mation that you want to make avail- tine is executed. The A/D converter is rupt vectors in C.[1] Since we are just able to the source file. By including set up to automatically start another getting our feet wet in the shallow statements that have a header file sur- conversion each time it’s read. I use end, it’s easier to use the assembly rounded by “” characters, the search the ADC input for digital filters that I language table. The original code had path begins where the source program won’t cover in this article. The all unused vectors pointing to RESET. is found.[2] If the header file name is Msec10Timer, timer2, and StateTimer This is a good solution for production, enclosed with <>, the search follows variables are also 16-bit integer enti- but I wanted to trap any unexpected implementation-defined rules. Line 1 ties. The constant MSEC10_TIMER will interrupts while testing. So, I changed in Listing 4 includes a header file be explained shortly. The C operator them to point to a routine that just defining all the CPU register and bit ++ in this listing, simply increments loops on itself. This way I know I have constants. While line 2 includes a file the variable one count. Look for more a problem with a particular interrupt named CCconsts.h (Circuit Cellar on this operationWWW.GiURUMELE.Hi2.RO in later articles. source. It is also better than just get- constants), that file contains all the Every time this routine is executed, ting reset and then trying to figure out constants and definitions for this par- the Msec10Timer variable is incre- why. The last point we need to cover ticular project. mented. When that value is greater is setting up the timer. Listing 3 contains a lot of informa- than some constant, the value is Listing 3’s routine sets up all the tion; let’s look at it in more detail. reset and other variables are incre- hardware used in this system. The Line 1 is a comment line. Line 6 is the mented. When the Msec10Timer variables that appear in all caps are procedure declaration. Line 8 stops the variable is greater than the constant defined (constants). Now do you see 430’s watchdog timer. The watchdog MSEC10_TIMER, that means that why we adopted that convention? You timer is an interrupt source that’s sup- approximately 10 ms in real time have know to look elsewhere for their posed to monitor your program’s oper- transpired. So the Msec10Timer vari- meaning. And when we’re dealing ation, and if it’s not reset every so able is reset to zero and other timers with all the registers and bits in a often, it will generate an interrupt

68 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703013Martin.qxp 2/5/2007 1:41 PM Page 69

warning you that your program is out count 10-ms intervals so the constant of control. Lines 10 through 12 set the MSEC10_TIMER is defined as 35. So: internal oscillator to run as fast as ⎛ 32, 768 Hz ⎞ possible (DCOCTL, DCO Clock Fre- ⎜ ⎟ ⎝ 9 ⎠ 3,. 640 88 quency Control and BCSCTRL1, Basic = = 104. 025 Hz Clock System Control). Lines 14 35 35 through 18 define the pins as either Thus, lines 15 to 17 in Listing 1 inputs or outputs and set some initial advance every 104 times per second, output values. Lines 21 to 27 set up the or 9.61 ms. Could I have come closer ADC. And lines 30 to 35 set up the to 10 ms? Sure 32,768 Hz/328 is only timer. All of that is done in C, and you off by 98 µs. But as I said, I needed must admit it’s not that far away from 3,640.88 for the digital filters I was an assembly language implementation. running and the blinking of our lights Note, for the MSP430, PnSEL can be approximate. The point is that selects whether the pin is a normal you have some flexibility in how you I/O pin or dedicated to a special func- structure what goes on inside a timer. tion, PnDIR sets the pin’s direction as either in or out, and PnOUT sets the MOVING ALONG output value of the pin. Well, learning is an action sport. Let’s spend a little more time look- Enough sitting around, let’s install a ing at the timer. The 32,768-kHz crys- compiler and get to it. I’m going to tal goes into the timer input. Line 30 keep with the Texas Instruments divides that crystal input by nine. So MSP430 family. If you’ve got another, 32,768/9 = 3,640.88 Hz, or 0.2746 ms, go ahead and use that one. The details for every interrupt. I needed that fre- of I/O system peripheral control will be quency for the original design this different, but that’s the point of using code was copied from. I would like to C. It should be easy to move designs

Listing 2 —The Trap9n(n) labels will trap the CPU operation on any unexpected interrupts.

Trap1 (1) jmp Trap1 (2) Trap2 (3) jmp Trap2 (4)

—- all vectors have a Trap location but are omitted here —- (5)

Trap15 (6) jmp Trap15 (7) (8) ;———————————————————————————————————- (9) RSEG INTVEC ; MSP430x11x1 interrupt vectors (10) ;———————————————————————————————————- (11) DW Trap1 ;RESET ;1 no source (12) DW Trap2 ;RESET ;2 no source (13) DW Trap3 ;RESET ;3 no source (14) DW Trap4WWW.GiURUMELE.Hi2.RO ;RESET ;4 no source (15) DW Trap5 ;RESET ;5 no source (16) DW Trap6 ;RESET ;6 A2D_ (17) DW Trap7 ;RESET ;7 no source (18) DW Trap8 ;RESET ;8 no source (19) DW Trap9 ;RESET ;9 was Timer-AX (20) DW TimerISR ;10 Timer-A0 (21) DW Trap11 ;RESET ;11 was Watchdog/Timer (22) DW Trap12 ;RESET ;12 was Comparator-A (23) DW Trap13 ;RESET ;13 no source (24) DW Trap14 ;RESET ;14 no source (25) DW Trap15 ;RESET ;15 was NMI, Osc. fault (26)

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 69 2703013Martin.qxp 2/5/2007 1:41 PM Page 70

among different processors. On TI’s D: is the drive containing your data files, you should be placed in the IDE with web site, under Get Design Support, CircuitCellar is the customer, LearningC the main.c file opened. From the tool enter Microcontrollers and Selection is the product group, MyFirstProduct is bar, select Project/Rebuild All. Con- and Solution Guide. Then press Go. the product, and Latest is the latest gratulations you have just compiled This gets you to the TMS430 technical version of the design. This may seem a your first C program. You now have a documents. You’ll also see TMS470 bit cumbersome, but as your projects working IDE that will compile C, assem- and DSP products. Don’t go there! Seri- and designs grow, you might find your- ble, link, and locate all for just some ously, there is just too much informa- self thankful for this detailed structure. download time. I know this was a lot to tion available. Stick with the TMS430 I’ve also found that it is difficult to point follow and I bet you won’t get the direc- for this installment. You will find the IDEs to different versions of the proj- tory structure to your liking on the first selection guides, code examples, and ect. So, I will copy the contents of Latest try. So work with it and get comfortable. development tools. Take some time to into V00-01, V00-02, and so on as I keep Now, under Project/Options in the look through the information. I’m changing the code. main tool bar, you can set up the tools to going to stick with one of the smaller, When everything is installed, start suit your needs. Some of what I do on less expensive versions of the TMS430. the IAR workbench and select “Create small projects is as follows: Under Gen- The header file is msp430x11x2.h a new project in current workspace.” eral-Target, I select the correct Target and the key document is the Then select C and main. Notice the CPU (msp430F122). Under C Compiler- “MSP430x1xx Family Users Guide,” explanations as you make the choices. Language, I allow IAR extensions. Under which gives a technical description of Then, name your latest project and C Compiler-Code, I do not allow opti- the microcontroller (actually, several in this subset of the TMS430 family). Listing 3—Configuring the Texas Instruments MSP430 hardware that we will use in our system. You’ll see details about all the avail- able peripherals, along with the //*********************************************[ public ]**** (1) instruction set. Now, if everything // (2) goes well, you will never have to look // Hardware Setup (3) at the instruction set sections again. // (4) Actually, I look at them while I’m get- //*********************************************************** (5) ting to know the CPU. The C compil- void SetupHardware(void) { (6) er can output the C source lines mixed (7) with the assembly language code that WDTCTL = WDTPW+WDTHOLD; // Stop the watchdog (8) was generated. I keep an eye on this to (9) DCOCTL |= DCO2+DCO1+DCO0; // set DCO to run (10) make sure the code does not get bloated. // at fastest setting (11) Next, look up Compilers/Assem- BCSCTL1 |= RSEL2+RSEL1+RSEL0; // XT2=ON (12) blers/Linkers under development tools. (13) You will see that Texas Instruments and P1SEL &= ~(BIT3+BIT2+BIT1+BIT0);// These PINS are Digital I/O (14) IAR offer free (code limited) C compil- P1DIR |= (BIT3+BIT2+BIT1+BIT0); // These PINS are outputs (15) ers. I’m going to talk about the IAR P1OUT |= (BIT3+BIT2+BIT1+BIT0); // Set outputs to 1 (16) because that’s the one I use. Look up P2SEL &= ~(BIT4+BIT3+BIT2+BIT1);// These PINS are Digital I/O (17) www.iar.com and then C compilers. Fol- P2DIR &= (BIT4+BIT3+BIT2+BIT1); // These PINS are inputs (18) low the links to IAR Embedded Work- (19) bench version x.xx for the Texas Instru- (20) ments MSP430. You’ll find a link to the ADC10AE = 1; // Analog input A0 enabled P2.0 (21) ADC10CTL1 = ADC10DF; // Select ADC out data format as (22) 4-KB Kick Start edition. You will need to // signed left justified (23) register with IAR and then you’ll come ADC10CTL0 = ADC10SHT_1 + ADC10ON; (24) across a download page. Download the // ADC10 ON and mode set (25) compiler, install, and enter the keys as (26) directed in the instructions.WWW.GiURUMELE.Hi2.RO Ta-da! ADC10CTL0 |= ENC; // Enable conversions (27) Most of the modern IDEs have a (28) project structure that they want you // Set up Timer A (29) to follow. I use several and never take CCR0 = 8; // CCR0 for sampling rate of 3640Hz (30) the time to quite figure out how to // from 32768Hz ACLK signal (31) finesse my preferences on the IDE’s // (32768/9 = 3640) (32) directory structure. So, I just get it (33) CCTL0 |= CCIE; // enable CCR0 interrupt (34) sort of close to what I want for a proj- TACTL = TASSEL0+MC0; // TACLK = ACLK, Count up to CCR0 (35) ect structure and move on. (36) Let’s try a directory structure some- } // end of void SetupHardware(void) (37) thing like this: D:/CircuitCellar/ LearningC/MyFirstProject/Latest, where

70 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703013Martin.qxp 2/5/2007 1:41 PM Page 71

Listing 4—The Msp430x112.h file is from TI, while CCconsts.h is one that I created for this design.

#include (1) #include “CCconsts.h” (2)

mizations. Under C Compiler-Output, I own and co-founded a design and click to generate debug information. For manufacturing firm (www.embedded- C Compiler-List-Output, I list file-assem- designer.com). George’s designs typi- bler mnemonics. These are probably the cally include servo-motion control, default settings, but you should under- graphical input and output, data stand what options are available. acquisition, and remote control sys- Let’s talk a little about style. I prefer tems. George is a charter member of to convert the tab character to spaces the Ciarcia Design Works Team. He’s lined up every three. Whenever there currently working on a mobile com- is a {} pair, I put the first one (opening) munications system that announces on the line that started it all, and the highway information. George is a last one (closing) on it’s own line. Look nationally ranked revolver shooter. at Listing 1, lines 14 and 18. And the last style issue for now is in a proce- dure. I do the {} as just mentioned, but PROJECT FILES I do not indent the first line of code. To download code, go to ftp://ftp. Look at Listing 1, lines 8 and 20. I feel circuitcellar.com/pub/Circuit_Cellar this style gives me good visual spacing /2007/200. for indentation and brackets but keeps the code compact. We’ll get into format- REFERENCES ted source print utilities, and these style [1] D. Saks, “Modeling Interrupt Vec- choices go well with those utilities. tors,” Embedded Systems Design, ASSIGNMENT 2006, www.embedded.com/ showArticle.jhtml?arti- Your assignment is to enter the code cleID=192503651. that I’ve described in these first two articles and compile it. Chase down [2] B. Kernighan and D. Ritchie, The C the errors until you get a clean com- Programming Language, Second pile. Look at the code generated. Are Edition, Section 4.11.1, Prentice you surprised at anything? Next time, Hall, 1988. we’ll look deeper into the compiler and fire up another IDE. RESOURCES If you want to run any of your code on real hardware, all the manufactures and S. Harbison and G. Steele Jr., “C a other suppliers offer low-cost (less than Reference Manual,” Prentice Hall, $100) evaluation boards. Check out the 1995. offerings on the Texas Instruments web P.J. Plauger, “The Standard C Library,” site for examples of what’s available. Prentice Hall, 1991. Also, the IAR environment includes a simulator. So, even if you didn’t buy Texas Instruments, Inc., “MSP430 any target hardware,WWW.GiURUMELE.Hi2.RO you could still Microcontroller Datasheet,” step through all the C code and SLAS439C, 2006, http://focus.ti.com/ observe its operation. lit/ds/symlink/msp430f2131.pdf. As usual, I’ll be happy to address any ———, “MSP430x1xx Family Users of your questions on the Circuit Cellar Guide,” 2006, http://focus.ti.com/lit/ bulletin board (http://bbs.circuitcellar. ug/slau049f/slau049f.pdf. com/phpBB2/). I

George Martin (gmartin@circuitcellar. SOURCE com) began his career in the aero- MSP430 Microcontroller space industry in 1969. After five Texas Instruments, Inc. years at a real job, he set out on his www.ti.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 71 2703021nisley.qxp 2/5/2007 1:42 PM Page 72

ISSUE 200 SPECIAL FEATURE by Ed Nisley

A Plethora of Projects Since 1988, Ed has written more than 120 articles for Circuit Cellar on everything from home control to programming. In this article, he covers his all-time favorite projects.

My wife, a budding author, per- shelf struts. The compressed air tank first serious water rocket, it may have suaded me to join her in a “Write, and enthusiastic bystanders don’t sported the first launchpad instrumenta- Write, and Rewrite” class for aspiring appear in the picture, but they were tion. I found 2-liter bottles accelerated at essay writers. When discussion turned definitely present. about 400 G and departed the gantry at to the difficulties of finishing an essay Blasting bottles into treetops wasn’t nearly 250 ft/sec. That’s 170 MPH, or and sending it off for publication, per- enough for the Circuit Cellar crew, 275 km/h for you metric folks. Not haps I wasn’t sympathetic enough though, because we wanted numbers. bad for a bottle of air, eh? when I quoted Dr. Samuel Johnson: You’ll see that attention to detail in A followup in Issue 4 (1988) described “The gallows doth wonderfully con- every issue: not only do you get con- a better launcher and you can find centrate the mind.” struction information, but perform- improvements on the web today after Although Circuit Cellar’s editors ance measurements and background two decades of innovation. Oh, by the don’t threaten me with the gallows very to show why the information’s rele- way, don’t believe any of the slanderous often, producing a regular technical col- vant in the real world. stuff Steve wrote; it’s mostly all true. umn does concentrate one’s mind on The bookshelf struts supported thin getting the job done. All in all, though, wires that the rocket dislodged in FIRMWARE AND HARDWARE when they’re happy, I’m happy! passing. A real IBM PC recorded the “Firmware Furnace,” my first col- Perusing the master Table of Con- elapsed times through its parallel umn series, explored the low-level tents on the Circuit Cellar web site printer port, using a reprogrammed interface where software meets silicon. shows that I’ve written 120-some-odd hardware timer. In those days, of The now-classic Intel 8051 Microcon- columns and articles for the last 200 course, we told you how to modify a troller figured prominently in early issues, covering everything from home printer port to enable data input. columns, with applications ranging control to protected-mode program- Although this wasn’t the world’s from simple LCDs, to power-line com- ming to RF circuitry. munication, to digital Here’s a look at some of video, with a DIY in- my all-time favorite circuit debugger thrown projects. in for good measure. Capturing and dis- WATER BOTTLE playing analog video ROCKETRY with an 8051 microcon- Steve presented the troller wasn’t easy, but Circuit Cellar Strategic some precise firmware Defense InitiativeWWW.GiURUMELE.Hi2.RO in and a handful of cheap Issue 2, based on a gadg- external parts did the et from my machine trick. I think I was the shop that was so much first to explain why the fun I still get an occa- usual software-inten- sional e-mail about it. sive approach produced Photo 1 shows a launch- unacceptable jitter and er that fired 2-liter soda show how to reduce it. bottles out of sight: My column in Issue 3 some bicycle brake com- (1988) certainly raised Photo 1—Combine some bike parts with a soda bottle, add some parallel-port electronics, stir in a ponents, a few brazed bit of firmware, and we had the single most popular project ever: The Circuit Cellar Strategic some hackles with fittings, and three book- Defense Initiative. Two hundred issues later, we still get e-mails! tightly interlocked

72 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703021nisley.qxp 2/5/2007 1:43 PM Page 73

PCI Express interconnects, the ISA bus was eminently hackable, primarily due to its relatively low speed, and I showed how the bus control and timing signals interacted with external hardware. From the beginning, Intel’s 80x86 addressing was widely regarded as baroque and protected-mode program- ming wasn’t well-understood, so in Issue 48 (1994), I began my “A Journey to the Protected Land” series that built up a Photo 2—An ISA-bus board stuffed with everything from a serial number to a non-LSI graphic LCD interface lets us miniature multitasking kernel while explore hardware design, bus and BIOS interfacing, and firmware control. Trivia quiz: What happened when you examining some obscure PC hardware pushed that gray button? features. To put this in perspective, in those days the Linux kernel was at 1.1. mainline and interrupt handler code, traced instruction timing down Unlike Linux, however, my code because the handler didn’t save any through interrupts, past DRAM refresh used Intel’s full-throttle segmentation registers at all! and into the CPU’s prefetch queue. model, with privilege rings, memory Although PCs weren’t yet cheap In Issue 31 (1993), I began exploring protection, and task isolation. I even enough or reliable enough for real the intricacies of the ISA bus used in included a simple Virtual-86 mode embedded use, that trend was becom- IBM PC-compatible systems, starting “DOS Box” that could execute real- ing clear, even when an Intel 33-MHz with a bare expansion board and cul- mode code. It wasn’t a full operating 80386SX microprocessor was a fast minating in a large bitmapped graphic system, but it did lay out the funda- CPU. In Issue 11 (1989), I looked at LCD by Issue 46 (1994). Photo 2 shows mentals at the hardware level. how cache misses (in the few CPUs the resulting board, built entirely with Starting with Issue 1 (1988), Steve that had caches!) clobbered the precise hand-wired TTL logic and interfaced to insisted that all Circuit Cellar articles timing we’d come to expect from the PC bus through both memory and have descriptive titles. Now, I ask you, microcontrollers. In Issue 19 (1991) I I/O ports. Unlike contemporary PCI and doesn’t “Serious CISC Meets the Tas-

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 73 2703021nisley.qxp 2/5/2007 1:43 PM Page 74

kettes” tell you exactly what that need those mysterious antialiasing column was all about? and anti-imaging filters and what happens when they’re missing. THE ANALOG REALM From the very beginning, Circuit Much analog circuitry these days Cellar has always maintained that is designed and cared for by some- “What’s Inside the Box Still body primarily responsible for digi- Counts,” and we’ve always been tal hardware. Unfortunately, many willing to do whatever it takes to “analog problems” arise from a mis- get the story. Photo 3 shows a par- understanding of basic analog prin- ticularly dangerous mission from ciples, so my current columns Issue 163 (2004), where a Lentz explore those issues with circuitry Launcher that fired pennies into the that illustrates how design equa- ceiling showed how high current tions become real hardware and interacts with fast switching. what happens in the real world. When you must understand how For example, in Issue 151 (2003), I things work, start by reading, then showed how nonlinear components fire up your soldering iron. Simu- can generate unexpected signal fre- lation is good, but rosin smoke is quencies. I then showed how filters even better! can isolate or eliminate those fre- That bottle rocket was so much quencies in Issue 161 (2003). Some fun, I might have to do it again. of those components may even lie Hmmm. I outside your circuit boards, as the Photo 3—Pointing out subtle design details sometimes requires crystal diodes I measured in Issue getting into the guts of the hardware. Remember, what’s inside Ed Nisley is an EE and author in the box still counts! 195 (2006) demonstrate. Poughkeepsie, NY. You may contact Sampled-data systems, even those him at [email protected] with “Cir- with “simple” ADC and DAC circuits, domain. My Issue 185 (2005) and 187 cuit Cellar” in the subject to avoid have peculiar properties in the frequency (2006) columns showed why you really spam filters.

WWW.GiURUMELE.Hi2.RO

74 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703002-Bachiochi.qxp 2/5/2007 1:45 PM Page 75

FROM THE BENCH by Jeff Bachiochi

Embedded USB Breakthrough Jeff recently got crafty with the new FTDI VNC1L embedded USB host controller IC. Now he doesn’t need to carry around his laptop in order to log data from his designs.

I’m interrupt driven. By rights, this three interfaces: serial, parallel, or SPI. other mass storage) drives. No need to column should be one in the continu- This will eliminate the need to tote think about FATs and file structures. All ing series I began last month. I have a around my laptop in a backpack to log of a sudden today’s most popular storage number of projects planned that coa- data from last month’s project. device, the USB flash/stick/thumb drive lesce around electric vehicles. In fact, is accessible for use in embedded proj- the vehicle I began with last month is VNC1L ects. Simple ASCII commands via the an electric bicycle. The first project If you are like me, when you take a chosen interface control access to the centered on circuitry to monitor stor- look at the VNC1L’s block diagram USB storage device. age batteries up to 48 V (4 to 12-V lead bells and whistles will go off in your Although I will most likely add this acid batteries). Both charging current brain (see Figure 1). I ordered the as a peripheral to last month’s project and operating current give a picture of VDIP1 prototyping module to get at some point, here it makes most battery capacity and efficiency. That started. This module has the VNC1L sense to design a stand-alone logger. I circuit outputs a serial stream of and supporting SMT parts, along with want to be able to attach an RS-232 ASCII data at 1-s intervals. I used a a USB connector, all on a small 0.6″ cable, open a file, and accept data laptop to record the data. Since the DIP-28 header. This way I can hand- until I close the file. To do this, I need operating data comes from riding the wire some circuitry without messing to use a microcontroller between the bike, I slung the laptop in a backpack around with any SMT stuff. data and the VNC1L. If the microcon- while I rode a three-mile course typi- The VDIP1 module comes with Vin- troller has twin serial ports, then I cal of the topography of New England. culum disk and peripheral interface could use the serial interface between Plans are underway to explore other (VDAP) firmware preprogrammed into the microcontroller and the VNC1L. areas (e.g., a LIN automotive bus, a the VNC1L chip (see Photo 1). VDAP However, I wanted to use the solitary vehicle dashboard, a course slope, etc.). firmware supports USB flash memory (or serial port for data collection, which I am delaying all this left either a SPI or FIFO to sneak in a project that interface to the VNC1L. uses a brand new chip to Connects With To achieve maximum improve the task I ended USB throughput, I chose to Port 1 USB USB MCU with last month. I came Host/ 64 × 8 UART ADBUS 0–7 use the FIFO interface. Drive slave Flash memory I/F across this device and SIE1 Figure 2 shows how I instantly knew I needed USB Serial wired up this project. The Port 1 USB port Vinculum FIFO ACBUS 0–7 to make use of it. I think Camera Host/ VDIP is plugged into a slave core I/F you will feel the same SIE2 DIP socket made of head- way. Future Technology ers JP1:2. Power comes WWW.GiURUMELE.Hi2.ROCrystal Devices International 12-MHz 32-bit NPU into JP6, which can also PDA USB (FTDI), the guys that Oscillator Drive have TTL serial on it. BDBUS 0–7 were first to bring us a This eliminates the need RESET# Dual DMA USB-to-serial interface, controller I/O for the MAX232 and DE9, × PROG# 4 Ports BCBUS 0–3 have released the VNC1- Clock but adding these parts Keyboard/ embedded USB host con- Mobile PLL makes the project more TEST mouse phone 4k × 8 troller IC. The 48-pin SRAM flexible for use in the PLL Filter flash memory-based con- future. LEDs 1 and 2 troller is preprogrammed mimic the LEDs on the Figure 1—The VNC1L allows the designer to use many of the USB devices on the market via one to interface twin host/slave of three available interfaces. The I/O ports are predefined as the full complement of asynchronous VDAP module (port1:2 USB ports with one of serial interface signals, a minimal SPI, or an eight-bit bidirectional parallel FIFO data port. activity). These will

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 75 2703002-Bachiochi.qxp 2/5/2007 1:45 PM Page 76

Figure 2—To aid in prototyping this application, I used the 24-pin VDIP module. This schematic shows how I used a microcontroller to interface with the VNC1L. The applica- tion detects an inserted USB flash storage device, opens a file, and stores delimited data to the file.

make more sense when I do a layout with either a “No Disk” message or a watches this buffer for a 0x0D charac- using discreet parts in place of the D:\> prompt. Other commands work ter. When one is found, it notes the VDIP module. Four additional LEDs the same way. Most commands reply number of characters in the string and and four push buttons make up the with the appropriate data, a “Bad commands the VNC1L to write that user interface. I wanted to keep this Command,” or a “Command Failed” number of characters to the file. This design fairly simple, so I didn’t use an (see Table 1). command is actually two. The first is LCD. An LCD would be necessary if As you can see in Figure 2, I tied the WRF command containing the you wanted to give the user the ability LED6 to the VDIP reset line; there- number of characters. The next com- to enter file names or view the direc- fore, LED6 is the status of the mand is the string of data. LED5 indi- tory of the storage device. I thought VNC1L. LED3 indicates when a cates a WRF is being performed. Press- that would make the device overly device has been inserted. At this point ing SW1 halts the logging process. You complicated. I opted for simplicity, you may request logging serial data by can begin another logging session by and simple it is. I used only one push pressing button S1. The appropriate pressing SW1 again. No checks are button in this application. commands are sent to the VNC1L to made for free space; therefore, ample At reset (or at power-up) the VNC1L search the directory for a file called space must be ensured, which is not is programmed to check the FTB00.TXT. If the file is found, the usually a problem. ACBUS5:6 pins for user interface file number is incremented (00–99) selection and sendWWW.GiURUMELE.Hi2.RO out a sign-on mes- until the file is not found. It is then VNC1L APPLICATION sage through the selected interface created and opened for writing. To help debug and understand this connection. The message appears in A file can also be opened for device, I added a few options to this the following format: Ver xx.xx, appending data. LED4 indicates when application. Both the SPI and FIFO VDAP, On-Line. It also checks the sta- a file is open. (At this point, as with interfaces are coded into the applica- tus of the two USB ports and reports any storage device, removing the tion. This is selected in the assembly on any device. (A search is done on device will close the file with a loss of code as the I/O definitions change any storage device to check for ROM data). The data stored is delimit- with the selection. You can also images, because the VNC1L can ed, and I use this fact to save data. choose to disable the logging applica- update its software via an automatic Data received from the microcon- tion all together and have the microcon- file transfer). Sending a carriage return troller’s serial port is stored in a RX troller just pass serial port data directly () reports the status of the port data ring buffer. The microcontroller to and from the VNC1L. This allows

76 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703002-Bachiochi.qxp 2/5/2007 1:45 PM Page 77

you to connect to a PC running Hyper- The major differences in the appli- use only the FIFO interface to get the Terminal, type in commands directly, cations have to do with the type of fastest throughput. After wiring up and receive replies. Figure 3 shows a interface you are using with the the VDIP module to a microcontroller, general flow chart for this application. VNC1L. My initial reaction was to I began developing some code for the

ASCII Binary Function Reply $0D Check if online This will return the appropriate prompt or “no disk” message for the current command set. Response to check if online for Extended Com- If no valid disk is found ‘No Disk’,$0D mand mode If a valid disk is found ‘D:\>’,$0D Directory operations ‘DIR’ $01,$0D Lists the current directory A list of file names and directory names are returned. Each entry is terminated by $0D. A directory entry has ‘DIR’ after the name and before the $0D. ‘DIR’ $01,$20, ,$0D Lists the file name followed by the size. Use this $0D, $0D before doing a file read so that you know how many bytes to expect. ‘DLD’ $05,$20, , $0D Delete directory Deletes the directory from the current directory. $0D ‘MKD’ $07,$20, ,$0D Make directory Creates a new directory in the current directory. $0D ‘CD’ $02,$20, $0D The current directory is changed to the new $0D directory ‘CD’’..’ $02,$20,$2E, $2E,$0D Move up one directory level. $0D

File operations ‘RD’ $04,$20, $0D Read file This will send back the entire file in binary to the monitor. The size should first be found by using the ‘DIR’ command so that you will know how many bytes to expect. $0D ‘RDF’ from This will send back the requested amount of data to the monitor. bytes MSB first) > bytes) , $0D the current open file. $0D ‘DLF’ $07,$20, $0D Delete file This will delete the file from the current directory and free up the FAT sectors. $0D ‘WRF’ to the $0D hex(4 bytes MSB first) bytes) , $0D end of the current open file. > ‘OPW’ $09,$20, ,$0D Opens a file for writing to with ‘WRF’ $0D ‘OPR’ $0E,$20, ,$0D Opens a file for reading to with ‘RDF’ $0D ‘CLF’ $0A,$20, ,$0D Closes a file for writing. $0D ‘REN’ $0C,$20, , Rename a file or directory $0D $20, ‘FS’ $12,$0D Returns free space in bytes on disk. For disks $0D of over 4 GB in size, this will return $FFFFFFFF if more than 4 GB available. Otherwise, use ‘FSE’ command ‘FSE’ $12,$0D Returns free space in bytes on disk $0D Debug commands ‘IDD’ WWW.GiURUMELE.Hi2.RO$0F,$0D Identify Disk Drive. This will display information Sends IDD data block and then $0D about the attached disk up to 4 GB. ‘IDDE’ $0F,$0D Identify Disk Drive Extended. This will display Sends IDDE data block and then $0D information about the attached disk allowing for a disk capacity up to 2 TB. ‘FWV’ $13,$0D Get firmware versions Displays the versions of the main firmware and the reprogram- ming firmware ‘MAIN x.xx’$0D ‘RPRG x.xx’$0D then $0D

Table 1—This table shows just a few of the commands supported by the VNC1L. All commands end with a carriage return (0x0D), as do replies.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 77 2703002-Bachiochi.qxp 2/5/2007 1:45 PM Page 78

Bit Status signal that he would investigate this. ming the VNC1L on the VDIP module 0 *RXE After looking at my schematic, I with the beta code required one of the 1 *TXE found I had the necessary connections USB-to-serial chips FDTI Chip is 2 — in place to redefine the interface as noted for. Luckily, I had all that was 3 — SPI without any rewiring (as long as I necessary to make this connection 4 RXEIRQ didn’t mind bit-banging an SPI.) So, (maybe more on this another time). 5 TXEIRQ while waiting for words from the The reprogramming utility worked 6 — “Empire,” I wrote some code to han- fast, and I was quickly ready to try 7 — dle SPI transfers. The SPI is a minimal some of my code in Feedthrough Table 2—Since the SPI has no status associated with interface so it is handled a little bit mode. Having already set up for the the interface, the user gains access to status through differently. Since there are no signals SPI, I decided to begin there. This an internal register. Four bits available in this status indicating the status of things, all time when I powered up the project I register mimic the operation of the FIFO's status I/O communication gets channeled got a sign-on message from the bits: *RXE, *TXE, *RD, and *WR. through one of two registers (inside VNC1L. I stuck a stick (flash memory the VNC1L). The SPI data is actually drive) into the USB port. Another interface. The FIFO interface is simple: 8 12 bits long, a start bit, a RD/*WR message indicated the device was data bits, 2 output bits (*TXE and bit, a Data/*Status bit, 8 data bits, detected. I ran through a number of *RXE), and 2 input bits (*RD and *WR). and a reply bit. You supply the data commands. Everything looked fine. I *RXE indicates when the VNC1L wants bits on a *WR. The VNC1L supplies toggled the switch (in my assembly) to to communicate with you. *TXE indi- VNC1L the data bits on an RD. The make adjustments in my code for the cates when its alright for you to com- Data/*Status bit chooses which inter- FIFO interface and reassembled it. municate with it. Use *RD and *WR for nal VNC1L register the communica- Yep! The FIFO seemed to be working! controlling the passing of data. tions use. The reply bit is always sup- Now for the logging application. I was having problems communicat- plied by the VNC1L. It indicates Since there is no terminal or LCD ing with the VNC1L, so I read over the whether the RD data bits are involved with the new application, literature again. I single-stepped through Old/*New or if the *WR data bits code operation is verified by the LED my code to see where things were going were Rejected/*Accepted. Read the activity. LED6 lit up, indicating the bad. When I brought *RD low on the status register to get the status bits VNC1L was coming out of reset. microcontroller, the signal wouldn’t go (see Table 2). LED2 flashed when the stick was low. Hmm, could I have had a bad I/O? Beta ROM code arrived from the inserted, telling me the VNC1L was No, when the signal was disconnected U.K. just prior to executing my appli- interrogating the storage device. Then from the VNC1L, it wiggled fine. Short cation in SPI mode. Getting the new LED3 came on telling me my code on the PCB? No, not that either. Hmm, code into the VDIP temporarily took saw the VNC1L’s output. I was ready it looked like the VNC1L inputs were my mind off the rapidly approaching to plug in my data source. When I being driven. I shot off an e-mail to the deadline for my column. Reprogram- pressed button 1, LED5 let me know a manufacturer and waited. file had been opened. Timely flashes After days without a reply, I started of LED5 indicated data was being Initialization getting antsy. I pored over all the written to the file. I let a few seconds information I could find on the web of data get captured before pressing N site, but I found no further documen- Logging? Button 1 to close the file. Good thing I tation to help. I noticed that all of the work alone, as I’m sure the sight of Y N applications on the site were using the RXE = 0? my strutting, fist pumping, and audi- Call check for serial interface. Nothing used SPI or buttons ble screams of “Yes!” were quite Y FIFO. The chip was announced at the unprofessional. Hey, if my sports Call move data Embedded Systems Conference (ESC) Y to TXBUF heroes can do their victory dances, File open? in Taipei, Taiwan. I found that Don why can’t an engineer! I was as happy Prowie of DLP Design had given a N as a clam to see data scrolling on my WWW.GiURUMELE.Hi2.RORXBUF Y Call check for presentation on the VNC1L in Sep- Empty? PC after inserting the stick and open- stick tember 2006 at the Boston ESC. After N ing the FTB00.TXT data file. visiting the DLP Design web site, I Call check for Call move data decided to dash off a note to Don. He data from RXBUF PROJECT LIMITATIONS immediately responded with, “Nope, Using a small embedded microcon- no experience with the FIFO inter- Figure 3—This chart shows the basic steps of this appli- troller for this project has some limi- face.” I asked if he would kindly share cation’s support of two modes of operation. Feedthrough tations. RAM is usually at a premium, a contact with me and he graciously mode allows a terminal to send and receive ASCII com- so TX and RX buffers need to be limit- mands directly to the VNC1L. Logging mode makes use forwarded my inquiry. Gordon Lund of those commands under the covers to create a stand- ed in size. The Microchip Technology from the home office in the United alone logging system for data. The VNC1L communication PIC16F737 has four 128-byte banks of Kingdom replied with a short note interface supports both serial (SPI) and parallel (FIFO). data RAM. The user’s portion of these

78 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703002-Bachiochi.qxp 2/5/2007 1:45 PM Page 79

Interfacing with most mod- ules occurs through serial connections. If you plan to 3URXGO\GLVWULEXWHV use the FIFO mode, make sure the present revision level of the VDAP firmware is greater than V1.1 (the orig- Battery Backup Module for HESC, inal version). V5SC & HPSC Series Power Supplies I get excited when a prod- uct opens up new design pos- sibilities and is easy to use. However, there is a level of frustration that comes with BAT-NiMh45 exploring new products, espe- cially when you begin to Capacity 4500 ma-hr @ 8.4V nominal question your abilities. Manu- Energy backup of 37.8 watt-hr. facturers must be responsive PC/104 footprint size. with strong support, or they Available with built-in Real Time Clock Photo 1—The VDIP module is used in this prototype. It conforms to a run the risk of having a design ″ 24-pin 0.6 DIP socket. This allows prototyping without the need to han- changed to eliminate a part dle any SMT parts. that may actually be superior. Now I can get back on task. varies; I set up 80-byte ring buffers in As spring approaches, there are plenty of IDE Flash Drive Carrier Board with Micro SD Interface the third and fourth banks. This appli- paths to take in my quest of exploring cation requires data to be delim- electric vehicles. But first, I’d like to ited and no string can exceed 80 bytes congratulate all of the past and present (or the head wraps around and staff of this magazine for the blood, destroys data). The application could sweat, and tears they’ve shed to make use hardware handshaking to request it the success that it has become. Not SD-IDE-40/44 that data be paused if the buffer gets many periodicals reach the amazing full, but I didn’t want any data source milestone of 200 issues. Steve Ciarcia Available in 40 and 44 pin header configuration used with this project to have a hand- knew what readers wanted back when Support PIO 0-4 and Ultra DMA 3 mode. shaking requirement. he wrote his “Circuit Cellar” column Bootable from Transflash/micro SD. One thing you can’t program for is in Byte magazine. Since then, a whole Low power consumption. the user removing the storage device new generation of readers has joined prior to closing any open files. I sup- the ranks. Now we all have the pose you could mechanically prevent opportunity to share ideas and learn the device from being removed or from one another, thanks to his close the file between each store. understanding of what is important. Industrial Relay Board (This lowers the odds, but it doesn’t Thanks for steering us on a straight eliminate error.) Although this appli- course, Captain Steve. I cation doesn’t check for or report free space, all the commands are here to do Jeff Bachiochi (pronounced BAH-key- this. At some point, a real user inter- AH-key) has been writing for Circuit face would be necessary. I’d like to see Cellar since 1988. His background IR104 a touchscreen integrated with some includes product design and manu- small LCDs. This would make inte- facturing. He may be reached at WWW.GiURUMELE.Hi2.RO5amperes @ 250VAC or 30VDC output grating a simple user interface much [email protected]. 3V to 24V AC or DC input easier. I wonder if the pressure of a PC/104 compliant, 3.75”W x 3.55”L touch on an LCD could be detected as SOURCES 20 optoisolated input and 20 output relays some change in the driving signals. VNC1L Embedded USB host con- VINCULUM troller IC Future Technology Devices International www.tri-m.com [email protected] You can get the VNC1L and VDIP www.ftdichip.com datasheets at www.vinculum.com.

This web site (devoted to the VNC1L PIC16F737 Microcontroller 1.800.665.5600HEAD OFFICE: VANCOUVER product) has other modules and appli- Microchip Technology, Inc. tel: 604.945.9565 fax: 604.945.9566 cations available to aid the designer. www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 79 2703003-cantrell new.qxp 2/5/2007 2:14 PM Page 80

SILICON UPDATE by Tom Cantrell

Code Like the Wind World Tour Finding the right programming language is like selecting a hammer at a hardware store, it has to match your task. Tom introduces the latest version of Express. Perhaps it’s the right “tool” for your next job.

Two hundred issues down the line ask Firestone. dures and a failure to fully investigate and, with apologies to an old Saturday Indeed, bad software can be a problem reports because there haven’t Night Live shtick, I can certainly say: killer—literally. Many of you are prob- been problems before. An initial pre- “Silicon has been very, very good to ably familiar with the disturbing story sumption that faulty hardware must me.” I suspect it’s been very, very of the Therac-25 radiation therapy be to blame is all too common, and good to you as well. machine that killed rather than cured. usually wrong. Ultimately, as stated Software? Now that’s another story. A fundamental design mistake made above, designing a machine that For instance, despite more than 10 by the Therac-25 designers was requires “bug-free software” (an oxy- years of upgrades to Windows, my PC ”building a machine that relies on moron) to be safe is asking for trouble. still does the blue-screen boogie-to- software for safe operation.”[1] I made all these mistakes and nowhere from time to time. Sure, a The Therac-25 story is a must-read learned my lessons long ago, thankful- PC crash is something folks have for any engineer. You’ll find a litany of ly suffering little more than excessive come to accept as “normal.” It’s just mistakes, including poorly document- head scratching along the way. How an inconvenience, like getting a flat ed spaghetti code full of side effects, about you? And remember, even if tire on the way to work. But some- race conditions, etc. Other mistakes you aren’t a software writer, you are a times a flat tire can be a killer—just include piecemeal, ad hoc test proce- software user. For example, everybody who drives is likely to soon encounter “drive-by-wire” software under the hood of the latest vehicles. Knowing what we know about the myth of “bug-free software,” reports of elec- tronic throttles that don’t, and “over- active” suspensions are not unexpect- ed.[2] I figure I’ll wait for version 3.1 and let other folks be the beta site.

TOWER OF BABEL While today’s chips are a zillion WWW.GiURUMELE.Hi2.ROtimes better than the originals, soft- ware tools have not enjoyed a similar improvement. In short, there’s no Moore’s law coming to the rescue of software. For example, the “C” lan- guage widely used today is little changed from the original defined more than 30 years ago. Not that it’s necessarily fair to blame the tool for the folly of its user. Photo 1—According to Cypress, an Express program (in this case a heater) is a picture that’s worth a thousand After all, the common household lines of code. hammer hasn’t changed much in cen-

80 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703003-cantrell new.qxp 2/5/2007 1:46 PM Page 81

tion: What is the best tion of hammers. Besides the one programming lan- you’ve got in your kitchen drawer, guage? Of course, reali- you’ll find all manner of specialized ty-based imperatives hammers (tack, mallet, sledge, nail sometimes dictate the gun, etc.) optimized for specific tasks. answer. For instance, The main problem I have with soft- in the PC world, the ware is that it generally remains the answer to the “best” province of a priesthood of full-time language question may gurus. This was true of computer simply be whatever hardware long ago, but silicon Microsoft says it is. changed all that with the PC, which Having dabbled in gave everyone an entrée to the former- more than a few lan- ly insular cult of computing. Not so guages over the years, with software. Everybody has a PC, I’d like to propose that but I daresay few people ever actually there is no single lan- program them, at least beyond tweak- guage that can be ing a spreadsheet. deemed “best.” Indeed, Actually, the odd thing about the my experience is that situation is that it’s understood and languages that try to be accepted that only “computer jacks of all trades end experts” can do even the simplest Photo 2—With four PSoCs and all the trimmings (e.g., an accelerometer, USB up being complicated thing. Does it make sense that the and LCD interfaces, and LEDs), the Cypress World Tour demo board has and bloaty masters of average person can drive a car, but something for everyone. none. Rather, I’d say they can’t program a one-line what language is “best” IF/THEN application? turies, but nobody blames the ham- depends on the task at hand. Next mer when they whack their thumb. time you’re in the tool department at SOCKETS, SEATS, SOFTWARE It all raises the philosophical ques- a hardware store, check out the selec- All of these software ruminations

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 81 2703003-cantrell new.qxp 2/5/2007 1:46 PM Page 82

Photo 3—A notable upgrade with the latest version (2.1) of Express is the addition of a number of “smart” I/O ele- ments. Shown here is the LCD Bar Graph that goes beyond simply interfacing the LCD to include a scalable bar graph function.

set the stage for a review of the latest incorporated programmable logic to version (2.1) of Express, the visual pro- uniquely differentiate their otherwise gramming language for Cypress middle-of-the-road 8-bit flash memory Semiconductor PSoC chips. I covered MCU. The icing on the cake is that the PSoC chips when they were intro- the programmable logic includes ana- duced more than five years ago (T. log capabilities and the PSoC price, Cantrell, “SoC Hop,” Circuit Cellar typically a buck or two, is right. 128, 2001). At the time, I was The embedded market doesn’t impressed with the way Cypress switch horses overnight. Even for a standout part, it takes a long time to WWW.GiURUMELE.Hi2.RObuild awareness, establish credibility, get designed in, and ramp into produc- tion. After five years, PSoC is finally getting the respect it deserves. According to Cypress’s web site, PSoCs are now shipping at a run-rate approaching 100 million units per year. Sure, that represents just a few percent of the gigantic 8-bit market. Photo 4—The LCD bar graph in action. Note that the But, unit shipments, “sockets” if you function also supports four-line displays, a feature that allows two parameters and bar graphs to be displayed will, are only part of the story. simultaneously. Ultimate success and staying power is

82 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703003-cantrell new.qxp 2/5/2007 1:46 PM Page 83

Cypress says they have 2,000 PSoC customers, and more importantly, the number is growing at an impressive rate, having doubled in just six months. A couple of years ago Cypress introduced the Express visual program- ming language for PSoCs, which I covered in “World Beyond Ware”(Circuit Cellar 180, 2005). Let’s start by reviewing The Express basics to set the stage for this month’s eval- uation of the new version. Photo 6—Here’s an example of the USB interface at work using Concept-wise, Express HyperTerminal on the PC side. The “WR” commands toggle the LED, while the “RD” commands sample the voltage input (which I changed uses an “input,” “computa- between readings). Note also the trapping of error conditions, a situa- tion,” “output” model that tion your PC-side software must deal with. reminds me of a schematic. Photo 5—Another smart I/O function in version 2.1 is a USB interface. In conjunction with a Windows driver A “program” is created by (generated by Express), it allows a PC to get into the choosing elements from a library and Verilog) is noted. Have it your way. action, in this case reading a voltage on a PSoC input then configuring and connecting them The predefined I/O and processing and controlling an LED connected to a PSoC output. (see Photo 1). The irony that Express elements are enhanced with a measure uses “pictures” to create software, of “parameterization” (i.e., the ability as much determined by “seats,” (i.e., even as hardware designers are to configure certain aspects of their the number of designers using a part). switching to “words” (e.g., VHDL and behavior). The more they do, the less

Create your Future at Camosun College

Read about ourWWW.GiURUMELE.Hi2.RO Students’ Success Stories in this Issue! N Digital Signal Processing N Digital and Analog Wireless N Embedded Ethernet Communications N CPLD and VHDL N Real Time Operating Systems N C and C++ N CCNA and A+ Small classes,dedicated teachers,proven reputation. That’s the Camosun advantage!

www.elex.camosun.bc.ca [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 83 2703003-cantrell new.qxp 2/5/2007 1:46 PM Page 84

Offset Name Read/write access been a lot of additions and improve- outputs. Both actions rely on the PC 0 Command RW ments to the I/O and computation accessing the corresponding locations 1 LED RO building blocks. in the PsoC, as defined in the “regis- 2 Volts RO For instance, the I/O options before ter map” created and shown in the pretty much extended only as far as datasheet generated when the project Table 1—When a design using the USB interface is built, Express enables PC access with a register map the pins on the chip. Now, the list has is built (see Table 1). showing the address and access rights (e.g., read- grown rapidly with support for a vari- So just how does the PC do that? write, read-only) for variables in the design. ety of external devices including sen- The answer is found in the USB driver sors such as temperature, pressure, on the PC side of the equation, which you have to. “Building’” an Express humidity, optical, distance, along with is also generated by Express. It program not only creates the software, the aforementioned acceleration and includes a basic command processor but also a complete schematic, a bill CapSense. On the output side, there that allows the PC to issue commands of materials, and a datasheet for the are a bunch of PWM building blocks to write, read, or continuously read underlying hardware. Development supporting different applications (i.e., locations in the PSoC register map. and debug takes advantage of a built- motor, heater, power supply) with a Since the commands and results are in simulator, reducing the need to variety of configurations and power in ASCII, we can use a terminal emula-

“blow and go” every time you change levels (i.e., from VDD at 10 mA, from tor to see what’s going on. As shown in something. the PSoC itself to 48 V at 10 A, using Photo 6, first we tell the terminal emu- an external power transistor). lator (e.g., Hyperterminal) to connect to WORLD TOUR The new LCD bar graph in Photo 3 the virtual COM port (i.e., in this case Cypress is embarking on a world demonstrates the value of a “smart” COM7) created when the Express gen- tour of seminars to roll out the new I/O function. Simply getting some erated USB driver was installed. version of Express. For those of you data onto the display is one thing, but Next, you can see I typed in the who can’t make a seminar in person the function also includes a bar graph commands to turn the LED on and off read along and I’ll take you on a guid- feature with built-in scaling capability by writing 1 and then 0 to address 0, ed tour of some of the highlights. (see Photo 4). Put it all together and which maps to the “Command” inter- The world tour board is a fun little the few seconds it takes to configure face valuator in the design. Along the gadget with the equivalent of four the object replaces hours or even days way I turned the potentiometer to demo boards built-in (see Photo 2). of conventional programming. change the voltage input. You can see Starting in the top left, the first PSoC Another example of a time and the resulting change of value returned shows off Cypress CapSense capaci- effort saver is the newly added USB in the “Volts” register map location tive (i.e., touch) sensing scheme, “interface” object. Let’s take a closer (addresses 2 and 3). which Fred Eady covered in his col- look at the world tour USB demo to The command processor is a bit umn last month (“Embedded see how that works. finicky, with strict rules about for- Capacitive Touch Applications,” As shown in Photo 5, an “interface” matting. Everything has to be upper- Circuit Cellar 199, 2007). Heading is different than a regular input or case and all values must be two-digit clockwise to the upper right, there’s a output device in that it kind of just hex. Furthermore, as shown in the USB demo. Cypress has been big in sits off to the side without any con- example, your PC-side program needs USB chips for a long time, and now nections. That’s because it works by to be able to deal with error condi- Express can speak a bit of USB too. exposing all the variables in the tions and messages caused by access The USB port also acts as a handy design, the so-called “register map,” to an undefined address or attempting power supply connection for the board for access. to write to a register location defined (no wall wart needed) and there’s a 9-V One such variable is the “Volts” object, as read-only. battery option as well. Continuing to which is an analog (0 to 2,600 mV) Joining the I2C and USB interfaces, the lower right, there’s a PSoC driving voltage controlled by a potentiometer Cypress has added support for their a four-digit, seven-segment LED dis- on the board. The fact “Volts” doesn’t proprietary Wireless USB 2.4-GHz play. Finally, onWWW.GiURUMELE.Hi2.RO the lower left, we appear to be connected to anything in radio. Although some of the target find a tilt demo using a low-g the Express design is a clue that it’s applications (i.e., wireless keyboard accelerometer and also an interface for accessed via the “USBuart” interface. and mouse) and the brand name itself a commodity (i.e., HD44780-type) The same goes for “Command,” sound PC-centric, there’s no reason two- or four-line LCD. Each demo has which is a so-called “Interface Wireless USB can’t be used for a vari- a potentiometer driving an analog Valuator.” ety of non-PC applications (i.e., wire- input, a switch, a five-pin header for In summary, what’s going on is that less sensor) as well. the cute MiniProg USB flash memory the PC on the other end of the USB programmer, and a Tokyo-by-night interface can read the “Volts” present TOTAL RECALL complement of LEDs. on the PSoC analog input and it can One seemingly small addition to Compared to the first version of also issue a “Command” to control Express version 2.1 is a “Delay” valu- Express I covered last time, there have the LED connected to one of the PSoC ator. In this day and age when per-

84 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 2703003-cantrell new.qxp 2/5/2007 1:46 PM Page 85

ing it’s holding the concept back. I have lots of ideas for improvements. For instance, why not add arrows to connections to make the direction data flow clear at a glance? It might also be helpful to visually indicate the data type (8 or 16 bits) of an object, a) lest you encounter an unexpected mis- match (which I did and, by the way, the simulator didn’t catch). In addi- tion to a better pan and zoom capabili- ty, a macro-like encapsulation feature would ease working with larger designs by hiding complexity and reducing screen clutter. b) On the other hand, the temptation Photo 7—The Delay valuator (a) is a welcome addition to the latest version of Express. It gives designs a sense of to “fix it until it breaks” should be history (i.e., data that persists across loop iterations) that’s needed for many common functions, such as averaging avoided. Express will never be able to (b) shown here. handle giant, complex, high-perform- ance, real-time apps. To do so, it formance is all the rage, it may seem And Express 2.1 represents solid would have to lose its identity and odd that the ability to slow things progress on a lot of fronts. In particu- itself become a bloaty, complicated down is a feature. But, due to the way lar, the much larger I/O device library tool. Anyways, rocket science applica- Express works, the delay valuator is in stands out for both expanding the tions are kind of a moot point when fact a must-have feature for a variety application spectrum and simplifying the target is tiny PSoC chips. of applications. your work. And although I didn’t get If Express isn’t the perfect solution, Why is the delay valuator so impor- into it this time, Cypress now pro- so what? Remember the hammer tant? The answer lies in the way vides ways for users to create their example. No tool is ideal for every Express uses a “loop” structure to run own application-specific Express add- application. If you’re hanging a pic- your program. Inputs are captured, ons as well as integrate Express ture, you’re better off using the ham- valuators are calculated, and outputs designs with conventional (i.e., C, mer in the kitchen drawer, not a nail updated each iteration of the loop. ASM) programs. gun. If a simple tool like Express can However, that means there’s no easy Make no mistake: if it leads, it get your idea to silicon faster and easi- way for an Express program to keep bleeds. Though much improved, er, doesn’t that make it the best tool track of results from an earlier loop Express still has, shall we say, quirks. for the job? I iteration. For instance, going back to Photo 3, That’s a problem, because a sense of notice how some of the text at the Tom Cantrell has been working on history is key for many applications. bottom right is off the edge of the chip, board, and systems design and DSP functions like filtering rely on window, but the window can’t be marketing for several years. You may performing computations on a time- scrolled or resized (Hint: You can reach him by e-mail at tom.cantrell ordered past-to-present stream of data adjust the column width). Similarly, @circuitcellar.com. samples. Another example is PID con- the zoom function is kind of goofy, trol, which needs to keep track of pre- making it harder than it should be to REFERENCES vious and accumulated errors (i.e., D see what you want where you want it. and I terms, respectively) in order to It seems like half the time I right- [1] N. Leveson, “Medical Devices— calculate the new output. clicked on an object to do something The Therac-25,” http://sunnyday. The example WWW.GiURUMELE.Hi2.ROin Photo 7 shows with it, I got a pop-up menu from mit.edu/papers/therac.pdf. Delay at work. As shown in the simu- Adobe instead. (Express uses an [2] J. Scheeres, “Teched Out Cars Bug lation, the output of each loop itera- Adobe-supplied graphics front-end.) Drivers,” www.wired.com/news/ tion is calculated by averaging the last Not to mention the fact there are still autotech/0,63846-1.html?tw=wn_ five readings. It’s kind of the software plenty of “gotchas” documented in story_page_next1. equivalent of a hardware designer’s the README file. But to be fair, FIFO or shift register. many of the worst offenders from last time, such as the inability to edit a SOURCE EXPRESSION SESSION list without completely retyping it, Express 2.1 visual programming lan- I remain intrigued by the Express have been fixed. guage for PSoC concept of visual drag-and-drop pro- If anything, complaints about the Cypress Semiconductor Corp. gramming for embedded applications. implementation are fueled by the feel- www.cypress.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 85 ib-200.qxp 2/2/2007 1:21 PM 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″× 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) 872-3064.

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 x86: Elan SC520 v USB-FIFO up to 8 mbps CAN C166/XC16x/ST10/8051 CAN v USB-UART up to 3 mbps Blackfin: BF537 v USB/Microcontroller boards Faster-to-Market: Save time by pre-programmed with firmware integrating a PHYTEC Single 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

High-speed USB 2.0 + Xilinx FPGA Full Speed CAN Complete Software API USB Adapter

Simple configuration & use

75mm x 50mm 3.5“ x 2.0” $399.95 $199.95 XEM3010-1500P: XEM3001: Š 1,500,000-gate FPGA Š 400,000-gate FPGA $ 00 Š Programmable PLL Š Programmable PLL 235. WWW.GiURUMELE.Hi2.ROŠ Over 110 I/Os Š Qty 1 Over 80 I/Os Š 32 MB SDRAM Š 0.1” expansion headers Š Configuration PROM Š Business-card size Š 0.8-mm expansion Š $199.95 / Qty 1 Š $399.95 / Qty 1 Š $174.95 / Qty 10 Š $349.95 / Qty 10 FrontPanel Software API: Š Windows XP, Mac OS X, Linux Š C/C++, Python, Java Š Configure FPGA and communicate with your design +1 630-245-1445 Š The easiest way to integrate USB into your product Š Use for image capture, control, test equipment, etc. Naperville, Illinois USA Š Up to 38 MB/s transfer rate! 5% off with Coupon Code: CKTCLR73* www.c-a-n.com

* Valid for first order only. Void 30-days after issue publication.

Visit us online at: Opal Kelly www.opalkelly.com

86 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-200.qxp 2/2/2007 1:17 PM Page 87

New IP Products • $129.95

IP Power

IP Video

www.ArucaElectronics.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 87 ib-200.qxp 2/2/2007 1:17 PM Page 88

SpectraPLUS 5.0 Audio Spectrum Analysis Features Sound Card based I/O FFT sizes to 1048576pts, 1/96 Octave Up to 24 bit, 200kHz sampling rates 3-D Surface and Spectrogram Digital Filtering, Signal Generation THD, IMD,WWW.GiURUMELE.Hi2.RO SNR, Transfer Functions DDE, Macros, Data Logging, Vibration Analysis, Acoustic Tools FREE 30 day trial! www.spectraplus.com

Pioneer Hill Software 360 697-3472 voice PHS [email protected]

88 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-200.qxp 2/2/2007 1:18 PM Page 89

www.LinkInstruments.com 973-808-8990 Digital Oscilloscope Ȭȱ ’‘•’‘ȱ”Ž¢ȱ™›˜žŒȱ 500 MSa/s ȱȱȱŽŸŽ•˜™–Ž—œ • 2 Channel Digital Oscilloscope • 500 MSa/s max single shot rate 250 MSa/S (Dual channel) 512 Kpts Ȭȱ —›˜žŒŽȱ—Ž ȱ™›˜žŒœ 500 MSa/S (Single channel) 1 Mpts • Advanced Triggering ȬȱŽŒ›ž’ȱ‘Žȱ‹Žœȱ • Portable and Battery powered • Only 9 oz and 7” x 3.5” x 1.5” ȱȱȱŽ—’—ŽŽ›œ • FFT Spectrum Analyzer ȱ • USB 2.0 Ȭȱ›ŽŠŽȱŸŠ•žŠ‹•Žȱ‹›Š— $950 ȱȱȱŠ Š›Ž—Žœœ

ŽŠŒ‘ȱ‘Žȱ›’‘ Šž’Ž—ŒŽǰȱ›’‘ȱ—˜ ’‘ȱ’›Œž’ȱŽ••Š›Ȃœ

ŽŠȱ˜¡ŽœǷ www.LinkInstruments.com 973-808-8990 NNetet M Modulesodules ZigbeeZigbee WWirelessireless I I/O/O wwatchoutatchout extend your digital I/O’s hhereere c comesomes over100’s of feet up to tens ofmiles - in both directions - with the SpiderSpider 16IO-SSRT RF transceiver wwirelessireless modules pprogrammablerogrammable auto-binding multidrop sensor / actuator rrevolutionaryevolutionary networknetwork podspods

SAVE 5% enter coupon code CCI at checkout SAVE 5% enter coupon code CCI at checkout SAVE 5% enter coupon code CCI at checkout AABACOMBACOMdirectdirect..comcom AABACOMBACOMdirectdirect..comcom ABAABACOMCOMdirectdirect..comcom

ABACOM tel: +1(416) 236 3858 ABACOM tel: +1(416) 236 3858 ABACOM tel: +1(416) 236 3858 Technologies fax: +1(416) 236 8866 Technologies fax: +1(416) 236 8866 Technologies fax: +1(416) 236 8866

MYLYDIA, INC. Layout Gerber, Prototype Making QUWWW.GiURUMELE.Hi2.ROICK TURN PCB & Turnkey @ The Best Prices

{Œ“a _WWT]`\T`Z[Y [email protected]

WWW.MYLYDIA.COM

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 89 ib-200.qxp 2/2/2007 1:18 PM Page 90

EtherSmart WildcardTM Network -Enables Your Product

$140/100sWWW.GiURUMELE.Hi2.RO

G Standard RJ45 jack hosts 10/100Mbit Ethernet G HTTP, SMTP, TCP, DHCP, ICMP, and ARP Protocols G Email program-controlled messages to a specified LAN IP address G Establish a TCP/IP connection to exchange binary or ASCII data G Serve software-controlled dynamic content to your web browser Mosaic Industries Inc. tel: 510-790-1255 fax: 510-790-0925 www.mosaic-industries.com

90 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com ib-200.qxp 2/2/2007 1:18 PM Page 91

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

www.schmartboard.com

C Programmable Controllers & ICs

- Onboard Tiny C interpreter for fast program development

- Multiple program storage

- Free IDE includes text editor, compiler, simulator, serial downloader and test terminal

Full documentation on website www.ozitronics.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 91 ib-200.qxp 2/2/2007 1:18 PM 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 WWW.GiURUMELE.Hi2.RO 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 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 2/5/2007 2:41 PM Page 93

12

3 CROSSWORD

45

6 7 8

910

11

12 13

14

15

16 17

18

19

20

Across Down 1. A software glitch in this lunar explorer caused all of its fuel 2. To convert a file into secret code to vent in 1994. 3. To put into mechanical action 4. In this code, common in telecommunications, each bit of 5. & data is represented by at least one voltage level transition. 7. The size of a signal 6. Founded in 1998, this service enables you to send and receive 8. A pressure-sensitive display used to pres- online payments. ent and receive information 11. Malfunction 12. Object-oriented programming language developed in the 9. A ball in a socket used for pointing and 1980s for embedded real-time applications navigation 13. A two-terminal semiconductor that passes current in one 10. An association charged with defining pro- direction tocol standards for the short-range 14. Non-returnWWW.GiURUMELE.Hi2.RO to zero exchange of data over infrared light 16. Signals whose range of frequencies are measured from zero to 15. Sloping; slanting a maximum bandwidth or the highest signal frequency 17. The opposite of digital 18. To drive around in search of a Wi-Fi network 19. Quadrature counts 20. American designer (1918–present) who developed coincident- current magnetic storage, which was a precursor to RAM.

Brought to you by: The answers are available at www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 200 March 2007 93 94-advertiser's index.qxp 2/5/2007 2:38 PM 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 73, 91 ezPCB 19 Maxstream 49 R4 Systems

90 AP Circuits 86 FDI-Future Designs, Inc. 87 Merican Made 39, 95 Rabbit Semiconductor

89 Abacom Technologies 90 Front Panel Express, LLC 86, 88 Micro Digital, Inc. 87 Rabbit Semiconductor

91 All Electronics Corp. 37 Futurlec 27 Microchip 23 Reach Technology, Inc.

87 Apex Embedded Systems 89 General Circuits, Inc. 92 microEngineering Labs, Inc. 13 Renesas

63 Arcom Control Systems 86, 91 Grid Connect 90 Mosaic Industries, Inc. 91 Schmartboard

87 Aruca Technologies 33 HI-TECH Software LLC 31 Mouser Electronics 28 Sealevel Systems

7 Atmel 71 IMAGEcraft 89 Mylydia, Inc. 11 SEGGER Microcontroller Sys. LLC

32 BG Micro 90 Intec Automation, Inc. C2 NetBurner 74 Sierra Proto Express

47 Bitscope Designs 88 Intrepid Control Systems 3 Noritake Co., Inc. 10 Silicon Laboratories, Inc.

65 CWAV 58 Intronix Test Instruments, Inc. 69 Nurve Networks LLC 92 Systronix

26 CadSoft Computer, Inc. 92 Ironwood Electronics 92 Ontrak Control Systems 90 TAL Technologies

83 Camosun College 64, 91 JK microsystems, Inc. 86 Opal Kelly Inc. C3 Tech Tools

90 Conitec 17 Jameco 91 Ozitronics 56, 57 Technologic Systems

39, 88 Custom Computer Services, Inc. 71 Jeffrey Kerr, LLC 50 PCB Design Confrence West 88 Technological Arts

1 Cypress 5 Keil Software 87 PCB Fab Express 89 Tern, Inc.

86 DLP Design 69 LabJack Corp. 81 PCB-Pool 64 Tianma Microelectronics

71 Decade Engineering 69 Lakeview Research C4 Parallax, Inc. 55 Tibbo Technology, Inc.

37 EMAC, Inc. 87 Lawicel AB 86 Phytec America LLC 92 Trace Systems, Inc.

66 ESC-West 29, 87 Lemos International 92 Picofab Inc. 79 Tri-M Systems, Inc.

87 Earth Computer Technologies 2, 89 Link Instruments 88 Pioneer Hill Software 88 Triangle Reasearch Int’l, Inc.

74 Elprotronic 83 Linx Technologies 82 Pololu Corp. 32 Trinity College Robot Contest

88 eMicros 87 MCC (Micro Computer Control) 88 Pro-Tech Electronics Canada 88 WCSC (Willies Computer Software Co.)

22 ExpressPCB 21 Matrix Orbital 91 Pulsar, Inc. 90 Zanthic Technologies, Inc.

Preview of April Issue 201 ATTENTION ADVERTISERS Theme: Embedded Programming May Issue 202 Java-Based Earthbox Watering System Deadlines Reverse-Engineered ECP Bus Space Close: Mar. 12 ATir Keyboard Interface Material Close: Mar. 21 Slave Flash TriggerWWW.GiURUMELE.Hi2.ROTheme: Generic Modbus Simulator (Part 2): Create a Modbus Master Measurement & Sensors Build a Three-Axis CNC Mill Machine BONUS DISTRIBUTION: Sensors Expo ABOVE THE GROUND PLANE Battery Capacity: Charge Call Shannon Barraclough APPLIED PCs Uncomplicated RF Communication now to reserve your space! FROM THE BENCH Local Interconnect Network 860.872.3064 SILICON UPDATE USB: (Wire)Less is More e-mail: [email protected]

94 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com 66.qxp 4/4/2006 3:34 PM Page 1

WWW.GiURUMELE.Hi2.RO steve_edit_200.qxp 2/5/2007 2:41 PM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director Inside the Box Still Counts

This was the title of my very first Circuit Cellar INK editorial 19 years ago. Two hundred issues later I still believe it. Like solder being my favorite pro- gramming language, I still believe that however appliance-like embedded control and personal computing implementations become, we can’t forget that the process of achieving that goal isn’t instant. In order to create the sophisticated devices and technologies regarded as off-the-shelf, many people still have to maintain real expertise in rudimentary design skills. Basically, somebody always has to know what’s inside the box. Dave Tweed has done a wonderful job describing both the evolution in technology and Circuit Cellar’s editorial course during the last 200 issues. Ed Nisley has supplemented it with musings about how wild and wooly some of his projects have been. What is not touched upon is how we all got here in the first place. Perhaps you’ve picked it up from my sarcastic editorial comments over the years, but in my opinion the phrase “engineering appreciation” is an oxy- moron to most of the business world.They love us when it comes to conceptualizing and designing profitable products and then complain about the costs of maintaining the engineering department after it’s done. They love our geeky personality when it comes to working 16 hours a day to solve a design problem at the office, but they refer to us as “hackers” because we like to do the same stuff at home. It’s no secret that I wrote a monthly hands-on design series at BYTE for 10 years before Circuit Cellar.The great success that BYTE and I shared was because we had a mutual appreciation of discovery and invention. Unfortunately, BYTE was insanely profitable. I say “unfortunately” because when you start having the revenue from 700-page issues, management gets addicted to the money. The result was that it only took a minor market fluctuation and they all started “tweaking” things to keep their “fix.” The biggest “tweak” was changing the entire editorial direction of the magazine from invention and design to “follow the bouncing PC.” Seeing PC Magazine make lots of money was too much for them and they decided to make BYTE into a PC Magazine clone. It didn’t mean an immediate end for me, but I saw the handwriting on the wall. Ultimately, I was given an opportunity to continue with the magazine, but only if I would review advertiser products instead of writing design articles. I’m sure you can understand my response to that. I was already at a slow burn around that time, but the final straw for me was at a restaurant when I overheard someone at a nearby table describing how the PC was taking over the world and becoming a high-volume commodity and the embedded controller of the future. As I mentioned a long time ago, the point at which I almost jammed a piece of garlic chicken in the guy’s ear was when he said that businesses didn’t care what was in the box. The future was commodity computer users. All the rest of the engineers were just hackers (and not the good kind). That was the last straw. It would be fun to say that I ran out of the restaurant and started a magazine that afternoon, but it actually took about a week. It would also be very egotistical of me to leave you with the impression that I started it alone. Circuit Cellar is and always has been a team effort.The peo- ple who started Circuit Cellar 200 issues ago were Ken Davidson, Ed Nisley, Jeff Bachiochi, Dan Rodrigues, Tom Cantrell, my wife Jeannette, and me. The important point to be made here is how things stand 19 years later. BYTE is gone now and just a dusty memory, but like the constancy of Circuit Cellar’s editorial direction for the last 19 years, every member of this original team is still involved with producing Circuit Cellar magazine today. I look back at some of our early articles and smile at their simplicity, but that’s where everyone’s experience level was when we started. Today’s tech- nology indeed seems more sophisticated, but it is really only the sophistication of the blocks we plug into a design and not the innate intelligence of the engineer that has changed. Blocks that were once just NAND and NOR gates have been replaced with integrated logic and programmable devices. Continually increasing the complexity and function of these design building blocks can only happen if there are people who know what’s already there and where we are going. To describe how Circuit Cellar fits into that equation, I choose to use the exact same words that I said 19 years ago:

Without a continuous effort at understanding and improving present achievements, we cannot progress to higher levels of achievement. Circuit Cellar is a publication designed to increase that awareness. We must not ignore the fact that it is a combination of people and machines that create intelligent per- sonal systemsWWW.GiURUMELE.Hi2.RO.Whether they be applied as toaster-like appliances throughout an industry, serve as the control system of a CAT scanner, or function as a video arcade game, the basic ingredients of computers are similar. It is the continual evolution of a computer’s concept, design, and application that ulti- mately results in the perfection of the truly Intelligent Personal System.

Apparently, enough of you agree with this assessment that we’re still here 19 years later. Thank you.

[email protected]

96 Issue 200 March 2007 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 8/9/2006 2:19 PM Page 1

WWW.GiURUMELE.Hi2.RO C4.qxp 1/31/2007 9:16 AM Page 1

WWW.GiURUMELE.Hi2.RO