#157 August 2003 www.circuitcellar.com CIRCUIT CELLAR®

THE MAGAZINE FOR COMPUTER APPLICATIONS WIRELESS COMMUNICATIONS

WiFi SniFi

Palm-Controlled Telescope

Wireless Outdoor Light Control WWW.GiURUMELE.Hi2.RO USB-CAN Interface

08>

7925274 75349 $4.95 U.S. ($5.95 Canada) WWW.GiURUMELE.Hi2.RO MCU later.

Your Customized Mixed Signal platform in 60 minutes or less Build your custom PSoC™ with programmable analog and digital functions from our extensive library.

Option #8926

Option #1530 8-bit PWM Inverting Amplifier

Option #625 Low Pass Filter 24-bit Timer

Option #4237 16-bit CRC Notch Filter IrDA Transmitter Analog 12-bit Comparator Incremental A/D 8-bit DAC ™ 8-bit DAC Use the Cypress PSoC instead of an MCU for 12-bit Incremental A/D more flexibility, fewer parts and lower cost. Band Pass Filter IrDA

Band Pass Filter 8-bit Counter Analog Semiconductor Corporation. The versatile PSoC™ Programmable System-on-Chip™ is Transmitter Comparator the world’s first mixed signal array that lets you custom Instrumentation11-bit AmplifierDelta Sigma A/D configure the exact functions you need. And it has an Instrumentation Programmable Amplifier CPU Gain Amplifier8-bit Counter on-chip controller to manage your application and run Analog the configuration process. Comparator 11-bit Analog Delta Sigma A/D Comparator 16-bit PWM Graphically select, place, and interconnect the peripherals you want and adapt the architecture with PSoC Designer™ software There are many more blocks to work with— Dynamically reconfigure a single PSoC and thousands of configurations to choose from. chip multiple times—changing functionality PSoC Designer™ software is free for download, with on the WWW.GiURUMELE.Hi2.ROfly in any application full-featured emulation hardware starting at $248. Reduce BOM cost by reducing the number of external components To learn more about our innovative PSoC solutions and to enter a drawing to win a PSoC Development Cypress, PSoC, Programmable-System-on-Chip and PSoC Designer are trademarks of Cypress Semiconductor Corporation. ©2002 Cypress Kit, visit www.cypress.com/ad/mcu. All other Trademarks are the property of their respective owners. Digital Oscilloscopes

• 2 Channel Digital Oscilloscope DSO-2102S $525 • 100 MSa/s max single shot rate DSO-2102M $650 • 32K samples per channel Each includes Oscilloscope, • Advanced Triggering Probes, Interface Cable, Power • Only 9 oz and 6.3” x 3.75” x 1.25” Adapter, and software for • Small, Lightweight, and Portable Win95/98, WinNT, Win2000 • Parallel Port interface to PC and DOS. • Advanced Math options • FFT Spectrum Analyzer options Logic Analyzers

• 40 to 160 channels • 24 Channel Logic Analyzer • up to 500 MSa/s • 100MSa/S max sample rate • Variable Threshold • Variable Threshold Voltage • 8 External Clocks • Large 128k Buffer • 16 Level Triggering • Small, Lightweight and Portable • up to 512KWWW.GiURUMELE.Hi2.RO samples/ch • Only 4 oz and 4.75” x 2.75” x 1” • Optional Parallel Interface • Parallel Port Interface to PC • Optional 100 MSa/s Pattern Generator • Trigger Out • Windows 95/98 Software LA4240-32K (200MHz, 40CH) $1350 LA4280-32K (200MHz, 80CH) $2000 LA2124-128K (100MSa/s, 24CH) LA4540-128K (500MHz, 40CH) $1900 Clips, Wires, Interface Cable, AC LA4580-128K (500MHz, 80CH) $2800 Adapter and Software $800 LA45160-128K (500MHz, 160CH) $7000 All prices include Pods and Software www.LinkIns4.com Link Instruments • 369 Passaic Ave • Suite 100 • Fairfield, NJ 07004 • (973) 808-8990 • Fax (973) 808-8786 WWW.GiURUMELE.Hi2.RO TASK MANAGER

EDITORIAL DIRECTOR/FOUNDER CHIEF FINANCIAL OFFICER Steve Ciarcia Bulk Be Gone Jeannette Ciarcia MANAGING EDITOR CUSTOMER SERVICE Jennifer Huber Elaine Johnston TECHNICAL EDITOR ireless technology has become such a part of our lives that it’s diffi- C.J. Abate ACCOUNTANT W Jeff Yanco cult to remember what life was like without it. As I was walking into a movie WEST COAST EDITOR theater last weekend, I noticed a group of teenagers—each girl on her own Tom Cantrell ART DIRECTOR KC Prescott phone (personalized by different colors and ring tones). Remarkable CONTRIBUTING EDITORS Ingo Cyliax designs, innovative low-power devices, and, of course, savvy marketing GRAPHIC DESIGNER Fred Eady Mary Turek have helped make wireless technology accessible to nearly everyone. George Martin For the Wireless issue, we found some projects that are sure to pique George Novacek STAFF ENGINEER Jeff Bachiochi the interest of the more sophisticated consumers. But, what’s fun about John Gorsky simply buying the next gadget? We hope these projects inspire you to want NEW PRODUCTS EDITOR to build your own. John Gorsky QUIZ COORDINATOR David Tweed You’ll want to get started on your own wireless outdoor lighting system PROJECT EDITORS before summer’s over. John Dammeyer combined CAN, RF, and a Steve Bedford Ken Davidson PIC12C509 to develop an impressive outdoor lighting scheme (p. 12). David Tweed John’s design makes a sensible alternative to bulky wires or solar lamps that are often dim or unusable after cloudy days. ADVERTISING PUBLISHER For those of you who prefer looking to the sky rather than the ground, Dan Rodrigues E-mail: [email protected] we also have an interesting project to enhance your telescope. Steven ASSOCIATE PUBLISHER/DIRECTOR OF SALES Pope devised a way to link his Palm device to his Meade ETX-105 tele- Sean Donnelly Fax: (860) 871-0411 scope using the Zilog eZ80 and Webserver module (p. 20). (860) 872-3064 E-mail: [email protected] Cell phone: (860) 930-4326 The ETX-105 has Meade’s Autostar controller, which enables it to locate celestial coordinates by compensating for the Earth’s rotation. The only ADVERTISING COORDINATOR Valerie Luster Fax: (860) 871-0411 trouble is that the telescope’s two-line display makes it difficult to use the (860) 875-2199 E-mail: [email protected] system. Although he could attach a laptop, he figured adding bulky wires to ADVERTISING ASSISTANT a nighttime activity might be a bad idea. Plus, he had a more inventive solu- Deborah Lavoie Fax: (860) 871-0411 tion: use the Palm device as an interface to a GPS receiver. There was one (860) 875-2199 E-mail: [email protected] last hurdle; he needed a wireless infrared IrDA port for the telescope. That Cover photograph Chris Rakoczy—Rakoczy Photography problem, too, was solved easily enough with the Zilog IrDA development PRINTED IN THE UNITED STATES system. CONTACTING CIRCUIT CELLAR We also found a project to suit the interests of WiFi fans. When stories SUBSCRIPTIONS: INFORMATION: www.circuitcellar.com or [email protected] about WiFi started showing up on CNN’s web site last year, it was a sure To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or sign that the technology has gained mainstream popularity. If you want to [email protected] PROBLEMS: [email protected] know the literal ins and outs of WiFi, turn to page 50 for Roy Franz’s arti- GENERAL INFORMATION: cle. Using an 8-bit microcontroller (NEC’s µPD78F9418), Roy designed an TELEPHONE: (860) 875-2199 Fax: (860) 871-0411 INTERNET: [email protected], [email protected], or www.circuitcellar.com application to find and monitor 802.11b wireless networks. The compact, EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066 NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066 low-power WiFi SniFi (pronounced “wiffy sniffy”) serves as a network node. [email protected] Aside from sniffing out wireless networks, the WiFi SniFi also displays AUTHOR CONTACT: E-MAIL: Author addresses (when available) are included at the end of each article. frames and responds to pings and ARPs. These projects are so interesting that I don’t even need savvy market- For information on authorized reprints of articles, contact Jeannette Ciarcia (860) 875-2199 or e-mail [email protected]. ing to draw your WWW.GiURUMELE.Hi2.ROattention. From a consumer’s perspective, the next thing I CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub- would like to see wireless is television, so I can get rid of the rat’s nest of lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at TV, cable box, and VCR (that’s right, despite the rental industry’s insidious Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico $31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico efforts to get me to buy a DVD player by dwindling the VHS selection, I still $55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money order, or check drawn on U.S. bank. use my VCR) cords in my living room. Sanyo and Magis Networks have Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call (800) 269-6301. developed a wireless TV prototype that sounds promising. Something tells Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

me that that TV would sell itself without any fancy marketing ploys, too. 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- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction. The reader assumes any risk of infringement liability for constructing or operating such devices. Entire contents copyright © 2001 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks [email protected] of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO August 2003: Wireless Communications FEATURES

12 Wireless CAN Yard Lamp Control 44 Flexible USB-CAN Bridge John Dammeyer Craig Beiferman Mad Dash for Flash Cash First Prize Winner 20 Palm-Enabled Telescope Steven Pope 50 The WiFi SniFi Sniffing In and Out of Wireless Networks 28 Build Your Own Four-Function Calculator Roy Franz Daniel Ramirez Mad Dash for Flash Cash Contest Entry

COLUMNS

40 ABOVE THE GROUND PLANE 70 APPLIED PCs IR Sensing Mission Possible: Achieve Cheap USB Connectivity Ed Nisley Fred Eady 60 FROM THE BENCH 78 SILICON UPDATE Spotlight on the Renesas Switch Hitter Hitachi and Mitsubishi Market MCUs for Embedded Systems Tom Cantrell Jeff Bachiochi

DEPARTMENTS

4 TASK MANAGER Bulk Be Gone Jennifer Huber

8 NEW PRODUCT NEWS edited by John Gorsky 11 TESTWWW.GiURUMELE.Hi2.RO YOUR EQ edited by David Tweed

94 INDEX OF ADVERTISERS September Preview

96 PRIORITY INTERRUPT Contest Zest Steve Ciarcia

6 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com Our AVR microcontroller is probably 12 times faster than the one you’re using now. (It’s also smarter.)

Introducing the Atmel AVR®. An 8-bit MCU that And when you consider that it can help slash months off your can help you beat the pants off your competition. development schedule and save thousands of dollars in project AVR is a RISC CPU running single cycle instructions. cost, it could make you look pretty smart, too. With its rich, CISC-like instruction set and 32 working registers, AVR comes in a wide range of package and performance it has very high code density and searingly fast execution–up to options covering a huge number of consumer and industrial 16 MIPS. That’s 12 times faster than conventional 8-bit micros. applications. And it’s supported by some of the best development We like to think of it as 16-bit performance at an 8-bit price. tools in the business. With up to 128 Kbytes of programmable Flash and EEPROM, So get your project started right. Check out AVR today at AVR is not only up to 12 times faster than the MCU you’re using www.atmel.com/ad/fastavr. Then register to qualify for your free now. It’s probablyWWW.GiURUMELE.Hi2.RO 12 times smarter, too. evaluation kit and bumper sticker. And get ready to take on the world.

Check out AVR today at www.atmel.com/ad/fastavr

AVR 8-bit RISC Memory Configurations (Bytes) Debug and Processor Package Flash EEPROM RAM Development Tools tinyAVR 8-32 pin 1-2K up to128 up to128 Available Now low power AVR 8-44 pin 1-8K up to 512 up to1K Available Now megaAVR® 32-64 pin 8-128K up to 4K up to 4K Available Now R

© 2002 Atmel Corporation. Atmel and the Atmel logo are registered trademarks of Atmel Corporation. NEW PRODUCT NEWS Edited by John Gorsky NEW TCVCXO The FOX923E is a new temperature-compensated, volt- 75°C. The new TCVCXO’s frequency stability is –2.5 to age-controlled crystal oscillator (TCVCXO) that measures 2.5 ppm over the temperature range and –0.2 to 0.2 ppm only 3.2 mm × 2.5 mm × 1.2 mm, which is half the length over the supply voltage change of 3.0 V ±5%. Pullability of previous models. The significantly reduced footprint and is ±5 to ±15 ppm at a control voltage of competitive pricing makes the oscillator 1.5 ±1 V and input current is 2 mA at 3.0 V ideal for applications where size and cost are (25°C). critical, such as in the portable, handheld, Pricing for the FOX923E with a stability and wireless markets. of ±2.5 ppm and a frequency of 26 MHz The frequency range of the FOX923E is 13 starts at $1.99 in 10,000-piece quantities. to 26 MHz, with a supply voltage range of 2.85 to 3.15 V and an initial frequency toler- Fox Electronics ance of –0.5 to 0.5 ppm at 25° ±2°C. (888) 438-2369 Standard operating temperature is –20° to www.foxonline.com

300- TO 450-MHZ TRANSMITTER IN SOT23 PACKAGE IR TO RS-232 CONVERTER The MAX1472 is a VHF/UHF PLL-based ASK transmitter The IR232 is an infrared-to-RS-232 converter that is housed in a tiny 3 mm × 3 mm 8-pin SOT23 package. The based on the Sony SIRCS protocol of 12-bit control transmitter is perfect for low-cost, high-volume applications codes. The IR232 not only sends and receives control where space is critical, such as security products and remote codes in one of two binary modes, but it also can be sensors operating in the 300- to 450-MHz band. The configured to send predefined character strings to the MAX1472 runs directly from a lithium cell and operates serial port when specified infrared control codes are down to 2.1 V, consuming only 100 nA of current in Standby received. This mode allows it to act as a host to any mode. During transmission, the MAX1472 can output –10 to slave device that can accept RS-232 commands. 10 dBm of power into a 50-Ω load. For a 10-dBm power level, The IR232 printed circuit board assembly contains a the MAX1472 consumes 5.5 mA of current at 315 MHz when 40-kHz infrared receiver module, a high-power using a 50% duty cycle encoding scheme, such as Manchester. Current consumption drops to 3 mA at 0 dBm output. The part can accept data rates up to 100 kbps. After the MAX1472’s ENABLE pin is activated, it takes only 250 ms for the device’s PLL and crystal to settle so the device is available to transmit. The MAX1472 accepts crystal frequencies between 9 and 15 MHz. The MAX1472 uses a crystal-based PLL, so most of the problems of an LC- or SAW-based transmitter are eliminated. The inherent accuracy of the crystal frequency allows for a infrared LED, and a visible LED for confirmation of narrow IF bandwidth in the receiver to improve system sensi- transmissions. It has a true RS-232 interface with a tivity. With a receiver like the MAX1470 or MAX1473, a 9- DE9 connector that matches the pinout on PC-com- dB improvement in sensitivity is possible by narrowing the IF patible RS-232 ports, and can communicate at speeds bandwidth from 600 up to 19,200 bps. to 50 kHz. Improved Its on-board 5-V power supply can operate from a sensitivity translates wide range of input voltages provided through a pin- directly to greater type power jack, and the 5-V supply is available on range or more reliable pin 9 of the DE9 connector to power auxiliary devices. transmissions for your The IR232 is available as a complete circuit board product. WWW.GiURUMELE.Hi2.ROassembly or in an optional ABS plastic enclosure with Prices start at $1.25 infrared window. The circuit board is 2.25″ × 2.25″ × in 1000-piece quanti- 0.75″, while the enclosure is 2.6″ × 2.6″ × 1.1″. ties. An evaluation kit A wall block power supply, an RS-232 cable for con- for the MAX1472 is nection to PC-compatible computer during setup, and available directly from terminal emulation software for the PC are included. Maxim and other The IR232 costs $69, and the enclosure is available authorized distributors. for $10.

Maxim Integrated Products IndustroLogic (408) 737-7600 (636) 723-4000 www.maxim-ic.com www.industrologic.com

8 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com NEW PRODUCT NEWS EMBEDDED WIRELESS COMMUNICATION MODULES SOLUTION FOR SHORT-RANGE RF APPLICATIONS The XE900M second-generation Smart Transceiver and A complete system solution for short-range, unidirec- the XE924M Base Access Point add a number of perform- tional RF communication consists of three microcon- ance and feature enhancements to their predecessors. The trollers with integrated transmitters and two receivers. XE900M and XE924M provide a low-cost and convenient Several products supporting frequency bands ranging from solution to collecting data wirelessly from up to 128 dis- 260 to 930 MHz are now available. By combining the crete nodes located within a 150′ (indoor) radius. rfPIC12F675 microcontroller/transmitter with either the The XE900M Smart Transceiver combines a microcon- rfRXD0420 receiver or rfRXD0920 receiver, users can easi- troller and 900-MHz transceiver in a miniature, dual-in- ly create a wireless unidirectional communication link for line package. It can communicate with another Smart embedded-control applications. The receivers also can be Transceiver or with the XE924M Base Access Point to cre- combined with rfPIC devices and KEELOQ encoders to ate a data collection network. The count-off function has create remote sense and control applications. been enhanced to enable the network hub to quickly check Available in a 32-pin low-profile quad-flat pack (LQFP), the status of the up to 128 network nodes. the rfRXD0420 and rfRXD0920 single-conversion super- The XE900M is also capabable of communicating using heterodyne UHF RF receivers support frequency bands of up to 126 carrier frequencies within the 900-MHz ISM 300 to 450 MHz and 850 to 930 MHz, respectively. The band. The availability of multiple channels reduces inter- devices offer a maximum data rate of 80 kbps, a standby ference problems by permitting a change in the communi- supply current of 100 nA, and operate over a voltage range cation channel if noise levels affect data throughput. of 2.5 to 5.5 V. The active supply currents for the Multiple frequency channels also permit the network to rfRXD0420 is 6.5 to 8.2 mA depending on the low-noise include more than one Base Access Point. Multiple Base amplifier (LNA) setting, and 7.5 to 9.2 mA for the Access Points operating on different frequencies can rfRXD0920. extend both the distance and number of nodes within the The rfPIC12F675 is a 20-pin microcontroller that feature network. The Sensor-On-Air function allows two analog an integrated UHF RF transmitter. Output power for the inputs and four digital I/O lines to be monitored and/or transmitter section is specified at 6 dBm for increased manipulated by the Smart Transceiver’s communication range, and it is available in three frequency ranges: 260 to controller. Nodes can be easily added to the Base Access 350 MHz (rfPIC12F675K), 390 to 450 MHz (rfPIC12F675F), network without any additional hardware installation and 850 to 930 MHz (rfPIC12F675H) with a maximum other than the installation of an XE900M Smart data rate of 40 kbps. A standby supply current of 100 nA Transceiver into the new equipment. and operating voltage range of 2 to 5.5 V make the device suitable for low-power battery-operated applications. The microcontroller features a 14-bit instruction set with 1.8 KB of flash program memory, 64 bytes of RAM, and 128 bytes of EEPROM for nonvolatile storage. Additional features include an analog comparator and four channels of 10-bit ADC, making it easy to interface to a sensor for wireless sensor applications. Pricing in 10,000-unit quantities is $2.55 each for the rfRXD0420 and rfRXD0920, and $2.03 for the rfPIC12F675.

Microchip Technology, Inc. (408) 792-7200 The XE924M Base Access Point combines a 900-MHz www.microchip.com transceiver and a communication controller housed in a miniature, dual-in-line package. The XE924M eliminates dial-up hardware redundancy, and therefore reduces both the initial installationWWW.GiURUMELE.Hi2.RO cost and continuing operating costs. Agency approval is simplified because the integration modem includes transferable Part 68 Approval and is a UL- recognized component. The 900-MHz transceiver complies with FCC Part 15 rules. The unit price of the XE900M Smart Transceiver is $39, and the XE924M Base Access Point is $59 in OEM vol- umes.

Xecom, Inc. (408) 942-2200 www.xecom.com www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 9 NEW PRODUCT NEWS EMBEDDED COMPUTER HOOKS INTO WIRELESS NETWORKS The SBC1390 is a powerful controller in a PC/104 foot- The CompactFlash connector can accept print that will communicate with other computers in a cards from 16 MB to 1 GB in size. The unit comes wireless network. In addition to PC-compatible features— installed with a ready-to-run firmware system. This such as four serial ports, three timer/counters, and two firmware includes a complete industrial BIOS, board setup cascaded interrupt controllers—the new model can also screens, application download utilities, and a DOS-compat- include an on-board PC card interface that accepts a WiFi ible operating system that boots immediately upon power- (IEEE 802.11b) wireless Ethernet card. up. Alternatively, the board may be configured to boot 32- In addition to the wireless network capability, the bit operating systems. SBC1390 has other features that make it a full-blown The following are options: a PC card interface, a WiFi embedded PC. The SBC1390 is PC card, CompactFlash, implemented with the Intel increased DRAM, and an 386EX processor, which offers enhanced accuracy real-time speeds of 25 or 33 MHz. With clock. An industrial version up to 32 MB of SDRAM, a with –40° to 85°C operation is CompactFlash connector, a syn- also available. chronous serial port, a watchdog The basic SBC1390, with timer, and AT-compatibility, 16 MB of DRAM and 1 MB of high-performance control sys- flash memory , costs $315. A tems can be developed as single- free development kit is provided board solutions. If needed, I/O that includes cables, sample soft- expansion can be added to the ware, and full documentation. SBC1390 through PC/104 cards. In its stack-through version, the Micro/sys, Inc. SBC1390 is ideal for plugging (818) 244-4600 into a custom OEM I/O card. www.embeddedsys.com

WWW.GiURUMELE.Hi2.RO

10 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com T e s t Yo u r EQ CIRCUIT CELLAR— Edited by David Tweed

Problem 1—Consider the logic expression Problem 3—A simple electronic combination Y = A.B.C! + B.C + C.A!. This is called the sum of lock has four toggle switches, each of which products (SOP) notation. The normal way to may be either up or down. One of the switches implement it would be to use AND, OR, and NOT is disconnected and has no effect on the lock, gates. But it is sometimes required to implement but you don’t know which one. What is the such expressions using only NAND or NOR gates. smallest set of combinations you can devise that Explain how would you implement it using only is guaranteed to open the lock? NAND gates. The aim here is to guess the NAND gate structure required to implement the expres- Contributed by Eddie Insam sion by simply looking at the expression with no calculations involved. Contributed by Naveen PN Problem 4—If two of the four switches are known to be nonfunctional, how many combina- Problem 2—What 1-bit changes in the following tions must be tried in order to open the lock? circuit may cause glitches? Contributed by Eddie Insam A! B! C! A! F C A B What’s your EQ?—The answers are posted at www.circuitcellar.com/eq.htm Contributed by Naveen PN You may contact the quizmasters at [email protected]

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 11 FEATURE ARTICLE by John Dammeyer Wireless CAN Yard Lamp Control

In addition to providing a sense of security from intruders, sensor-controlled yard lamps make it safer for you to walk on your property after dusk. But they can pose problems, particularly when a flash triggered by a nocturnal animal awakens you from a dream. Other systems like solar-powered lights have problems, too. Wouldn’t it be nice to have more control over the technologies you use? Check out the CANRF module John built for yard lamp control.

I have a few PIR motion sensor-con- something, or somehow involve a were a number of wireless bridge trolled flood lamps that can light up a computer in the simplest task, I’ll do devices on the market, there wasn’t a driveway when a warm body is within it. I’ve been working with controller wireless CAN network. One year later, I range. The lamps work well, but they’re area network (CAN) systems for more had a wireless CAN system up and run- often triggered by false signals such as than 10 years, and a peer-to-peer net- ning, as well as a fairly powerful activ- passing cars and small animals. They’re work seems well suited for lamp con- ity board for evaluation and testing. also extremely bright, which is useful trol. However, the idea of stringing At that point, I started looking for on some occasions but detrimental on low-voltage power cables around my problems to fit my solution. I discov- others. They can actually impair my property, and a second pair for the net- ered that the need for a true peer-to-peer vision when I’m walking the dog. work, seems like overkill—not to type of system was minimal. Many con- Alternatives to flood-lamp lights are mention it isn’t nearly as entertaining trol systems that use CAN operate in small 12- and 24-V yard lights, some as a wireless control system. master/slave mode and require at least of which are solar-powered LED units When I first designed the CANRF one master at some point during the life that recharge during the day. However, modules, I didn’t have a specific applica- of the system to get things going. if you experience a few cloudy days, tion in mind, although a few of my cus- Wireless systems in the Industrial/ the solar-charged lights become non- tomers were interested and had ideas Scientific/Medical (ISM) bands suffer operational. In addition, low-voltage for the product. After I had completed a from low-range, fading, and multipath systems and solar-powered LED lamps survey, I discovered that although there interference. Everyone seems to want are dim, so they’re only useful after an extra 50 m more than possible my eyes have adapted to the darkness. when transmitting within MOT or After I thought things over, I decided FCC power emissions regulations. And that I need low-voltage garden lights that yet, tying in a garden path lighting sys- use more than 7 W, generate adequate tem with a wireless security system lighting, and consume current only when seemed like an appropriate way to use necessary. Ideally, the lights should be a peer-to-peer wireless network. able to sense a person’s presence, dis- Note that my yard is large enough that creetly light the path without impairing there are locations where RF modules anyone’s vision, and shut down when cannot see each other. Even a centrally the person leavesWWW.GiURUMELE.Hi2.RO the vicinity. located master wouldn’t work because of PIR-based flood lamps with low- the trees and topography, which would wattage bulbs would solve the problem, block the line of sight for the signals. but they can be troublesome: unless you open your curtains and look outside, you CAN BASICS may not notice a visitor or intruder. If Photo 1—The module is mounted on a 2.625″ × 3.75″ The CAN protocol uses carrier sense possible, such a system should also act metal plate. The battery holder for the four AA cells is multiple access with collision recovery as a security system capable of notifying screwed to the bottom, and the antenna is a quarter- (CSMA/CR), which allows multiple wavelength piece of solid 22-gauge wire. Ultimately, the you when someone enters your property. devices to access the bus at the same unit will be placed in a cast aluminum enclosure with One shortcoming of mine is that if I an external Rubber Ducky antenna. I borrowed the time. Thus, the bus must be able to can find a complicated way of doing LED array from another project. handle two or more simultaneously

12 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com The receiver interface always moni- Listing 1—The general-purpose I/O line is used as a simple UART with a short start and stop bit identifying tors the signal levels on the bus. The the start of the bitstream. With a storage scope triggering on the rising edge, the 8 data bits are easily CAN processor expects to see a domi- determined. This type of debugging is especially useful for battery-operated projects that cannot keep the in-circuit debugger active while they sleep. The extra NOPs are there to make the highs and low nant when it asserts a dominant; it symmetrical. anticipates a recessive signal level when it stops driving the bus. If the void receiver reads a dominant during the ReportByte(int bt @ local1) { int i @ local2; transmission of a recessive, then there GP_BIT = 1; is either an error in its driver or anoth- GP_BIT = 0; er device is asserting a dominant. for (i=0; i<8; i++) { The ISO11898 CAN bus is defined by if ( bt < 0 ) { NOP; NOP; a pair of signal wires that are held at GP_BIT = 1; 2.5 V relative to ground for a recessive NOP; NOP;NOP; signal. The line labeled CAN_H is } pulled high to a level near 4.5 V, and the else { GP_BIT = 0; CAN_L signal is pulled low to a level NOP; NOP;NOP; NOP; near 1 V for a dominant level. There are } a number of different types of drivers bt <<= 1; targeted at solving various speeds, bus } NOP; NOP; lengths, and power supply needs. You GP_BIT = 0; should consult the various datasheets GP_BIT = 1; to determine which ones are suitable. GP_BIT = 0; Like Ethernet, the CAN processors } first listen to the bus to determine if it is available for message transmission. If transmitting devices. The major differ- device wishes to transmit a logic low the bus appears free, it asserts a domi- ence between Ethernet and CAN is (e.g., a start bit), it turns on its transis- nant start bit and the rest of the header that Ethernet uses collision detection tor, which pulls the common signal line bits. If another node needs, by chance, whereas CAN uses collision recovery. low (dominant). Turning off the transis- to send a message and the test for the The terminology for CAN signals is tor brings the bus idle, which is equiva- available bus happens at the same recessive for a logic high and dominant lent to a logic high. Two or more nodes time, the two messages would collide. for a logic low. Look at it as if all the turning on their transistors would not The moment the Ethernet transmit- nodes are wire ORed together using damage the others, because the signal is ting node detects a signal level that’s open-collector transistors. When a already pulled down as low as possible. different from what it is transmitting, it

WWW.GiURUMELE.Hi2.RO

Figure 1—The interface to the CANRF module is simple. The processor is marked as a PIC12C509, but you can use a PIC12C508 or PIC12CE674. You can install a 0-Ω R9 to allow for processor control of the power supply to cause the unit to power down and draw only microamps. Or, remove R9 and connect the A/D channel 0 of the PIC12CE674 to a temperature sensor via J2.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 13 stops the transmission and be able to detect a valid signal. delays (a random period of time) CAN bit stuffing ensures before trying again. The other that there are never more than node will do the same. As long 5 bits of any polarity. If a string as the delay is different between of 8 zero bits needs to be trans- the two, both messages will be mitted, the first five zeros will subsequently transmitted with- be followed by a single high- out a collision. If the bus is level stuff bit and the next busy, the throughput may be three zeros. If the receiver sees drastically effected because five zeros in a row, it automati- numerous nodes collide, detect cally removes the next oppo- the collision, and then retry a site-polarity bit, assuming it’s a short time later. In the worst stuffed bit. However, if the fol- case, all of the nodes are con- lowing bit is still dominant, a stantly colliding and retrying. stuff error is flagged. The new 802.11-based wire- Photo 2—I have a fairly large yard. The nodes are represented by small Bit stuffing helps keep the RF bitmap images that are loaded depending on the status of the node. The left- less systems use a collision most node has its switch closed. The other nodes are all turned on. The Delphi receiver’s data slicer roughly cen- arbitration method that enables application also responds to mouse clicks on the node images and can send tered on the average signal level. them to not only listen for a messages as if they came from that node, which is extremely useful for testing. The error flags should destroy cleared bus but also wait a short badly formed messages. [1] In the time before listening and transmitting. that I’ll soon describe in more detail. relatively quiet environment of a CAN That goes a long way toward reducing Although I said robust, I wasn’t bus transmission line, the occasional collisions but can still leave the bus being totally truthful. CAN devices noise spike or burst will have little free for certain periods of time. Note have a clever method of ensuring that effect on overall communication. Errors that 100% utilization is impossible. defective nodes don’t become babbling reduce the determinism of the individ- CAN implements a collision-recovery idiots. They have several weighted ual messages. An ACK from a node scheme by considering a dominant bit error counters that track transmit and doesn’t automatically imply that the in the arbitration bits of the header as receive errors. To prevent the long intended receiver obtained the message. higher priority than the recessive bits. stream of bad messages that can occur All nodes that correctly received the As soon as the CAN processor detects a when a low-priority node holds off an message issue an ACK. dominant where it expects a recessive, import message from a high-priority Another key variable dictating the it aborts the rest of the transmission node, an error flag can destroy a bad range of OOK-based RF systems is the and switches to Receive mode. After the message. Too many transmit errors, signal-to-noise ratio (SNR). When no one current message is complete, the node and a node’s bus will go off, requiring is transmitting, the signal level detected will try again. The message still may be intervention from the processor to go by the receiver is called the noise floor. delayed but based only on the relative back to active bus activity. It doesn’t matter if the receiver has a priority of the arbitration field. An error flag is a sequence of six sensitivity of, say, –115 dBm when the In place of two wires with drivers cre- dominant bits that creates a bit stuff noise floor or background noise is ating dominant and recessive voltage lev- error. The bit-stuffing technique is an –70 dBm. However, this often is an els, imagine substituting an RF frequen- added benefit for RF transmissions. In average, and it doesn’t address short cy for a dominant bit and no frequency order to properly condition the bit- noise spikes above the noise floor that for a recessive bit. The bus would be idle detection logic inside the RF receiver, a may fool the receiver into thinking when one isn’t transmitting. A dominant comparator called a data slicer is condi- that a message has begun. would occur when the transmitter is on tioned to have the threshold for deter- If the CAN receiver section supposes long enough to be interpreted as a signal mining a one or zero set at 50% of the that a start bit has occurred and then above the RF noise floor. That’s not signal level. Ideally, there should not be sees the equivalent of six consecutive unlike the technique that Guglielmo a long string of ones or zeros, or the recessive bits (no signal after the noise Marconi used toWWW.GiURUMELE.Hi2.RO transmit signals across average signal level will drift upwards pulse), it will think that the message the Atlantic Ocean. In radio parlance or downwards and the data slicer won’t has a bit-stuff error and transmit an it’s called on-off keying (OOK). By treating the CAN signals as the Listing 2—The MAPCAN commands can be found in byte 1 of the 8-byte CAN message. Byte 0 is the destina- simple absence or presence of a radio tion ID, and bytes 2 through 7 hold command-specific data. In the case of the motion forward command, byte 2 frequency carrier, I have a simple and holds the lamp and switch status, while bytes 3 and 4 hold the originator’s ID and the message lifetime. somewhat robust peer-to-peer network, because I don’t need a master polling #define UNIT_STATUS 0x10 //I/O status heartbeat message #define MOTION_SENSED 0x11 //Motion detected and waiting for a response. This is espe- #define MOTION_STOPPED 0x12 //No motion anymore cially important if the master cannot #define MOTION_FWD 0x13 //Someone else’s MOTION_SENSED message reach the node, which is a situation

14 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO error flag of six dominant bits. Next, could happen that one node issues the at the same time, it listens during the it will increment the transmit-error ACK and the rest do not. For CANRF recessive bit windows. If it sees a domi- counter by eight. This scenario can hap- to be robust, the higher-level protocol nant when it expects a recessive, it pen numerous times until the receive- (HLP) must handle missing messages. relinquishes the bus and starts receiving error counter reaches 128, at which Soon I’ll cover message forwarding, the message. At the end of the message point the device becomes error passive. which addresses the problem. it issues an ACK in the ACK slot if the In other words, it won’t produce domi- To summarize, the CAN device is message was correctly received. Then, nant, or active, error flags anymore. always listening for a start bit. It detects it tries resending its own message. The downside is that if a real mes- the edge, verifies a short time later at sage is received with bad data, an active the sample point that the bit is a domi- HARDWARE error flag won’t abort it early. Instead, it nant, and then starts accumulating the For small projects, the absolute cost has to run to completion without any identifier and data-length code bits. By of the processor rarely justifies the extra nodes issuing an ACK. Worse yet, it chance, if the device starts transmitting software development that may be required to fit the application in a restricted environment. The PIC12C509 is one of those environments. Normally, I would pick the largest device available (e.g., a PIC16F877) so that the code, data, or stack size would- n’t be an issue. But for this project, I thought I’d try to make the application as compact as possible, so I chose a simple eight-pin processor that could be upgraded with an A/D converter and EEROM. (I also had five PIC12C509 devices in my prototype tray.) One of the six modules I built is shown in Photo 1. Figure 1 is the schematic. By the time I had allocated pins for the SPI interface and interrupt line, I had only one line left for I/O. However, the MCP2510 CAN device used on the CANRF has five user-definable pins that can be defined as three inputs and two outputs. I designed the board so that the one leftover pin on the PIC could be used for digital input or out- put or as an analog input on one of the more sophisticated eight-pin processors like the PIC12CE674. Speed or timing accuracy weren’t important in this application, so the internal oscillator (4 MHz) and reset were enabled. That came back to haunt me later on. The standard SPI MOSI, MISO, CLK, and CS signals constitute the brunt of the interface. I also chose WWW.GiURUMELE.Hi2.ROto use the interrupt from the MCP2510 as the signal that a message had arrived rather than having to poll the registers inside the device. The two MCP2510 outputs drive small FETs to create high-current sink- ing outputs for LED arrays or relays. The inputs are filtered through an RC network. The free PIC I/O pin is used as a debugging output to blink an LED or to provide a bitstream with embed-

16 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com ded digital information (see Listing 1). on the features implemented on the The ReportByte() function generates core . Bluetooth modules a short pulse and then longer 0/1 pulses that incorporate the 4-MB flash ROM representing the value of the byte fol- have enough space to accommodate an lowed by another short end-of-frame end user application. 802.15.4 is expect- pulse. This function lets you examine ed to use 35 KB of code. Both protocols program variables and follow move- have many advantages over CAN, but ment through the various states or dur- CANRF seems to have a few of its own. ing the parsing of the CAN messages. With a few carefully placed macro def- Because of the two-level hardware initions, I’ve been able to make the code stack in the PIC12C509, most of the portable between the PIC12C509 and code is in line, and there are only a few ’12CE674. The ’12CE674 has two times function calls, which make the code size Photo 3—The CANRF activity kit logs messages at the code space as well as EEROM and larger with a lot of duplication. However, 119 kbps from the serial port to the PC. A flag set in an ADC. And, it uses the PIC14xxxx the SPI bus CANRF support code ended the EEROM causes the red LED to blink when a mes- architecture. Thus, it will be possible, up using only about 539 words of code sage is received. You can program the push button to because of the larger stack and more send a custom CAN message, which I use for an All on the ’12C509 and 449 words on the Lights On command. The activity board’s firmware subroutines, to shrink the code and ’12CE674. Filter setup will increase the allows for full access to the MCP2510 CAN device. I support an analog channel on GP0 and code size (as will the application), but found it handy for concept testing. EEROM for parameters and node ID. this is impressive nonetheless because in this small code size, there is a wireless “Wireless Data Link” (Circuit Cellar MESSAGE HOPPING 20-kbps peer-to-peer network with retries 131). When I compiled the sample code My property has areas that make and CRC checks on the messages. Even from their article, the core software was low-powered, line-of-sight transmis- better, the entire application fits within 588 words for a master/slave network sions difficult. Photo 2 is an aerial the 1024-word code space. running at 600 bps using the 20-MHz view of my lot. The small icons repre- Contrast the code space with the PIC16F877. Although Bluetooth is far sent locations where I want to mount wireless data link described in Tom more sophisticated, Bluetooth can take CANRF transceivers. Dahlin and Donald Krantz’s article, from 200 KB to over 2 MB depending A program written in Delphi demon-

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 17 strates an individual light sensor send- announcing the status of the inputs and and turns on its own lamp. It sets bit 7 ing messages (a mouse click on the outputs. The message has a lifetime of of the I/O status byte to show that the icon) to the other lights to turn on. one, so it is sent one time to each one lamp is on (based on a received mes- I’ve also written serial port interface (task 0) and nothing else is done with it. sage) and then forwards the message. code, which parses the CAN messages If a change of state occurs (e.g., a Finally, node 4 sends out a new sta- reported by the CANRF activity board switch closure or output change), a tus message showing that the switch and changes the icons representing the MOTION_SENSED or MOTION_STOPPED reopened and the lamp is still on. This transceivers, sensors, and lamps (see message is sent with a lifetime of five. message has a lifetime of one, so it Photo 3). The activity board reports a All nodes receiving this message check won’t be forwarded by anyone else. CAN message in the following format: the sender’s ID value to determine if Each lamp is run on a timer. Thus, if the number is within a range of their the motion sensed or forwarded mes- Time, ID, length and data bytes. own ID. If the sender’s ID fits within sages stop, the lamp will turn off by [RSSI] that range, the lifetime is decremented itself shortly thereafter. 00:00:16.22 ID:226 DLC:8 20 10 by one and the message is reissued as I’ve obviously run into restrictions. 70 26 03 01 10 61 [458] a MOTION_FORWARD command. I’ve had to think carefully about how to A node receiving a MOTION_FORWARD assign IDs for each of the nodes. Ideally, The 11-bit ID is broken into groups executes the same tests along with an each node should be within range of at as defined by the MAPCAN protocol, additional test against the original least two other nodes, and those nodes which stands for modular automation sender ID value. The originator of the should be within a numeric range of protocol for the controller area network. MOTION_SENSED message isn’t allowed two away from the node. That means The first two bits of the message ID to forward it, but everyone else is. This node 2 should be placed close to nodes 1 (bits 10 and 9) define the type of message creates a flurry of messages that will through 4. Node 4 should be close to organized in the same type of ring struc- ultimately touch every node in the net- nodes 2 through 6, and so on. ture as a real-time operating system. The work. As long as a node can see at least An unexpected issue was that of the highest priority, ring 0, is the control (or one other node, odds are that it will time it takes to transmit a single mes- signal) message represented by the 0b00 receive messages from the others. sage, and the time it takes to retrieve it value. The next priority ring holds the Listing 3 is the entire message from the MCP2510 via the SPI interface. devices that have the first two bits set to sequence, which demonstrates how The 4-MHz PIC12C509 doesn’t have a 0b01. Tasks, or threads, have the 0b10 device 5 senses the switch closure, built-in SPI controller, so I needed to bit value. Block transfers, or files, are the turns on its own lamp, and sends out bang it. It turns out that it takes about lowest priority with a 0b11 value. the status message with a lifetime of 500 µs longer to detect and pull out a Bit 8 is defined as a client/server bit five. Device 4 receives that message message than it takes for the message to that represents the direction of be transmitted. That’s because I the message. The final eight bits also need to check overflow and Message type have different values depending 00 Control or signal transmission-complete flags, on the type of message. Devices 01 Device acknowledge the interrupt, and 10 Task break the 8-bit field into two 11 File or block enable the receiver. The inter-

4-bit nibbles. The most signifi- Direction (tt is the message type) rupt routine also performs some cant nibble identifies the type or tt1 Client of the store and forward filtering. tt0 Server class of device while the lower With this simple application, Node: device type (01) direction (d) nibble is the device number in 01dccccnnnnn overruns are a fact of life that class. Tasks, or threads, cccc Device class because a single message could 0 User defined use all 8 bits to identify the 1 Keypads, keyboards, and switches generate an immediate response task/thread ID, where zero is a 2 I/O bit devices from four nodes that generate 3 User defined global ID to which all devices 4 Analog-to-digital devices another flurry of messages back 5 User defined can respond (see Figure 2). 6 Counter devices to back. It’s a given that this Messages in MAPCAN use the 7 Digital-to-analog devices simple application will lose WWW.GiURUMELE.Hi2.RO 8 User defined first data byte as the destination 9 Encoder devices messages, yet it works well. If I 10 Motor controllers ID and the second byte as a com- 11 User defined were to use a processor with a mand. A destination zero means 12 PWM Devices hardware SPI module, reliabili- 13 Display devices like LED or LCD all devices can react to the com- 14 User defined ty would improve. 15 User defined mand in the second byte. Node: task or thread I’ve placed the units in my Refer to Listing 2 for the com- x0dnnnnnnnn yard and tested the messaging. nnnnnnnn Node ID for originator of control or task message. mands for the garden light sys- I have to rely on the Delphi tem. The MOTION_FWD message Figure 2—Organized like the ring structure of a multitasking executive, the application to know if all the command makes the entire sys- MAPCAN message IDs are broken into bit fields that make use of the lights turn on, because I cannot inherent priority structure of CAN messaging. Control or signal messages tem work. Every 2 s each node have a higher priority than device messages. Server messages will win see them in the 10 s that they issues a heartbeat message arbitration over client messages. Devices outrank tasks and threads. remain on when a single unit is

18 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com Listing 3—This is a sequence of messages logged from the activity board. Devices 4 and 5 each send their status message. Device 4 then forwards the message from device 5 with the last byte, the message lifetime, decremented by one. When the message lifetime equals one, it’s no longer forwarded.

224 5 20 10 70 24 01 //Motion status from device 4 225 5 20 11 61 25 05 //Motion sensed, switch closed, lamp on from device 5 224 5 20 13 E1 25 04 //Motion forward from device 4 224 5 20 10 71 24 01 //Motion status, switch open, lamp on from device 4 | | | | | | | | | | | | | --- //Message lifetime | | | | | --- //Message originator | | | | --- //Bit 0 = LED status, bit 4 = switch status | | | --- //Command | | --- //Destination class 2, all devices | --- //Five bytes in CAN message --- //ID is device type, device class 2, device ID 4 and 5

pulsed. If I leave the switch input range. Then, they’d issue sync up to a closed, a walk around the yard shows clock message, receive a permanent ID all lights on. The next step is to find from a master, and go to sleep. As inexpensive PIR motion sensors, build always, some sort of node location iden- weatherproof housings, and run the tification would be required in order to nodes over a longer period of time. display the device’s location. I

PEER INTO THE FUTURE John Dammeyer earned a B.S. from the The CANRF peer-to-peer environment University of Alberta after studying is suitable for a large node system in both computer science and electrical which many of the nodes are out of engineering. He has been designing and range. Data acquisition systems that writing software for embedded systems cover a large physical area can be tied for 20 years and CAN bus systems for together inexpensively. Using the the last 11 years. In his spare time, he ’12CE674, I could program a unique ID enjoys working in his machine shop in the EEROM rather than compile each and sand-casting aluminum and of the nodes with a hard-coded ID value. bronze bits for his sailboat. You may The analog channel on the 12CE674 reach John at [email protected]. could be connected to an LM235 tem- perature sensor and used to acquire PROJECT FILES localized temperature readings over a wide area. One idea would be to use To download the code, go to these modules in a vineyard to detect ftp.circuitcellar.com/pub/Circuit_ frost and turn on sprinkler systems to Cellar/2003/157. prevent the grapes from freezing. Because the messages would be for- REFERENCE warded around the wide area network, [1] J. Bachiochi, “The Missing a centralized master could monitor (Wireless) Link,” Circuit Cellar and log the vineyard over time. 132, July 2001. To save power,WWW.GiURUMELE.Hi2.RO the large network tem- perature profiling system could shut SOURCES down and turn on only once per minute. PIC12C509/C508/E674, MCP2510 To make sure all nodes wake up at the CAN Device same time, additional software—used to Microchip Technology, Inc. synchronize the TOD clocks—could cir- (480) 786-7200 culate before a sleep is allowed. New www.microchip.com nodes installed in the system would stay awake until they start receiving mes- CANRF Module sages. They could determine which IDs Automation Artisans, Inc. are not being used within their local www.canrf.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 19 FEATURE ARTICLE by Steven Pope Palm-Enabled Telescope Why can’t a Palm Pilot talk to a telescope? That’s the question that prompted Steven to attempt adding an IR port to his telescope’s control unit. His effort has proved rewarding. Not only can he control his telescope with his Palm, but he has also created the possibility for Internet access.

Galileo achieved lasting fame by Of course, you may be wondering the second star and has you make fine being one of the first to turn a tele- why someone would want to use a adjustments. At that point, the Auto- scope toward the heavens to have a computer to control a telescope. After star can automatically point toward closer look. Such innovative applica- all, you just point and look, right? Well, any of several thousand objects it has tions of technology were his specialty, that’s true if you know where you want listed in an on-board database. and I wonder what he would do with to look. But many interesting objects in The trouble is that, like so many today’s telescopes. Modern telescopes the night sky cannot be seen with the product designs, usability was sacri- are smaller, higher powered, and have naked eye, which makes it difficult to ficed to save cost. As you can see in computer-controlled pointing, but they figure out where to point the telescope. Photo 1, the controller unit has a sim- could still use the hand of a master. Fortunately, astronomers have cata- ple two-line display and a numeric The controls on my Meade ETX-105 loged the positions of sky objects so keypad as its user interface. It uses a telescope (with Autostar controller), you can find them. Unfortunately, the nested menu, which gives you access for instance, include a sophisticated position is given in the celestial coordi- to all of its operating modes as well as star location and tracking algorithm. nates of declination and right ascen- the thousands of items in its star cata- Unlike my Palm Pilot, however, the sion, the latitude and longitude of the log. This is an inconvenient interface user interface for the telescope is a sky, which remain fixed in space primitive set of buttons and a two-line while the Earth moves underneath. display. What would Galileo do? I like The Meade telescope’s Autostar to think he would do what I did, controller helps locate objects in the which was to create an adapter that sky by compensating for this motion. enables a Palm to run the telescope. The compensation depends on your location as well as the Earth’s daily and annual movement, so the Autostar needs to know latitude and longitude as well as time and date. With this information, and a little alignment, the Autostar can point the telescope to any celestial coordinate. The alignment process is relatively simple, at least in concept. You enter WWW.GiURUMELE.Hi2.ROthe day and time, your location, and choose one of the alignment modes. The two-star alignment mode, for instance, picks two easily identifiable stars as its reference marks in the sky. With the alignment mode picked, the telescope points itself at the first star, and then you make fine adjustments Photo 1— The Autostar controller provides many useful to bring the star to the center of the Photo 2—The complete system has three parts: the functions for controlling the telescope, but its user inter- telescope with Autostar, a Handspring handheld (run- face is awkward. It has a two-line display and a data- telescope’s field of view. When you’re ning Palm OS), and the bridge module. The module is base of more than 1000 objects to select from. done fiddling, the telescope moves to housed in the box at the bottom of the photograph.

20 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com for entering the date, time, and loca- TWO SOFTWARE MODULES tion, and it’s extremely clunky when The hardware was the simple part. In trying to find an object in the data- order to make the bridge module work, I base. Scrolling two lines at a time needed to develop two sets of software. through a list of thousands of stars is One set runs on the eZ80 and handles not my idea of usability. the exchange of information between What my telescope really needed the Autostar and the IrDA link. was a graphical user interface that Commands and responses follow the made it simple to find what I was look- Meade telescope serial command proto- ing for. Automating the entry of set-up Photo 3—By looking inside the box, you can see the col, which functions like the old AT Webserver module and the secondary board under- information also seemed like a good neath it. The module contains the core processor, mem- command set for modems (and bypasses idea, because I can hardly keep track of ory, and IrDA circuits. the annoying nested menus). The other time much less my latitude and longi- software runs on the Palm and provides tude. The Autostar includes an RS-232 number of other features that would be the user interface as well as the inter- port for using a laptop computer to useful for this and future projects. For face to the GPS receiver. The Palm is handle the interface, but I didn’t want instance, the eZ80 offers an RS-232 port the master controller, which means that to have cables that I could trip over in and an I2C interface, which allow the the Palm initiates all communication the dark connecting my laptop to the bridge module to connect to a number of between the telescope and user. The telescope. With my luck I’d trip, pull different displays if I want to give the telescope does not send messages the telescope over, crash into the com- module its own user interface. The without a command from the Palm. puter, and destroy them both. eZ80’s real-time clock allows the mod- Of the two software modules, the ule to maintain time of day, eliminating eZ80’s is the simplest. The eZ80 takes PALMING THE PROBLEM one manual step in the telescope’s setup. a command coming over the IrDA link As I thought things over, I realized The processor also has a large address and passes it to a routine that reformats that my Palm personal organizer could range (up to 16 MB), which will come it into an Autostar message. It then serve as the computer interface and in handy as I keep adding functions. completes the operation by passing the connect to a GPS receiver to automati- Another important reason for choos- message to the Autostar through the RS- cally determine the viewing location. ing the eZ80 processor is that it is avail- 232 link. It takes responses from the The Palm also offered a wireless able in fully formed modules with a Autostar and passes them back to the infrared IrDA port for communicating complete development tool package. In IrDA link. One other note: when the with remote devices. That would solve this case, I chose the eZ80 Webserver eZ80 firmware powers up, it blinks the cable problem, if the Autostar also module (eZ80L925048MOD), which the status LED hanging on JP2 pin 1, had an IrDA port. It didn’t, so I decid- comes with on-board IrDA transceivers reminding you that the date, time, lati- ed to build one. and an Ethernet port, 1 MB of flash tude, and longitude have not been set. The overall system design is shown memory, 24 general-purpose I/O lines, After you send this information from in Figure 1 with the completed module and a system-expansion port for con- the Palm to the eZ80, the status LED and telescope shown in Photo 2. I creat- necting other hardware. The module’s ed a bridge module with an IrDA port software development support includes that connects to the Autostar controller a full tool suite with a flash memory Motor drive interface Meade and receives its commands from the loader, debugger, compiler, assembler, ETX motor drive Power to Palm. The module allows the Autostar and application examples. The software Autostar on this cable to function normally as a handheld package also includes Internet software 12-VDC Input Battery pack controller, but it adds the ability to that I will use for future enhancements. or wall adapter send commands from the Palm, as well. The Webserver module needs a little Meade Autostar Zilog’s I had a number of requirements to bit more circuitry in order to serve as RS-232 module Interface meet with this module beyond its the bridge between the Autostar and ability to offer an IrDA interface: it Palm. The additional circuits, shown Ethernet WWW.GiURUMELE.Hi2.ROGPS option had to be small, low power (it runs on in Figure 2, are on a PCB with pins IRDA Wireless access the same battery power as the tele- that mate with the Webserver mod- point (802.11 or Bluetooth) scope), and inexpensive to build and ule’s expansion sockets and provide RS-232 Palm OS develop software for. I also wanted back-up batteries, voltage regulation device some expansion capability for adding for the Webserver module’s power, and Any ’Net-based client: more interface options in the future. RS-232 drivers for the serial port. I Tungsten C Pocket PC, Mac Linux, or Window I chose the Zilog eZ80 as the module’s also needed to relocate the IRDA core processor because it provides the transceiver from the eZ80 module to two main features I wanted, an IrDA the front of the enclosure and add a Figure 1—The bridge module attaches to the Autostar through its serial port and receives infrared signals port and an Ethernet port (for future red IR window. The complete assem- from the Palm. It formats messages for the IrDA link expansion). In addition, it includes a bly is shown in Photo 3. using a protocol designed to ensure message delivery.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 21 stops flashing and stays on. the first nibble set to zero. The datastream over the Thus, an attempt to trans- IrDA interface is different mit 0x04 0xF3 0x06 would from the Meade protocol. be sent as 0x04 0xF2 0x0F The first difference is that 0x03 0x06. This minor refor- messages passing over the matting, along with the IrDA link include a com- framing elements, help mand code at the begin- ensure reliable communica- ning and add a checksum tion over the IrDA link. followed by end-of-mes- The Palm software sage code at the end, fram- includes an application pro- ing the telescope’s protocol Photo 4—You can activate the telescope software by tapping the Galileo icon, which gram and the IrDA commu- string. The eZ80 uses the takes you to the Welcome screen. The main control screen, shown on the far right, nication program. I used the command code to deter- emulates the functions of the Autostar controller. Metrowerks CodeWarrior mine the start of a message for Palm OS software devel- coming over the IrDA link and the IrDA link. Any message that includes opment tool (V.7.0) to create the Palm checksum to verify that the message these values in the datastream has to code. You may download the source arrived correctly. If there is a message be modified. When sending data con- code from the Circuit Cellar ftp site. error, the eZ80 will not acknowledge taining a reserved value, the eZ80 or The software targets the Palm OS the message and will throw it away. Palm (whichever is sending) inserts a V.3.5. The code will not work with The other difference is that the 0xF2 command to tell the receiver later versions of the Palm OS because binary values 0xF0 through 0xFF are that something is up, and then breaks of a change Palm made to the IrDA reserved as command codes in the the offending data into two bytes with Enable API call in version 4.0. The

WWW.GiURUMELE.Hi2.RO

Figure 2—The bridge module consists of a manufactured processor board and additional circuitry. The additional board provides RS-232 interface signals as well as voltage regulation for the module.

22 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO new call causes a hardware conflict in through the Palm screen. In Focus database requires a lot of tedious scroll- this application, so if you want to use mode, you can control the telescope’s ing. The Palm’s pull-down menu inter- the later version of Palm OS, you’ll focus motors at one of two speeds. face makes finding an object in the need to make an assembly routine for Another feature of this screen is the database a simpler, more pleasant task. the Palm to bypass the API call. pull-down selection menu. Tapping on the top bar of the screen will bring up COMPENSATING FOR IRDA THE PALM APPLICATION the menu. With the Autostar’s two- Although the software routines for Users initiate the Galileo application line display, finding an object in the the eZ80 and Palm are mostly straight- from an icon on the Palm screen, which takes you through a Welcome screen to the main control screen, as shown in Listing 1—The Palm uses this communications routine to talk to the telescope. It has to reformat bytes that Photo 4. This screen emulates the might be confused for commands and resend the commands when they fail. Autostar control functions, giving you the ability to control the direction and //Format message to send to IRDA Port. You can enable/disable speed of telescope movement for manu- the handshake feature with the do_not_wait_for_handshake bit. al pointing. It also gives you the ability void Send_Message(Char Msg[]) to adjust the telescope’s focus and pro- { vides user location information. The int i; display takes the day and time from the FormPtr pForm; Palm OS; it also takes latitude and longi- Msg[byte_count] = 0; tude from a GPS receiver if one is con- nected to the Palm’s RS-232 port and for(i=0; i

24 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO clock recovery and bit synchroniza- Palm will resend the command. In tion. It’s up to the higher-level proto- this way, the Palm maintains control cols to address the unreliable link. over the communications link, and When I began looking at the IrDA the eZ80 can simply send its response specifications, however, I was over- messages blindly. whelmed with all the software layers This protocol makes the communi- needed to get a standard protocol stack cation bulletproof in that it ensures the up and running. I put the specification accuracy of messages. It also makes the book back on the shelf and created my use of the IrDA link more convenient. own protocol to get the job done. Unlike a television remote, the Galileo Palm tries multiple times during a peri- THE GALILEO PROTOCOL od of several seconds to get the mes- The aforementioned command and sage through. You don’t have to point checksum framing are part of my first and then press the button to see if Galileo protocol. Starting the message they are aligned correctly; nor must Photo 5—Mapping the Autostar to the Palm display with a reserved command word, the you try again if there is no response. gives soft keys. The software also maps those keys to Galileo protocol ensures that the You can simply press, point, and let the the Palm’s hard buttons. receiver can distinguish between a Palm take advantage of the link as soon valid incoming message and a message as everything lines up. forward translation and display, the IrDA fragment. The checksum at the end of Be careful when using this protocol. link is a critical element that requires the message ensures that the message Because of the need for handshaking careful consideration. The IrDA link is was received correctly. Listing 1 and retry, the messages sent over the not simply a wireless version of the RS- shows the Palm routine that builds IrDA interface should be short. The 232. There are two major differences. the IRDA command string. longer the message, the more likely it The first difference is that the IrDA The eZ80’s protocol task is to validate is that the link will be broken before a must operate in Half Duplex mode. incoming messages, send an acknowl- successful transmission and response Unlike a pair of wires, which don’t edgement when a message arrives cor- have been completed. That means interfere with one another, the optical rectly, and to format its respons- pathways interact. The IrDA transmit- es properly. All of the protocol ter is located next to the receiver, intelligence is in the Palm. No user input Palm OS controls sharing a common molded lens assem- As you can see in Figure 3, Palm resources Palm main bly. Thus, during transmission, you the Palm software provides for a control screen have to shut down the receiver, or you message retry. When you press a will see your own outgoing message. button to initiate a command to N Button The second difference between RS- the telescope, the Palm writes push?

232 and IrDA is the reliability of the the message to a buffer and Y link. A wire is either working or dis- sends it to the serial port. The Control message connected. IrDA requires the sending IrDA driver software sends this for button just pushed formatted and receiving units to be aligned (i.e., message and awaits a response into “Message they need to point at each other) in from the telescope. If the tele- packet” order to connect, so connection scope doesn’t respond within Palm’s “Message Packet” Resend message serial port depends on your aim and the steadi- 500 ms, the Palm resends the written to Palm’s enabled in serial port ness of your hand. It also depends on message. During the message- IRDA mode not being blocked, such as when my sending process, the user dis- Start retry counter dog walks between the Palm and the play shows a “Searching” mes- Message telescope during transmission. sage. Each pass through the Wait N “OK” When the Palm tries to send a mes- retry loop adds a period to the 100 ms back from WWW.GiURUMELE.Hi2.ROIRDA sage to the telescope, it must be point- end of the Searching message. port Y ed correctly and stay that way After 20 passes (10 s), the Palm Output “Searching” throughout the message exchange or reports a “Cannot find eZport” message Operation complete the message won’t make it through. message and quits. back to main

To keep this uncertain link from being When the Palm is expecting a Retry Output N counter Y “Cannot Find a major frustration, the Palm should response from the telescope, 0? IRDA Port” be able to tell when messages fail and the retry loop includes looking correct the situation. for a valid response as part of The IrDA controllers in the Palm its definition of a completed Figure 3—To ensure reliable communication over the IrDA link, the Palm software uses a wait-and-retry approach to communi- and eZ80 don’t address this problem. message. If the response is cor- cations. It sends a message and waits for a response, resending Their function is to handle things like rupted, or never occurs, the if the response fails.

26 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com CT_CRL = 0×F8 MT_MOVE = 0×05 MESS_SOUTH = 0×01 ∧ ∧ MESS_CS = (CT_CRL MT_MOVE MESS_SOUTH) & 0×7F END_MESS = 0×FE

CT_CRL MT_MOVE MESS_SOUTH CS ENDMESS CT_CRL MT_MOVE MESS_SOUTH CS ENDMESS

5-byte messge approximately 1 ms

Wait for handsake time 500 ms

Figure 4—A typical message from the Palm demonstrates the Galileo format. Messages are short and framed with a command code and checksum. you’ll have to use additional retry network connection, I could even attempts to increase the odds of hav- stargaze over the ’Net from the com- ing the link work, which will make fort of my home. the link less responsive. Although searching the stars from I found that keeping the data packets inside my house doesn’t generate the to 10 or 20 bytes yields the best results same thrill as standing outside in the in terms of reliability and speed. Longer clear night air to gaze at heavenly data blocks should be broken up and objects with my own eyes, it does numbered so that the receiver can put have one benefit: I can scan the stars them back together and have labels to and still be able to meet my wife’s identify the start, end, and size of the request, which is to stay home and block. Figure 4 is an example of a gaze at her. I command string. Using the Palm and bridge module Steven Pope has a B.S.E.E. and holds to control the telescope, I get more five U.S. patents. Currently, he is a than a better user interface. I also have fellow at Zilog, where he focuses on the beginning of remote control capa- embedded microprocessor applica- bility. But pointing the handheld Palm tions. Steven’s hobbies range from at the telescope is a tedious way to astronomy to model trains and radio- issue a long series of commands. A controlled cars. You may reach him wireless Ethernet link would be more at [email protected]. practical. I chose to use the Webserver module as a core so that I could PROJECT FILES expand in that direction. To download the code, go to ftp.cir- The Webserver module includes an cuitcellar.com/pub/Circuit_Cellar/ Ethernet port and comes with full 2003/157. Ethernet and TCP/IP software support, so turning the Galileo Palm bridge into SOURCES a Galileo Internet bridge would require ETX-105 telescope (with Autostar) only RF access point components as Meade Instruments Corp. hardware additions. The eZ80 software (800) 626-3233 would become more complex, of course, www.meade.com but most of the necessary software ele- ments are available and ready to use in m100, OS Development tool the Webserver support package. The Palm, Inc. support software also includes a full (408) 503-7000 HTML server, WWW.GiURUMELE.Hi2.ROwhich turns the design www.palm.com of a user interface into a simple HTML Visor Prism programming effort. A PC, running any Handspring, Inc. operating system, can run the telescope www.handspring.com without additional programming. I could even set up the telescope for eZ80 Microcontroller and Webserver ’Net-based control. I could download module (eZ80L925048MOD), IrDA star data from the ’Net and pass it to development system the telescope, which would give me an Zilog, Inc. unlimited database of objects to gaze (408) 558-8500 at. With a CCD camera and a wireless www.zilog.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 27 FEATURE ARTICLE by Daniel Ramirez

Build Your Own Four- Function Calculator CONTEST ENTRY

Daniel recently built his own electronic four-function calculator, citing little more than the spir- it of invention as the impetus for his choice of design. In this article, he presents us with a thorough description of the project.

Electronic calculators are amazing the history of the calculator, you may however, to be perfectly honest, I ended tools that have been around in one download my essay on the subject up soldering one connection when a form or another for nearly half a cen- from the Circuit Cellar ftp site. lead from one of the LED digits broke tury. They’re used each day in homes, during the wire-wrapping process. offices, and schools for tasks such as BUILD IT YOURSELF balancing checkbooks, paying taxes, In this article, I’ll help you get started HOW IT WORKS and performing most arithmetical on the construction of your own basic My calculator’s internal workings are tasks. For convenience, calculators are four-function calculator, which you similar to those of commercial calcula- now available in sizes to accommo- may later modify to perform additional tors and computers. User input and date almost any purpose. The inner operations. In addition, I’ll show you numeric key sequences are entered by workings of a basic calculator using how all of the calculator’s subsystems means of the keypad or through the programmable logic devices may now (keypad, display, and PIC18C452 micro- serial port when it’s used as a numeric reside on a VLSI, FPGA, or CPLD chip controller) work together (see Photo 1). unit. no bigger than a pinhead. I took on the challenge of attempt- The calculator processes the selected Because PCs and laptops are descen- ing to make this project completely operations by feeding data to the dents of the calculator, gaining an under- solder-free. PC boards, chemicals, and embedded microcontroller for evalua- standing of calculators and how they point-to-point wiring are unnecessary, tion. Then, it performs the calculations work should furnish you with insight although you may use any method of using standard floating-point arith- into the workings of modern digital construction that you desire. For the metic, as shown in Listing 1. Answers computational devices. Newer genera- most part, I succeeded in assembling are converted from the internal IEEE tions of calculators have evolved in my own calculator in this manner; floating-point formats to ASCII values parallel to PCs, and they are equipped and sent to the desired output device, with financial, trigonometric, and scien- which includes the LED display, LCD, tific functions. Some calculators from or the serial port connected to a host Hewlett-Packard and Texas Instruments PC or laptop. In Coprocessor mode, the even include matrices, symbolic inte- system uses the serial interface exclu- gration, differentiation,WWW.GiURUMELE.Hi2.RO and program- sively for its I/O. A unique feature of ming languages such as Basic. this calculator is that answers may be You can build your own four-func- displayed in any combination of the tion calculator with common elec- three display methods. tronic components available on the Internet or at your local electronics CONSTRUCTION TECHNIQUES shop. In this way, you can recapture You may prefer soldering to coding something of Blaise Pascal and Charles software, but I prefer the lost art of wire Babbage’s spirit of invention by build- wrapping because messy chemicals are ing a calculator piece by piece. If Photo 1—Ready to build your own calculator? The unnecessary. Therefore, it’s cleaner and you’re interested learning more about clear casing allows you to see it all! doesn’t generate smoke. If I had my way,

28 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com the pin of each surface-mount IC that’s A basic Radio Shack wire-wrap tool THE VISIBLE CALCULATOR used for prototyping would be brought (part no. 276-1570), which costs $7.49, Inspired by the visible man and visi- out to a one- or two-level gold-plated is required for the delicate LED digit ble car engine educational models, post used to hang a wire-wrap wire. display. In order to save time, I also which you can find in most science Ordinarily, prototype boards such as used an electric wire-wrap gun, which stores, I chose to encase my calcula- those sold by Radio Shack (part no. I purchased at a surplus supply store, tor’s electronics and LED display in 276-174) use heavy-gauge jumper wires although the entire project can be transparent plastic boxes. I obtained to make the circuit connections. The built using only the wire-wrap tool. the boxes from an arts and crafts result is a wiring nightmare when all The 30-gauge wire used for wire wrap- store. I color-coded the LED digits to of the calculator’s components are con- ping may be found at Radio Shack in create a unique display. nected. I remedied this situation by red, white, and black 50′ spools. The display digits are grouped in four using multiple rows of 0.1″ pin headers The wire-wrap connections may be sets of three LEDs. Each set has a differ- as one-level wire-wrap posts to make soldered for extra durability, because ent color (red, green, orange, or amber) the connections. I used the extra-long they aren’t as reliable as normal two- to indicate thousands. I arranged the 3/8″ pin headers, which are available or three-level wire wraps. But this digits in the color-coded groupings from Jameco and Digikey, for making would make it harder to reuse compo- because I felt it was more intuitive than multilevel wraps. Thus, I no longer nents, including the wire-wrap wire. using digits of the same color. When need to buy expensive wire-wrap For a more durable calculator, it may the LCD is used, alphanumeric char- sockets for the ICs, and I’m able to be a good idea to consider using acters appear on the LCD and prompt use the thin 30-gauge wire-wrap wire point-to-point or PC board construc- you for input. Text messages cus- for the connections. tion methods. tomized in the firmware also can be sent to the LCD for output.

Listing 1—The code for the project is straightforward. This section of code shows how the four-function cal- PSYCHEDELIC DISPLAY culator evaluates simple arithmetic expressions. In order to make this project visually

The calculator performs double precision floating-point addition, interesting, I decided to use large, bright- subtraction, multiplication, and division. It does not currently sup- ly colored LED digits. The LEDs shown port levels of nesting parentheses for complicated mathematical in Photo 2 display well in a dimly lit expressions. ********************************************************************* room. Seeing the pi value in rainbow double Calculator(double Argument1, char Operator, double Argument2) colors might take you back to the psy- { chedelic 1960s. I produced a carousel of double TheResult; colorful numbers using a simple loop switch(Operator) and calling one of the LED display rou- { tines (see Listing 2). I selected the larger case '+': { LED digits (12.3 mm × 14.4 mm) to TheResult = Argument1 + Argument2; break; make the easy-to-read numeric display. } The LED display module is assem-

case '-': bled from individual LED digits that { were stacked together with glue. The TheResult = Argument1 - Argument2; break; 12 LED digits are arranged in clusters } of four: three red, three green, three case '*': orange, and three amber. To keep the { digits aligned, I used a heavy bookend TheResult = Argument1 * Argument2; break; } with a straight edge and carefully glued one digit at a time. I let each set case '/': for a few minutes and dry before I { attached another digit. WWW.GiURUMELE.Hi2.ROTheResult = Argument1 / Argument2; break; } After the LED digits were glued, it was time to wire wrap them. As you default: { can see in Figure 1, connecting each of TheResult = 0; the leads makes the LED display bus. I break; did this carefully because the LED } digit leads are delicate and can only } support a one-level wrap. Compared to an LCD, the LED dis- return (TheResult); play has some disadvantages. An LED’s } power consumption is much greater than that of an LCD, so the 9-V battery

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 29 will not last as long if the LED display MAX7219 DRIVER BOARDS eight digits. Furthermore, it can con- is constantly in use. Another drawback The MAX7219 LED digit display trol their brightness using a PWM and is that the LED display isn’t of the driver IC is extremely flexible. At $9, a current-limiting resistor (10 kΩ). matrix variety. So, it displays only the it’s one of the more expensive compo- The MAX7219 converts the binary following: “H,” “E,” “L,” “P,” digits nents, but it’s well worth the expense. values to BCD to drive the correct LED zero through nine, periods, and dashes. It drives the LED digits’ segments segments. Although the PIC18C452 Obviously, the letters can be used to using a multiplexing scheme that has the ability to drive the LED digits display a “HELP” message in the event keeps them from drawing too much with additional low-cost discrete com- of incorrect data entry. Floating-point power, and it also keeps them at the ponents attached, it would make the exponents may be entered and dis- correct level of brightness. A single calculator firmware code more com- played using the “E” character (e.g., MAX7219 can drive up to eight LED plicated, because timer-driven inter- 5.5E–20). Despite the disadvantages, I digits or 64 individual LEDs, although rupts and PWM waveform generation enjoyed working with an LED display. it can be cascaded to drive groups of would be required. The PIC18C452 sends data to the MAX7219 display driver using a three-wire SPI interface. The configu- Frustration? No, thanks. ration data—consisting of the level of brightness, number of digits, and data Fun? Yes, please. format (BCD or binary)—are sent to Satisfied customers - the key to our success the MAX7219. Test mode lights all the segments of each LED digit that’s > that´s why every new EAGLE version is based connected. The MAX7219 commands on the feedback from our customers > are shown in Table 1. that´s why all our customers have access to our For the final version of this project, I highly acclaimed, comprehensive support, free of charge used three prototype boards, one for > that´s why EAGLE has no hidden costs for EAGLE 4.0 each MAX7219 controller IC and a third libraries or modules which prove to be for the PIC18C452 micro. I could have indispensable after purchasing Schematic Capture • Board Layout made the MAX7219-based LED display Autorouter > that´s why we really want customers to enjoy ® driver circuit simpler if I hadn’t ordered for Windows working with EAGLE the wrong type of LED digits. I found > that´s why EAGLE is one of the top-rated and out too late that I should have ordered programs for schematic capture and board the common cathode variety instead layout W d   a d ad a  Mc   C  a L   a d ad a  L  T ad of the common anode. They were list- ed next to each other in the catalog. Version 4.0 Highlights ! Ordering the correct parts at that New Library Management with stage of the project would have added Component Browser ! Technology and Package variants for to the cost, so I decided to add four components low-cost 74240 inverted octal latches ! Design your own commands via User from my parts box. My intention was ! Language Unlimited length for component to invert the signals required by the names/values ! Design Rules define pad/via two MAX7219 LED driver ICs. The dimensions and shapes 74240 ICs may be substituted with ! Net Classes for Autorouter and DRC ! Minimum Autorouter grid: 0.02 mm common cathode LED digits connect- ! SMD pads can be rounded or round ed directly to the MAX7219. (You may ! Different pad shapes for Top, Bottom, or Inner layers purchase the cathode LED digits from companies like Digikey and Jameco.) EAGLE 4.0 LightWWW.GiURUMELE.Hi2.RO is Freeware! FREE Next month, I’ll provide you with a You can use EAGLE Light for testing and for Prices Light Standard Professional schematic that includes the common non-commercial applications without charge. The Freeware Version is restricted to boards up to half Eurocard format, Layout 199$ 399$ cathode LEDs. This will save time with a maximum of two signal layers and one schematic Layout + when building the boards, although sheet. All other features correspond to those of the 398$ 798$ Professional Version. Download it from our Internet Site Schematic the project looks more impressive or order our free CD. Layout + 398$ 798$ with the extra components. You can The Standard Version is suitable for boards in Eurocard Autorouter format with up to 4 signal layers The Professional Version Layout + drive even larger LED digits with the has no such limitations. Schematic + 49$ 597$ 1197$ Autorouter MAX7219 by making minor changes http://www.CadSoftUSA.com to the power supply and adding some Pay the difference for Upgrades 800-858-8355 transistors. If you’re interested in studying the wiring diagram, refer to CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483 Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : [email protected] the Resources section at the end.

30 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com Using two cascaded MAX7219 LED tons or toggle switches that are tied to driver ICs capable of multiplexing up to unused I/O lines (e.g., use port A, RA4 16 digits, I could only drive 10 digits by with a 10-kΩ pull-down resistor). One using them to push five LED digits switch may be used to act as an each. This may have been the result of inverse, shift, or secondary function in the excessive current drawn from each order to assign different meanings to of the large LED digits or it may have each key. The firmware must perform been caused by the fact that I used com- a logic bitwise OR between the state mon anode LED digits instead of com- of the switch and the keypad code mon cathode LED digits. In the near Photo 2—The 12-digit LED shows the value of pi in that’s returned in order to create a future, I plan to add the remaining four rainbow colors. I took the photos in a dimly lit room. unique function identifier. digits to the LED display. Hopefully, Using a 16 × 16 keypad opens unique I’ll be able to find blue LED digits. calculator. As you can see in Figure 2, keystrokes. When using one switch or To build the calculator, I used a wire- the keys are mapped to functions. If push button, you get 32 functions wrap technique with the 0.1″ pin head- you want to build a more powerful sci- (1 × 16 + 16 = 32). If you use two ers plugged into the prototype boards entific calculator, you’ll need a larger switches or push buttons, you get parallel to each IC. These boards are keypad (e.g., 5 × 4). By changing the 48 functions (2 × 16 + 16 = 48). shown in Photo 3. keypad firmware, you can designate a The inputs to port B are pulled high special shift key to allow for access to by using the PIC’s internal pull-up STANDARD 4 × 4 KEYPAD two times as many functions. resistors (see Figure 2). Because calcu- The standard 4 × 4 keypad has A simple way to effectively increase lator keypads can generate electrostat- enough keys for a simple four-function the number of keys is to add push but- ic discharges that can damage the PIC,

WWW.GiURUMELE.Hi2.RO

Figure 1—You can use the schematic to assemble the calculator’s optional common anode numeric LED display driver circuit. Parts placement and board fabrication tech- niques are not crucial.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 31 WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO 330-Ω resistors are placed in series DEBOUNCING THE KEYS with the port B inputs for ESD protec- Depending on the mechanical and tion. You can use a standard eight- or electrical characteristics of the selected 14-wire parallel ribbon cable to con- keypad, extra keystrokes may be nect the keypad, or you can try a stan- encountered each time a key is pressed. dard stranded hook-up wire for flexi- You can eliminate this anomaly by bility. I could have used the PIC’s Photo 3—Notice the placement of the pin headers. debouncing the keys, which is usually change on port B status interrupt, but They are parallel to each IC on the prototype board so accomplished by placing a 20-ms delay I chose not to. Basically, I wanted to that they may be wire-wrapped. in a loop where the key is polled. keep the firmware simple without I referred to Michael Predko’s book, interrupt service routines. there are more characters available, Programming and Customizing One problem with using the keypad such as “E” for exponentiation, when PICmicro Microcontrollers, as I wrote for input is the translation of charac- entering floating-point numbers using my version of debounce in PIC18xxxx ters required for entering exponential scientific notation. Thus, the value C. I rehosted Predko’s debounce routine floating-point numeric values (i.e., may be entered as “2.718E2.” in PIC assembly to C so that I could 2.718 × 102). Normally, the value is The labels for calculator functions include it for my calculator. [1] The algo- entered through the keypad as “2 × (+, –, ×, /, =, and .) may be affixed to rithm worked flawlessly, and it filtered 718E2”; however, the keypad I select- the keys. You can enlarge the labels multiple keystrokes. Listing 3 is my ed doesn’t have an “E” character. with a copier, print them on trans- C version of his debounce algorithm. Consequently, I’m limited to entering parencies with an inkjet printer, and You may download the C files from fixed-point numbers, although the cal- then glue them on the keys. In order the Circuit Cellar ftp site. The source culator is capable of handling expo- to distinguish overlaid functions, the code shown in the keypad.c file nential numbers. secondary function key labels could demonstrates how you can integrate When using the serial interface, all be printed in different colors as seen it in customized designs. of the keystrokes are entered from the on commercial calculators. For PC or laptop host keyboard instead of instance, you could use white for pri- THE BRAIN the calculator’s keypad, so character mary functions and red for secondary You must use a microcontroller for translation isn’t required. In addition, functions. this application, unless you incorpo-

WWW.GiURUMELE.Hi2.RO

34 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com The MAX233 IC shown in Figure 2 Listing 2—I used this snippet of code to produce a carousel of colorful numbers on the numeric LED display. uses the USART (RS-232) interface to

while(1) communicate with a PC or laptop { host via HyperTerminal. It also pro- for (i=0; i<99999; i++) vides the means to use the calculator { as an IEEE floating-point coprocessor //Convert i to string for display itoa(i, TestNumber); to another PIC or STAMP microcon- //Send it to the numeric LED display in color troller that doesn’t currently have access to floating point. MaxPrint(TestNumber); pause(10); When it’s used as the primary calcu- } lator storage device, the 24LC16B I2C } serial EEPROM can store up to 2048 bytes, which can be used for look-up rate EPLD, FPGA, or VLSI techniques. The PIC18C452 has 32 KB of EEP- tables. In addition, it can store inter- I chose the PIC18C452 microcontroller ROM and 1536 bytes of RAM, most of mediate calculation results. Another because it was more economical at $15 which I used for the firmware develop- possibility is for the firmware to use it than a BasicX or ATOM micro costing ment. I selected a 20-MHz oscillator for as a stack to evaluate expressions or as approximately $50 (supporting IEEE the microprocessor clock, although I a Forth or Basic interpreter. The floating point). The Stamp BSP doesn’t could have selected up to 40 MHz for capacity is easily increased to 32 KB have support for floating point, so I speedier calculations. Note that the new by dropping in a 24LC256 32 KB × 8 couldn’t have considered it for this flash memory-based PIC18F452 doesn’t serial EEPROM device. The storage project. Any Motorola 68HC12 or Intel require a UV eraser. This should help capacity can be increased even more 8052 derivative, such as the Domino alleviate the UV erase cycles. It will also with additional I2C-networked serial or a high-end Atmel processor, is suit- reduce the need to constantly remove EEPROMs (e.g., eight 24LC256 devices able for this project. The 8052 Basic the PIC from the hardware when using for a total capacity of 256 KB with interpreter that supports floating ICSP programming to burn the PIC. The only minimal changes to the point could be substituted with mini- chip’s low-cost in-circuit debugging firmware). You can add a 64-KB SRAM mal changes to this design. capability allows for ICD2 debugging. for the faster operations required by

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 35 As Figure 3 demonstrates, a 5-V Command Code Description/results supply is sufficient for all of these power-consumption requirements. No Operation 0 No operation performed. Used to cascade multiple MAX7219(s) Digit 0 1 Select digit 0 But, you could also use a 9-V alkaline Digit 1 2 Select digit 1 or NiCd rechargeable battery, or even Digit 2 3 Select digit 2 a 9- to 12-V wall transformer to power Digit 3 4 Select digit 3 the project. Depending on the number Digit 4 5 Select digit 4 Digit 5 6 Select digit 5 and type of devices connected to the Digit 6 7 Select digit 6 controller board, the 7805 IC may Digit 7 8 Select digit 7 need a heatsink if it gets too hot dur- Decode 9 Decode register, a value of one enables BCD decoding ing normal use or if it shuts down Brite 10 Intensity register Scan 11 Scan limit register (although I didn’t require one for my Switch 12 On/Off register hardware configuration). Display Test 15 Activates test mode The power supply can be separate from the board, or you can build it in Table 1—I’ve listed all the MAX7219 LED controller commands that are available. You may customize the firmware for special effects. using any vacant real estate on the prototype board. The calculator is the more sophisticated functions, Connect the power lines with red turned on and off with a convenient graphics displays, and languages. jumpers and the ground lines with toggle switch located next to the black jumpers. Finally, wrap each logic power supply. A push button would BUILD THE BOARD signal with white, yellow, or blue work as well. Use the schematic shown in Figure 2 wire. Check each off from the diagram My project doesn’t address low- to build the calculator’s controller until all of the signals are wired. Screw power consumption concerns, so the board. Point-to-point and PC board PC standoffs to the prototype board type of display you use (LED, LCD, or construction are viable options, but I and glue or solder the RS-232 connec- PC) will determine the length of time chose the wire-wrap method for a tor directly to it. Use a digital multi- the calculator will run using a 9-V challenge. Also, you can wire-wrap meter to check all of the connections battery. I recommend a 12-VDC wall the controller by following the specif- between the keypad and the controller. transformer for continuous use. ic set of instructions I described in my The next step is to check the circuit article titled “Optimize Your PIC” for shorts or open lines. Use the digi- C COMPILER AND TOOLS (Circuit Cellar 133). In fact, you can tal multimeter to check the continu- As you can see, building a simple recycle previously built boards by ity on all of the power, ground, and four-function calculator from scratch simply connecting the keypad and logic signals. You can inspect the isn’t as easy as it sounds, particularly MAX7219 driver boards. board with a magnifying glass. because of all the software tools and If you don’t have an older board, you’ll Before populating the board with even some of the hardware (e.g., the have to build the circuits from scratch. the ICs, power the board by connecting programmer and UV eraser) that are To do so, use two or three standard a 6-V battery to the positive and negative required. It would be even more diffi- Radio Shack prototyping cards (part no. power terminals, and then check to see cult and expensive with a hardware- 276-174). First, insert the required pin if the Power LED lights up. If it does, specific solution—such as using VLSI headers parallel to each IC. Use a small check for 5 V at the VDD pin of each IC techniques—unless you happen to block of hard wood to apply even pres- and volts at the VSS pins. Then, the board have access to the required silicon sure to the pin headers as you insert may be populated with the ICs, and compiler tools. But this method tends them into the prototype board (don’t use you can fire it up for the first time. to embed the entire application in one your fingers). Photo 3 is a great guide. monolithic IC, which is something For multiple connections, use a one- POWER UP I’m trying to get away from. or two-level wrap, or try a double row A good power supply is a must for the I chose a flexible software solution of pin headers. Next, place the 0.1-µF LED display. Even though the LED dig- using the PIC18C452 that fully demon- bypass capacitorsWWW.GiURUMELE.Hi2.RO as close to the IC its are multiplexed, they can still draw a strates exactly how a calculator works. socket power pins as possible. Place the lot of power when all of the segments The PIC18C452 has extensive capabili- remaining discrete components (resis- are turned on (e.g., when displaying the ties needed to handle most of the arith- tors, capacitors, and diodes) on the pro- number eight). Earlier, I mentioned the metic processing required by the calcu- totype boards. If you use the wire-wrap problem of only being able to display lator. Many of the PIC’s hardware fea- method, consider purchasing labels. a total of 10 large LED digits, which I tures are directly supported, using the The next step is to connect the believe could be the result of excessive PIC18xxxx C libraries, so that PIC power and ground wires. You may find current drawn by each LED. The power assembly language is not required. it advantageous to use the heavier supply must be able to handle this load This project provides a great opportu- gauge jumper wires instead of the 30- along with the power required for the nity to learn all about the PIC18xxxx C gauge wire-wrap for power and ground. PIC18C452 and the other ICs. compiler and tools, using Microchip’s

36 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com free tool suite, because they’re simple in order to reduce the UV eraser floating-point capability, unless to use and inexpensive. I recently pur- requirement, I suggest using the lower- you’re only going to use it for han- chased Microchip’s PICDEM 2 and cost PIC18F452 and ICD2 programmer dling fixed-point or integer quantities. ICD2 to support the new PIC18F452. needed to burn the PIC18F452. In addi- This is where I took advantage of the These new tools are a boon to hobby- tion, use the firmware contained in the PIC’s floating-point capabilities. ists because they provide excellent calc1.hex file (download from the In the past, I’ve expressed my regret low-cost development systems, which Circuit Cellar ftp site), which that Microchip doesn’t supply certain allow a PIC to be programmed within includes the complete four-function C libraries and functions with its demo the application by using in-circuit seri- calculator application. C compiler, specifically the stdio.h al programming (ICSP). The result is There is one drawback to using the library that supplies the printf and the elimination of the need to con- calc1.hex file instead of the C code: it scanf functions. I later found, to my stantly erase the PIC with a UV eraser. prevents the customization of the calcu- surprise, that I couldn’t access the nor- It also enables low-cost debugging via lator. I recommend the USB version of mally available trigonometric and sci- the PIC18F452’s in-circuit debugger the ICD2, because it’s much faster than entific C functions from the math.h (ICD), which provides ICE capabilities the serial RS-232 version during pro- library, even though my application similar to the ICE2000 at one-tenth the gramming and single-stepping code. It’s had compiled and linked correctly. cost. The ICD2 capabilities include set- too bad these tools weren’t available According to Microchip’s latest release ting one breakpoint anywhere in the sooner. They would have made debug- notes, these functions aren’t provided, program memory and giving the user ging my code much easier. The MPLAB but I hope they will be in the future. the ability to watch any register or and MPSIM tools are available on the Not having those libraries was dis- memory location while actually con- Microchip web site along with the couraging, to say the least, because my nected to the hardware. PIC18C C compiler demo. calculator is dependent on those func- I used the PIC18C452 because the tions. However, I eventually completed ’F452, which is functionally identical, MISSING MATH FUNCTIONS some of the required floating-point for- was not available at the time. However, A calculator needs some kind of matting and conversion functions.

WWW.GiURUMELE.Hi2.RO

Figure 2—Now you can build the main controller board. Use this schematic to connect the other subsystem components including the keypad, optional LED numeric display, and LCD.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 37 The functions are needed to scan if you were to add larger LEDs, voice conversation piece at the office or at numbers and operators from the key- recognition, or voice synthesis hard- home, especially if you use clear plas- pad, and to convert ASCII floating-point ware to the design. tic housing to showcase the interior. numbers to binary IEEE floating-point This was a fun project, especially format so they can be arithmetically NO SWEAT after I figured out how to get the multi- processed by the firmware. They’re Using simple tools and common colored LED display working, because I also needed to convert from binary components, you can build a calcula- was able to produce animated color dis- IEEE floating-point format back to an tor in a few evenings. It makes a great plays. I also felt a great sense of accom- ASCII formatted string so they may be shown on the LED, LCD, or PC displays. Although I haven’t modified Listing 3—What do you think about my version of Predko’s keypad debounce algorithm written in PIC18 C? It was originally written in PIC assembly, but I converted it to C so that I could use it for my calculator application. my version of printf to handle float- ing-point (%f) and fixed-point (%d) spec- //KeyScan: Scan a 16-key matrix keypad for operator keystroke ifiers, these functions are still neces- int KeyScan(void) { sary. Eventually, I will have to do this int i; //Loop index modification or, hopefully, Microchip int j; //Loop index will fill the gap for me. byte PortBValue; //Value read from port B //pause(20); I could have saved program storage //Debounce keypad input space and constructed a more sophisti- do cated calculator if the functions had { //Wait for all keys up been available in time for this article. PORTB = 0x00; Because of time constraints, I could TRISB = 0xF0; only provide support for four functions: } while ((PORTB >> 4) != 0xF); addition, subtraction, multiplication, pause(20); and division. You can work on the //Debounce keypad input financial, trigonometric, and scientific //Debounce the keypad here for (i = 0; i < 4; i++) functions if you’re interested in numer- { ical methods. Use the serial EEPROM provided in the controller board for //Discharge the keyboard PORTB = 0x0F; storing sine and cosine look-up tables. TRISB = 0x00; I may explore this option myself. //Send PIO mode command to set port direction to input, this works for any row TRISB = 0xF0; BASE CONVERSIONS //Drive all columns low to determine if a key has been pressed; You use the decimal system daily, port B pull-ups should be enabled but other systems—such as binary Low(PORT_B, i); PORTB = Cols[i]; (base 2), octal (base 8), and hexadeci- //Save Port B value mal (base 16)—are commonly used in PortBValue = PORTB; digital computers. A trinary system— //Look up the key scanned in table for (j = 0; j < 16; j++) such as the one in Arthur C. Clarke’s { classic novel, Rendezvous with Rama if (PortBValue == KeyLookupTable[j]) (1973), in which visiting aliens did { key = j; everything in threes, and the sci-fi goto ExitLoop; movie, War of The Worlds (1953), in } which the Martians formed groups of }

three before attacking—sounds key = 0xFF; intriguing to me. } If a calculatorWWW.GiURUMELE.Hi2.RO is needed to convert ExitLoop: between the bases and display the if (key != 0xFF) answers, it’s easy to add the base con- { version function. This function is if (db == 1) equivalent to the Stamp BS2/BSP hex goto done; //Already responded to this press, so function. The LED display isn’t able done to handle all of the hex digits, so I db = 1; //Set debounce and keypress flags press = 1; recommend an LCD when you’re } using this function. done: The unique color-coded LED dis- db = 0; //Reset the debounce bit return key; //Return keystroke to caller play is easy to read. In addition, hand- } icapped persons would find it helpful

38 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com RESOURCES B. A. Toole, Ada, the Enchantress of Numbers: Prophet of the Maxim Integrated Products, Inc., Computer Age, Strawberry Press, Serially Interfaced, 8-Digit LED Mill Valley, CA, 1998. Display Drivers, 19-4452, rev. 3, 1997. W. Press, et al., Numerical Recipes in C: The Art of Scientific Computing, Cambridge University SOURCES Press, Cambridge, UK, 1993. MPLAB, PIC18C452 Microcontroller, Figure 3—You’ll need a 5-V power supply to power PICDEM 2 your calculator’s controller board and the optional LED D. Ramirez, “Robot Sensor Microchip Technology, Inc. display board. A heatsink may be required for the 7805 Controller Board: Part 1,” Circuit (480) 792-7200 IC if the current drawn by LEDs and other peripherals is excessive. Cellar 135, 2001. www.microchip.com plishment after building an educational electronics project using only wire- wrap construction techniques. If you want to learn how to build a reverse Polish notation (RPN) calcula- tor, be sure to read my next article, which you’ll find posted on the Circuit Cellar web site in September. In that article, I’ll provide you with a schematic that uses common cathode LED displays. In addition, I’ll go into more detail about the firmware that’s needed for the calculator to perform mathematical scientific and trigono- metric functions. I

Author’s Note: I’d like to thank to my wife Pamela for her time and assistance with this article.

Daniel Ramirez is a software engineer with more than 10 years of experience working on real-time embedded sys- tems. In his spare time, when he’s not working on new robotics projects, Daniel enjoys traveling, golfing, and treasure hunting. You may reach him at [email protected].

PROJECT FILES To download the C code, floating- point formatting and conversion functions, firmwareWWW.GiURUMELE.Hi2.RO for the MAX7219 and keypad, and an essay on the history of the calculator, go to ftp.circuitcellar.com/pub/Circuit_ Cellar/2003/157.

REFERENCE [1] M. Predko, Programming and Customizing PICmicro Micro- controllers, McGraw-Hill/TAB Electronics, New York, NY, 2000.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 39 ABOVE THE GROUND PLANE by Ed Nisley

IR Sensing Most professional engineers believe they have an adequate understanding of IR sensing concepts, but it never hurts to brush up on the basics. In this column, Ed expands on many of the topics he covered in a lecture last spring at the Tenth Annual Trinity College Fire- Fighting Robot Contest. Both seasoned designers and curious students will find Ed’s straightforward commentary useful.

After a few years of designing, everything discussed here, you should room comes from their IR LEDs. building, and fiddling with electronic pass this column along to a younger Photo 1 clearly demonstrates the fal- gadgets, you learn that everything you friend. Perhaps you can share your lacy of that notion! need isn’t in the datasheets. Simply oscilloscope and circuit ideas, as well, Photo 1a shows Oosting Gym in put, your designs fail unless you factor to get them started in the right direc- visible light. Photo 1b depicts what it in your real-world experience. tion. Remember, these students will looks like in IR. My Sony DSC-F717V Last April, I gave a talk titled “IR become tomorrow’s engineers. They digital camera has a NightShot mode Sensing for the Bewildered” at the need all the help they can get! that removes an internal IR-blocking Tenth Annual Trinity College Fire- filter, thus passing both visible and IR Fighting Robot Contest. Most of the THE ENVIRONMENT to the CCD array. I added an external robots used infrared emitters and detec- Because human vision doesn’t filter that eliminates all visible light, tors of one sort or another to navigate extend into the infrared part of the so Photo 1b shows pure IR that the through the maze. In previous years, I spectrum, IR LEDs look the same camera renders in green-tinged had witnessed considerable confusion whether they’re on or off. For some grayscale. I suppose that’s in honor of caused by misbehaving sensors. reason, this leads many people to the phosphors in those awful first-gen- The overall goal of the contest is to believe that the only IR energy in a eration IR nightscopes. design an autonomous robot that can find a candle placed in a room of the a) b) maze, extinguish it, and return to the starting point. As Jake Mendelssohn, the contest’s founder, says, “The only people who think this is easy haven’t tried it.” He’s right! Many of the contestants are high school and college students who haven’t had much exposure to the real world. Their robots and sensors use straightforwardWWW.GiURUMELE.Hi2.RO designs that work perfectly well at home or in the lab but then fail completely in Trinity’s Oosting Gym. Is some mys- terious force at work? Although Circuit Cellar readers have much more experience with IR and circuit design than most students, Steve Ciarcia and I thought that Photo 1a—High-pressure sodium lamps illuminate the Fire-Fighting Robot Contest in Trinity College’s Oosting reviewing some basic IR sensing Gym. b—Taken through an optical filter that passes no visible light, this picture shows how the scene looks to IR would be useful. Even if you know sensors. Some robot designers don’t anticipate the high intensity or AC modulation of the ambient IR.

40 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com Figure 1 plots the char- REFLECTIONS Eyeball Lee 181 Congo blue IR LED acteristics of several Most robots and, for HP sodium lamp IR Photodiode Tungsten emitters, detectors, and that matter, people detect 87C IR filter filters against the wave- LEDs their surroundings by length in nanometers. 1.00 reflected light. The con- 0.90 The y-axis scale is linear, 0.80 test maze has matte- which exaggerates the 0.70 white walls and matte- highest decade but gives 0.60 black floors, all of which you an idea where the 0.50 are carefully painted 0.40 peaks lie. All of the 0.30 prior to each contest and Relative response Relative responses are normalized 0.20 sometimes touched up if to a maximum of one, so 0.10 an errant robot leaves a 0.00 you must take into 300 350 400 450 500 550 600 650 700 750 800 850 900 950 10001050 1100 major scuff. Even these account the actual power simplified conditions Wavelength (nanometers) of a source or the sensi- pose major problems for tivity of a detector. many robots. Figure 1—Infrared energy lies beyond the human eyes’ range, so you must rely on graphs to Notice that IR photo- show what’s happening. You can see that infrared photodiodes respond equally well to both IR energy behaves just diodes exhibit a broad IR and visible LEDs, high-pressure sodium lamps perfectly match the peak response of IR like visible light in most response with equal sen- photodiodes, and even IR optical filters aren’t much help against glowing tungsten filaments. respects: it can be reflect- sitivity to both IR and ed, refracted, diffused, and visible-red LEDs. Optical filters added which seemed like a good way to elimi- absorbed. Figure 1 shows that it has to their packages can reduce, but not nate excessive IR. Unfortunately, even about two times the wavelength of visi- eliminate, the effects of visible light. though fluorescent lamps convert ble light, which makes surfaces twice Many people are surprised when their much of their input power into visible as shiny and accentuates chromatic IR photodiodes produce signals caused light, ionized mercury has an IR emis- aberration in lenses. Thus, reflected IR by visible light, even though visible sion at 1014 nm, which can (and did!) tends to have more glare and to be less light is a small part of the problem. light up the IR detectors. diffused from a given surface, while Optical filters cannot eliminate The phosphors inside fluorescent refracted IR focuses on a different plane wavelengths close to those emitted by tubes convert mercury’s ultraviolet than the corresponding visible image. IR LEDs for the same reason you can- emissions into visible light, and the The matte-maze walls exhibit what’s not build brick-wall electronic filters. glass tube itself absorbs UV, but enough called Lambertian reflection, where The HP sodium lamp curve in Figure 1 UV escapes to trigger the Hamamatsu incoming light is diffused equally shows that high-pressure sodium UV-Tron sensors with which many well in all directions: you can see a vapor emits a great deal of energy at robots detect candle flames. The fluo- spot of light on a wall from any about 820 nm, which is almost exact- rescent lamps were gone by the next direction. Every light source falling on ly at the peak response of IR photo- year’s contest, and, eventually, they a Lambertian reflector contributes to diodes and extremely close to the simply turned off the HP sodium the outgoing energy in all directions. 930 nm of IR LEDs. lamps above the mazes, which pro- Mirrors exhibit specular reflection, The lighting in Oosting Gym con- duces the distinct shadows on the where all the incident energy bounces sists entirely of high-pressure sodium matte-black floor cast by lamps in the off at the same angle it enters. A sensor lamps, because they have excellent rest of the gym. that isn’t located exactly in that outgo- efficiency, decent color, and good oper- The curve for incandescent tungsten ing beam won’t see any of the energy, ating lives. Their visible color tends to in Figure 1 matches up well with IR just as you can’t see a flashlight beam be reddish-orange, but there’s enough photodiode sensitivity, and, thus, it on a mirror unless it’s glaring in your green energy to make the light fairly cannot be filtered out. A glowing fila- eyes. A robot in a hall of mirrors has a pleasant. They have a completely dif- ment has a high thermal mass; there- terrible time detecting the walls! ferent spectrum than the low-pressure fore, unlike mercury and sodium arc Most surfaces fall somewhere sodium lamps WWW.GiURUMELE.Hi2.ROfound in parking lots, discharges, it doesn’t have much between Lambertian and specular, which produce essentially monochro- 120-Hz AC modulation from the 60-Hz being neither completely matte nor matic orange-yellow light at the 590- power supply. Some contestants perfectly reflective. The Phong surface nm sodium D-lines. debugged their sensors under incan- model describes this situation using During the first years of the contest, descent lamps only to find a buzz on mathematics that isn’t relevant here the organizers realized that IR-rich their signals in the gym. because you generally don’t have the ambient lighting posed a major prob- In short, IR energy is everywhere, exact numbers. To get the general idea lem for most contestants, and since and you must understand how to of Phong reflection, think of a “hot then they’ve tried many seemingly detect your signal despite considerable spot” when viewed at the specular good ideas. One year featured banks of interference from the real world. Let’s angle plus a diffuse component visi- fluorescent lamps above the mazes, see what that requires. ble from all other angles.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 41 Many robots sport IR LEDs and tion from the front, any extraneous photodiodes that are mounted side by light can be devastating. side, lined up parallel to each other, Eliminating that light involves put- and pointed directly at the wall. Even ting the photodiode in an opaque in an ideal Lambertian world, that enclosure with an opening only in the doesn’t work well because the LED forward direction. A simple tube does- doesn’t light up the entire area viewed n’t work well because light can enter by the photodiode. Worse still, in a from the rear, penetrate the photodi- specular world, the photodiode might ode’s package, and bounce off the not see the LED’s reflection at all. front of the lens. Duct-seal putty, nor- If you want to detect a wall at a spe- mally used for sealing air conditioning cific distance, mount the LED and equipment, is available at your local detector as if they were looking at each hardware store and blocks light just as other in a mirror at that distance. The well as it does air. wall won’t be a perfect mirror, of After you’ve eliminated extraneous course, but a detector aligned with the light from the sides and rear, you may middle of the LED’s Phong “hot spot” want to concentrate your sensor’s reflection from the wall will capture as attention on a smaller spot to the much IR energy as possible. front. Although you can do this with Because the strongest ambient IR lenses, most designers favor simple generally comes from overhead, detec- collimators because they’re easy to tors should angle down toward the build, they don’t require focusing, and floor. The maze floors at the Trinity they don’t absorb IR. contest are flat black to minimize For a given spot size at a certain dis- reflections, but, in the real world, floors tance, the sensor’s acceptance angle are generally the most specular sur- works out to the following: faces after windows and doorknobs.  spot diameter  Therefore, you must trade-off direct arctan   wall distance  light from the ceiling versus a specular reflection from the floor. Part of the When a photodiode’s beam width is trade-off involves not seeing any unnec- larger than the desired spot size, essary light. Here’s how that works. which is usually the case, you can put an aperture or two of the appropriate COLLIMATION size between the photodiode and the According to their datasheets, IR spot. The apertures strip off light out- LEDs and photodiodes have a teardrop- side the acceptance angle, so only light shaped spatial response: maximum from the spot hits the photodiode. This along the forward axis and falling off reduces the total amount of energy on symmetrically around that axis. The the photodiode, but it can dramatically beam width is typically given as the increase the signal-to-noise ratio. angle where the response falls to half Typically, you build a simple collima- of the on-axis peak value measured in tor from a brass tube and shim stock current or power. The actual response washers. What most people don’t real- may have spots and lumps, but the ize is that you must make the inside model is a good start. of the tube nonreflective, because IR Common devices use an epoxy entering at an angle that ordinarily package, perhaps with filter dyes wouldn’t make it through the rear aper- WWW.GiURUMELE.Hi2.ROmixed in to reduce visible light. ture must be absorbed rather than Despite the datasheet information, bouncing around. Flat black paint is their response doesn’t fall off to zero good, but black construction paper is in any direction simply because the even better, particularly because you can entire package is transparent. The make the tube and apertures from the peak response may be to the front, but black paper without a machine shop. when you shine a light on the side or LEDs can be collimated the same way back of a photodiode, you’ll definitely with the same attention to reflections get (at least!) a small response from inside the tube. You need not seal the light bouncing around inside. When back of the collimator, because you gen- you’re trying to detect a weak reflec- erally won’t care about light leaks from

42 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com an LED. Even with a matched, filtered, Now you know why it’s so important collimated, and aligned optical system, to eliminate all extraneous light. A pho- many robots have trouble finding the todiode that works under dim light will walls. Let’s talk about energy. saturate in Oosting Gym’s ambient glare, but, paradoxically, may not be sen- DISTANCE sitive enough to see across the maze. Light sources follow the familiar inverse-square rule: the power incident CONTACT RELEASE on a given area decreases as the square of Everything you’ve seen so far operates the distance from a point source. A pho- at what’s effectively DC. The LED is todiode farther than a few meters away either continuously on or turned on as from a light bulb or a few centimeters needed. Ambient IR and visible light from an LED will follow the rule almost provide a high background level, and exactly. Laser beams follow somewhat even high-brightness IR LEDs are dim in different rules and pose different prob- comparison. The signal-to-noise ratio lems that I won’t consider here. can be extremely bad and well beyond An LED must put at least as much the capabilities of simple digital logic. power on a given surface as the ambient Next time, I’ll take a look at modu- light in order to be detected by simple lation and detection, which are analog circuitry. As the signal-to-noise ratio topics relevant to both RF and IR that drops, the circuitry must become more improve the odds of detecting a faint complex until, at some point, you sim- signal. Stay tuned! I ply don’t have enough signal no matter how clever you are. Many robots get into Author’s Note: I would like to thank trouble because their sensors are either William Beaty for the e-mail discus- too sensitive, not sensitive enough, or sion regarding IR filters and for provid- sometimes both at the same time. ing full spectrographic data for some Sunlight ranges from 100 to 400 W/m2 Lee filters. I would also like to and indoor illumination can be 0.1 to acknowledge Ken Boone, a Wizard- 10 W/m2. The lighting in Oosting Gym class roboticist, for providing hints and probably exceeds 10 W/m2, although tips. Ken’s article, “Building Organic you can see, with some difficulty, the Robots with Students,” shows how to spot a visible LED casts on a tabletop build an organic robot that’s ideal for from a few inches away. A typical IR classrooms, even if it doesn’t use IR. LED might reach 6 W/m2 at a distance of 6 cm, which gives you an idea of the problem! Ed Nisley, PE, is an electrical engineer The photodiode must detect reflect- and author living in Poughkeepsie, ed, not incident, light, which means it New York. You may contact him at “sees” all sources that contribute to the [email protected]. reflection. A Lambertian surface, such as the walls of the maze, reflects a frac- tion of all the overhead lights as well as RESOURCES from the nearby IR LED. That reflec- K. Boone, “Building Organic Robots tion will be much dimmer than a direct with Students: A How-To Lesson,” source, which is why collimation is so Circuit Cellar 128, March 2001. important: you must ensure your detec- Filter spectrographic data, tor doesn’t seeWWW.GiURUMELE.Hi2.RO anything other than www.amasci.com. the desired spot on the wall. Pop quiz: If an LED illuminates a Lee optical filter information, maze wall with 6 W/m2 at 6 cm, what’s www.leefilters.com/home.asp. the power level at 24 cm? Answer: Sony Electronics, Inc., DSC-F717: Because the distance increases by a fac- Cyber-shot Digital Still Camera, tor of four, the power drops by a factor of 2002, www.sonystyle.com. 42 to 375 mW/m2. The incident power goes from the high end of indoor illumi- Trinity College Fire-Fighting Robot nation to the low end just by moving Contest, www.trincoll.edu/ half the width of a maze corridor! events/robot/.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 43 FEATURE ARTICLE by Craig Beiferman

Flexible USB-CAN Bridge

FIRST PRIZE WINNER

When Craig decided that he needed a cost-effective, efficient way to control several micro- controller circuits from one computer, he used a PIC micro to design a USB-CAN distributed motion controller. Like many do-it-yourself endeavors, this project was born of necessity, so it’s inherently inexpensive and easy to follow.

Do you want the capability to con- USB has been growing in popularity, and an appropriate microcontroller. trol numerous microcontroller circuits for good reason: its simple plug-and-play I chose the 40-MHz PIC18F258 micro- from your computer? With this handy and high speed make for a great bus. controller from Microchip because of its project, now you “CAN.” In conjunc- At first, I was worried about how long built-in CAN 2.0B controller, which can tion with fellow designer Dale it would take me to develop drivers communicate at up to 1 Mbps. Its 32 KB Herman, I built an inexpensive circuit for a USB interface. I’m certainly not a of on-board flash memory and internal that allows a PC’s universal serial bus USB expert. That’s when I stumbled debugging capability make this an (USB) to interface to a controller area across Future Technology Devices extremely simple circuit for software network (CAN) bus. International’s (FTDI) FT245BM chip, development. The 10 MIPS of processing When it comes to communication which is a cost-effective device for power make it capable of transferring between multiple microcontrollers, I quickly interfacing a microcontroller to messages back and forth without break- cannot think of a nicer interface than the USB bus with little knowledge of the ing a sweat. (Note that my wife says it the CAN bus. You may be asking your- USB specification. The FT245BM allows takes me about 3 h to follow one self, why? What’s wrong with RS-232, a transfer speed of up to 1 MBps, and its instruction. So, I’m about 1011 times RS-485, SPI, or I2C? The simple reason 384-byte transmit and 128-byte receive slower. But enough about me.) is that if you really need full processor FIFO buffers allow for high data through- The 5-V power for the microcon- power, nothing will slow you down put. A parallel microcontroller interface troller comes directly from the USB like constant interrupts for every byte allows for the quick transfer of data. cable. Also, because the circuit is so received, not to mention the fact that But what about the drivers? No small, USB Implementers Forum the additional software overhead of problem. To my relief, I found out (USB-IF) recommends that if a device is packet decoding and checksum check- that FTDI supplies free Windows driv- light enough not to yank out the cable ing, ACK NAK schemes, and so on eat ers and example schematics. With my when it falls off a desk, you should processor bandwidth. The CAN link- fear subsided, I pressed on looking for attach the USB cable directly to the layer hardware handles board. This helps prevent many of these WWW.GiURUMELE.Hi2.ROissues in lost cables, saves the cost the background. 40-MHz ICD2 of the extra connector, and OK, so what’s the best 6-MHz Oscillator Port prevents miswiring. Resonator choice for communicating with a PC? Unfortunately, ADVANTAGES USB Bus CAN Bus the PC does not come stan- FT245BM PIC18F258 TJA1050 You’ll find CAN benefi- USB FIFO Chip Microcontroller CAN Transceiver dard with a CAN bus, and cial for several reasons. some manufacturers are First, note that all packets LEDs starting to phase out paral- EEPROM are filtered for their correct lel and RS-232 ports (par- node ID and others are ticularly on laptops). Figure 1—Several subsystems make up the USB-CAN board. For less than $30, you too ignored. (Firmware isn’t However, on the PC side, can have a high-speed USB-to-CAN bus. required, except for setting

44 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com up the message filtering.) In addition, retransmit automatically until at least the FTDI’s drivers. The message’s for- multiple transmit and receive buffers one node acknowledges that its data mat is extremely simple. I sent a 16- hold entire CAN packets (i.e., up to packet was successfully received. bit identifier (only the lower 11 bits 8 bytes of data and an 11- or 29-bit iden- Furthermore, the CAN bus trans- are actually used). Then, I sent from 0 tifier). Received messages are checked ceivers use differential signals, which to 8 bytes of data. The message is byte for proper CRC, and bad CAN packets laugh at external noise sources. The stuffed and then sent over the USB. will set error flags for recovery if neces- transceiver I used also suppresses tran- The byte-stuffed message will arrive sary. All transmitted messages are auto- sients on the CAN lines. Ha, ha, ha! in the FT245BM’s receive buffer. This matically appended with correct CRC. Do you want to learn more? Refer in turn causes the ’18F258 to read in Another benefit is carrier sense mul- to the Resources section of this article this message. The message is unstuffed tiple access with collision detection if you’re interested in gaining a more and loaded into the CAN transmit (CSMA/CD). For instance, when two in-depth understanding of CAN. buffer. The CAN link layer hardware Ethernet packets collide, both nodes internal to the ’18F258 continually have to retransmit after a random delay HARDWARE AND SOFTWARE transmits this message until another (yuck!). However, when two CAN pack- The hardware design is actually simple node acknowledges its reception. ets collide, the packet with the lower (see Figure 1). The schematics on FTDI’s After receiving a CAN message, the priority loses, and the original packet web site show its chips in numerous ’18F258 reads the CAN receive buffer continues to be sent as if nothing had configurations. I choose the schematic into RAM. This data is byte stuffed, happened (awesome!). The losing node with a 5-V microcontroller powered via and the message is transferred to the will attempt to retransmit automatically the USB bus. After adding a few extra FT245BM’s transmit buffer. The data sits after the other node has completed send- components like LEDs and the CAN in the FT245BM transmit buffer until ing its packet. Firmware isn’t required. transceiver, I was finished (see Figure 2). the PC’s USB drivers poll the FT245BM Moving on, note that hardware gener- The software on the PC side works to check to see if it has available data. ates an interrupt after receiving an with the firmware in the microcon- This polling is a weak point for USB, entire message packet. Hardware inter- troller to form a virtual bridge between because the USB slave node must wait rupts on an empty transmit buffer. With the PC and the CAN bus. This is the for a USB packet to indicate that it is three transmit buffers, you can really master node. All other nodes on the ready to begin transmission. But, you crank out the messages at full speed. bus are considered slave nodes. probably won’t notice this because the Finally, keep in mind that the CAN To send a message to the CAN bus, FTDI’s transmit buffer is so large. transmitter will continually try to the user’s program sends a message via Also, note that the polling rate is

WWW.GiURUMELE.Hi2.RO

Figure 2—A USB bus-powered circuit allows the high-speed microcontroller to easily provide a communications bridge between a PC’s USB and a CAN with up to 127 nodes.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 45 settable by FTDI’s drivers. This you to read. The microcontroller TRISC PIC, you’ll have to face the problem of polling period can drop as low as 1 ms. should be set to 0xFF, so it is an input knowing where the real message pack- port. Toggle RD from high to low to ets begin and end. For instance, if a INTERFACE TO THE FT245BM fetch the next data byte from FIFO. The byte were lost, how in the world Interfacing to the FT245BM is FT245BM will put data on the data bus would the firmware resynchronize straightforward. There are eight bidi- (D0 through D7). Finally, read port C to with the host? rectional data lines and four control a local variable to fetch data and tog- To solve this problem, I used a lines: RD, WR, TXE, and RXF. gle RD from low to high to return to straightforward byte-stuffing protocol: When transferring data back and forth the normal state. The FT245BM will to the chip, there are two tricks you’ll return its data port to high impedance. message need to remember. First, the data bus is bidirectional, so you must make sure CONFIGURING EEPROM that both the FT245BM and PIC18F258 The FT245BM has a serial EEPROM where the two bytes rep- data ports aren’t set as output pins at the (Microchip’s ’93C46B) attached direct- resent the beginning of transmission same time. Second, you should meet the ly to its output pins. The EEPROM and represent the end. timing requirements of the FT245BM isn’t needed for proper operation, but The message has an arbitrary length, chip when transferring data. (Note that if you would like to distinguish your and if any byte in the message con- the ’18F258 has a 100-ns instruction product from other vendors, it’s used tains a character, then a second time. This is code-dependent, so you to store vendor ID (VID) and product is inserted in the message should refer to the datasheet.) ID (PID), serial numbers, and so on stream. The inserted characters There are a few simple rules for inter- that are specific to your USB product. are not included in the facing to the FT245BM. When RXF goes Unfortunately, USB-IF wants to charge calculation, and the is low, there is at least 1 byte of data in money to rent a VID. Luckily, FTDI will the XOR of all the characters in the the FT245BM’s receive buffer waiting to let you use its VID and give you a few message. Refer to Figure 3 for an be read by the microcontroller. When PIDs to use for your product. When example of byte stuffing. TXE goes high, the transmit buffer is Windows checks the USB devices, the Using the simple byte-stuffing proto- full, so you should stop writing data to PID and VID are used to determine col, you can create a simple state the transmit buffer. Also, when a low- which drivers are loaded. FTDI also sup- machine in software to know if you to-high transition on the RD pin fetches plies a utility—FTD2XXST.exe—that have properly received a correct mes- the next data byte from FIFO, put the allows you to program these variables sage. After you have a complete mes- pin low again to have data placed on into the EEPROM via the USB. sage, you can pass the unstuffed mes- the data bus (D0 through D7). A high- Heed this warning: If you change sage to a handler function. Because to-low transition on the WR pin writes the variables, you may have to rein- both the PC and microcontroller have what is on the data bus (D0 through stall the drivers because the USB this potential synchronization problem, D7) to the transmit FIFO. device won’t be recognized. However, all of the messages passed between When you want to write data from in order to install these drivers, first them are byte stuffed. After I had the microcontroller to the FT245BM, you have to modify the FTD2XX.INF worked out the bugs pertaining to the you cannot write data to the FT245BM configuration file. The instructions are byte-stuffing and unstuffing functions, if TXE is high (i.e., the transmit buffer posted on FTDI’s web site. the communications were reliable. is full). Set *RD to high (to set the FT245BM data port to an input port) BYTE STUFFING WINDOWS USB DRIVERS and WR high. Also, change the micro- After you establish simple byte FTDI offers two choices for USB controller’s TRISC register to 0x00 (to communication between the PC and drivers. (Note that these drivers can- set port C as all outputs), and not be installed at the write the data byte you want same time.) I recommend to send to port C. Finally, set Original message: A B C using FTDI’s virtual the WR line low (a high-to- comport drivers when low transition WWW.GiURUMELE.Hi2.ROwrites the Bytes stuffed: DLE STX A B C CHKSUM DLE ETX you first complete your data to the TX FIFO buffer) Unstuffed: A B C hardware design. This and change the microcon- makes the USB port look Message that A B DLE C troller TRISC register to contains DLE: like another COM port. 0xFF (this sets port C as all To start a simple Bytes stuffed: DLE STX A B DLE DLE C CHKSUM DLE ETX inputs, or a safe state). HyperTerminal program, To read data from the Unstuffed: A B DLE C open a terminal window FT245BM to the microcon- and send and receive mes- Figure 3—You can take a string of characters and byte stuff them so the microcon- troller, keep the following sages over the USB just troller and host computer can regain synchronization immediately following a corrupted things in mind. If RXF is high, message. The included checksum ensures that corrupted messages are not acciden- like you would with any there is no data available for tally received. RS-232 device.

46 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com When you want to get serious, use [Identifier] is the address of the node CAN transceiver (the physical layer) FTDI’s D2XX drivers for Microsoft you want to send the message to can output a differential signal of Visual C++. The drivers let you (either 11 or 29 bits). [DLC] is simply either a dominant bit (0) or recessive exploit the full speed of the USB how many bytes are in the data field bit (1). The collision avoidance feature device, and they afford you a free (one (i.e., the data length code valid range, of CAN comes into play when a node of my favorite words) programming zero to eight). And, finally, [DATA] is tries to output a recessive bit and interface on the PC side! the 0 to 8 bytes of the data you want another node on the bus outputs a to send. How simple is that? dominant bit. The dominant bit CAN INTERFACE appears on the bus, and the transceiv- After getting the PIC to talk to the CAN PHYSICAL LAYER er that tried to output a recessive bit CPU via the USB bus, it was time to I used a Philips TJA1050 for the will recognize that its output isn’t turn my attention to the PIC18F258’s CAN transceiver. The device is inter- correct. Then, the CAN controller, or CAN interface. Luckily, Microchip had esting for several reasons. First, the link layer, will recognize this condi- much of the firmware already com- pleted. It was a simple matter to con- vert this code to the CCS compiler. Also, because of the complicated nature of debugging the CAN inter- face, I used a Microchip ICD2 debug- ger with good results. Unfortunately, if you’re a new developer writing CAN firmware, you’re stuck with a chicken- and-egg problem. If you don’t already have a CAN device to read and write CAN messages, you need to build two devices to test it. Luckily, I already had a separate PCI CAN card to which I could send and receive CAN mes- sages. And, luckily for you, I’m supply- ing you with working source code, so you should be able to send CAN mes- sages immediately without a problem. You may download the code from the Circuit Cellar ftp site. I think it is important to explain the CAN message format that you need to be concerned with. At first glance, a CAN message frame format is pretty complicated:

Idle [SOF][Identifier 11 or 29 bit][RTR][IDE][R0][DLC] [DATA 0 to 8 bytes][CRC] [ACK][EOF][IFS] idle

And don’t forget the bit stuffing. The CAN in Automation (CiA) web site contains an excellentWWW.GiURUMELE.Hi2.RO explanation of the fields. A good part of the CAN message is filled with extra bits, which you need- n’t concern yourself with. The bits are used by the CAN hardware to ensure reliable communications, and they should not worry you. For basic com- munications, there are only three fields that you should be concerned with: [Identifier], [DLC], and [DATA].

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 47 and you never need to worry again. (If Craig Beiferman earned a B.S. in only that were true!) Electrical Engineering and an M.S. in Computer Science from the University BOOTLOADER of Massachusetts at Lowell. Currently, The next problem arose because it’s he’s a senior electrical engineer at impossible make everyone happy, kSARIA Corp. When Craig’s not at which is something I learned in my work, he focuses on running DipChip previous career as an embedded soft- Electronics and spending time with ware engineer. So, I designed a boot- his two children, Zachary and Julia. loader program to allow for in-field You may reach him at craig- Photo 1—I hand-soldered the board. Note that the downloads of the program via the [email protected]. toughest parts to hand-solder are the 40-MHz crystal USB bus—the details of which are and the TQFP-32 package. better left to a future article. You may download the bootloader PROJECT FILES tion and stop attempting to transmit code for the CCS compiler from the To download the code, go to its message until the current message Circuit Cellar ftp site. Note that it ftp.circuitcellar.com/pub/Circuit_ is completed. took about 3 s to download the main Cellar/2003/157. With that said, when two nodes firmware via the USB bootloader. If attempt to communicate a message at you’re used to downloading with the the same time, the node that outputs a PICSTART plus, you should let out a RESOURCES dominant bit first has the highest priori- big sigh of relief. CAN Information, CAN in ty message. Thus, you must be careful Automation Organization (CiA), about how they choose to use the 11-bit BUILD THE UNIT www.can-cia.org. (or 29 bits for extended mode) identifier. Unfortunately, for some of you do-it- K. Pazul, Controller Area Network The lower the CAN identifier number, yourself people, the FT245BM comes (CAN) Basics, AN713, DS00713A, the higher the message priority. only in a surface-mount LQFP-32 Microchip Technology, Inc., 1999. Another thing to note about this package. However, with some careful CAN transceiver is that when the soldering and solder wick (for the USB Information, USB power is off, it will not disturb any inevitable bad soldering), you can hand- Implementers Forum, Inc., nodes that are running. It is short cir- solder this device yourself (see Photo 1). www.usb.org. cuit proof to VCC and to ground. The As you can see in Photo 2, I imple- bus pins are protected against tran- mented a CU-742-MB plastic enclosure sients, which allows for high-speed from Bud Industries. I had a machinist SOURCES traffic up to 1 Mbps and at least make the holes for the four LEDs, the CU-742-MB Utilibox 110 nodes to be connected together. USB cable, and the D-Sub connector. Bud Industries, Inc. Now it’s your turn. Go ahead and (440) 946-3200 ICD2 INTERFACE build one yourself! If you want a www.budind.com I added a five-pin header to interface jumpstart, kits are available on the Compiler to the debugging port on the PIC DipChip Electronics web site CCS, Inc. microcontroller. For all of you PIC (www.dipchipelec.com). I (262) 797-0455 fanatics out there, I highly recommend www.ccsinfo.com purchasing the ICD2 debugger. The simple serial debugger may not pro- FT245BM Interface Chip vide lots of breakpoints or advanced Future Technology Devices debugging functions like the ICE4000 International (not that I really know, the ICE4000 is +44 141 353 2565 a little out of my price range). But the www.ftdichip.com ICD2’s simpleWWW.GiURUMELE.Hi2.RO interface makes it easy ICD2 Debugger, PIC18F258 to download your latest firmware into microcontroller, and ’93C46B EEP- flash memory. Having a couple of real- ROM chip time breakpoints in your code seems Microchip Technology, Inc. to be more than adequate for most (480) 786-7200 debugging. And, if you are used to www.microchip.com ultravioletly erasing your microcon- trollers, it’s time to celebrate. Never Photo 2—I had the plastic enclosure machined to TJA1050 CAN Transceiver chip accommodate the board, which is designed to fit in the again will you have to pry your chip Philips Semiconductors box. The four holes in the corners of the PCB line up out of its socket with a small screw- with the screw holes in the plastic enclosure. This pro- (408) 991-3773 driver. Just solder in a blank device, vides a secure fit. www.philips.com

48 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by Roy Franz The WiFi SniFi Sniffing In and Out of Wireless Networks

Are you having trouble locating 802.11b wireless networks? Don’t worry. Roy has the perfect solution. The WiFi SniFi is a compact, easy-to-build device that can “sniff” out wireless net- works and display the appropriate packet information.

The WiFi SniFi, which I pronounce able PCMCIA interface in hardware, Refer to the Resources section of this “wiffy sniffy” for the fun of it, sniffs even if you’re working with some- article for a few useful links. out 802.11b wireless networks and thing other than a wireless LAN card. I had a difficult time finding displays captured packet information The design’s user interface may detailed PCMCIA information on the (see Photo 1). This little device can require some adaptation for other appli- ’Net, but I obtained a lot of useful remain quiet on the network or asso- cations, but it could be useful in a wide information from F. Imdad-Haque’s ciate with an access point and act as a range of designs. The user interface con- book, Inside PC Card: CardBus and network node. In Monitor mode, the sists of a scroll wheel taken from a PCMCIA Design. In addition, you can WiFi SniFi can listen to a specific mouse and a single push button. Roll the download the 802.11b specification channel or scan all of the channels. wheel to scroll through menu items and from IEEE (www.ieee.org). The big news is that the WiFi SniFi press it to select items. Use a separate Important aspects of the microcon- performs these functions without a push button to clear entries. The inter- troller include its on-board 32-KB flash high-powered microprocessor. In fact, face is simple, compact, and easy to use. memory and 512-byte RAM. The appli- one of its main advantages is that it cation code resides in the on-board flash generates a large amount of function- WHAT’S INSIDE? memory. Most significantly for this ality from its 8-bit, 5-MHz microcon- The WiFi SniFi couldn’t be simpler troller. Wireless local area networks (see Figure 1). Most of the necessary (WLANs) operate at much higher resources are inside the NEC Elect- speeds than the microcontroller, but ronics µPD78F9418 microcontroller. the WiFi SniFi manages to nab the all- The only major external components important management frames. It include a 4 × 20 LCD, a 128-Kb EEP- even grabs some of the data frames. ROM that’s used for saving captured Even if you don’t want to nab ‘n’ grab WLAN frames and device configura- WLAN frames, you might find some tion data, the mouse wheel, and an useful hardware and software nuggets in Intersil Prism 2-based PCMCIA WLAN the WiFi SniFi that apply to other types card. These are on a board I built that of microcontroller designs. I created the attaches to an NEC KORE9418 devel- WiFi SniFi as part of the 2002 Esprit de opment board (see Figure 2). KORE contest, which was sponsored You can deliver power to the WiFi by NEC Electronics America, so the SniFi with batteries, an AC adapter, or device is a demoWWW.GiURUMELE.Hi2.RO that shows how to a car cigarette lighter adapter. Either leverage microcontroller resources to of the latter two power sources will achieve surprising results. charge the batteries. The voltage mon- If you savor the kind of minimalist itor indicated in Figure 1 is used for design techniques that squeeze the most monitoring the battery’s charge state. out of system resources, you might The WLAN card acts as a basic appreciate this design’s interfaces with 802.11b node. I designed the WiFi its input switches, PCMCIA card, and SniFi without formal documentation Photo 1—The WiFi SniFi uses a PCMCIA card to interact serial EEPROM. You can easily reuse for this card, but you can get informa- with wireless networks, a small LCD to display packet con- the software for the PCMCIA interface tion about it from the various open- tents, and an old mouse scroll wheel to get user inputs. in applications that don’t have a suit- source device drivers available for it. An 8-bit, 5-MHz microcontroller runs the entire thing.

50 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com design, the microcontroller has PCMCIA channels overlap and inter- 43 I/O pins, including multiple Card fere with one another, so A/D input channels. I used one only three WLANs can oper- 16-bit Data of the A/D channels to monitor 6-bit Address ate unhindered in one area. battery voltage. If you are used 9-bit Control A WLAN can operate in Input to working with microproces- switches either Infrastructure mode Four switches sors, the microcontroller pres- (wheel, (BSS mode, where the net- buttons) NEC 1-bit Clock Serial ents a somewhat different Electronics work is controlled by an 1-bit Data EEPROM µPD78F9418 Voltage monitor interface task because it has no Analog in access point, or AP) or Ad (resistor network) external data or address buses. Hoc mode (IBSS mode, Most of the I/Os on this partic- 8-bit Data where there is no access 3-bit Control ular microcontroller are gener- point). The service set iden- al-purpose ports, which means tifier (SSID) is a string that that they adapt to different pur- LCD identifies a WLAN. Stations poses under software control. only associate with an AP Figure 1—The WiFi SniFi consists of few components other than the 8-bit micro- (or another station in Ad controller, which implements the PCMCIA interface in software. The microcon- WiFi SniFi CAPABILITIES troller includes a hardware LCD controller/driver. Some of the LCD I/Os are shared Hoc mode) that has the same To understand what the WiFi with other devices. SSID. When you turn on a SniFi does, you need to know a station such as a notebook few facts about 802.11b-based WLANs. device keeps up, which probably has a computer with a wireless card, the sta- These wireless networks operate in the lot to do with the large amount of tion scans all the channels checking for 2.4-GHz frequency range and offer a buffering the wireless card performs. a beacon frame that has the station’s maximum physical-layer signaling rate With the ability to buffer several dozen SSID in it. This beacon frame identifies of 11 Mbps. Although real-world net- packets in its internal memory, the card the channel and the address of the AP works achieve only 6 or 7 Mbps of greatly eases the timing constraints of that the station is seeking. If the sta- throughput, the data rates are rather interfacing to the microcontroller. tion finds no such beacon frame, it can- high for a 5-MHz system to handle. In The 802.11b networks in the U.S. not join any networks, so no wireless fact, it is interesting to see how well the can use 11 channels. All but three communication is possible.

WWW.GiURUMELE.Hi2.RO

Figure 2—The WiFi SniFi board is designed to mate with the four 20-pin headers that the KORE development board provides. The MAX3222 is used for debugging serial out- put and providing a negative voltage source to drive the LCD.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 51 LCD. The frame number increments until the EEPROM is full (containing 255 saved frames). Then, the WiFi SniFi continues to display frames without saving them. Use the Clear Captured Frames configuration menu option to clear the EEPROM. You can set the WiFi SniFi to capture or ignore a specific type of frame, including contention-free control frames (CF-Ack, CF-Poll, CF- Ack+CF-Poll, CF-End, CF-End+CF-Ack). To join a network with the WiFi SniFi, you must configure two fields in the configuration menu: the SSID, which is a string that identifies sta- tions that are logically on the same network, and the IP address. Then, you can select the network node mode in the configuration menu. If the WiFi SniFi successfully associ- Figure 3—The linear regulator keeps the power design simple. The Clear switch is a separate switch, while the ates with the AP, the “link status other three are part of the mouse scroll wheel. change: connected” message will appear on the LCD. At that point, the WiFi The WiFi SniFi has two basic modes. information displayed varies based on SniFi is ready to respond to ARPs and It can find and monitor a wireless net- the type of frame, because not all of the pings. The system displays but does not work by capturing management and data fields are present in every frame type. capture the received frames. Also, note frames. Or it can associate with a net- The WiFi SniFi is best adapted for cap- that the WiFi SniFi does not support work, display frames, and respond to turing management frames, which are the WEP encryption that is increasingly pings and address resolution protocols, or generally small. The system can save used to secure 802.11b WLANs. ARPs, which are named for mapping an and display most of the information in The WiFi SniFi does not need a net- IP address to a physical machine address. these frames. Management frames mask to associate with a WLAN because The WiFi SniFi won’t give you Internet include beacons, probe requests/respons- the device does not initiate network traf- access, but it does enable you to poke es, association requests/responses, reas- fic. The WiFi SniFi has no concept of a about the landscape to find the WLANs. sociation requests/responses, disassocia- local versus nonlocal IP address. When You can do so by placing the WiFi SniFi tion, authentication, and deauthentica- a frame is received, the WiFi SniFi in Monitor mode and listening for tion. Management frames are often the responds to the source MAC and source frames. When frames come in, the WiFi most interesting from a network-trou- IP addresses within that frame. SniFi displays them on the LCD and bleshooting point of view because stores them in nonvolatile memory. You they control the process of joining and USING THE WiFi SniFi can configure the WiFi SniFi to listen leaving networks. Before getting into how some of the on a specified channel or scan all of When it’s monitoring, the WiFi SniFi WiFi SniFi’s features work, let’s look the channels by selecting channel zero displays the current saved frame num- at how you can use them. The WiFi via the user interface. Because of the ber in the upper right corner of the SniFi has a simple interface consisting overlapping channels, frames are often received while listening on a channel other than the one they were transmitted Down Up on. Most frames do not indicate which channel they whereWWW.GiURUMELE.Hi2.RO transmitted on, but Switch 0 management frames such as beacons include this information so the stations Switch 1 know which channel to use. You can also control the types of frames that the system displays and saves. Because data frames tend to be Detent Detent Detent fairly large, the WiFi SniFi can display only a portion of their content on the 4 × Figure 4—As you rotate the scroll wheel, two switches open and close to generate the waveforms. Detents are stopping points on the wheel that you can feel as you rotate it, and both switches are in the high or low state at each 20 LCD. Similarly, the EEPROM stores detent. If you analyze which waveform goes high or low first, you can tell which way the wheel is rotating. By detect- only part of each data frame. The type of ing wheel-up and wheel-down events, software can iterate through menu items and packet listings on the LCD.

52 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com of a Clear button and the ex-mouse Note: Actions performed on transitions are in parentheses. Names match source code. scroll wheel. Pressing the scroll wheel Waiting for Detent state activates a switch that is used as a Select button. 01 If you press the Select button in S wit normal operation, you’ll enter the De ch te 0 * (sa nt ve b = WiFi SniFi configuration menu. Then, d it S e w t e i W t n c you can roll the wheel up and down t h bit 1 bit 0 h v e a 1 n l e u to cycle through the configuration l w S e 0 1 o w ) d i h menu selections. The top line of the l tc itc e h 1 ≠ Sw

00 e 11 h

LCD displays the current configura- w f

o nt-bit p e tion item, and the bottom three lines Initial det Detent u =

state l = Found

e h

c display a short help message. Pressing e it state h w the scroll wheel selects the currently w S n = r = u t h displayed menu option. When you e c

t Switch 0 == Switch 1 R i

w ≠ 1

select an item, you can edit its value. detent bit S l

e e ) 10 t 0 The way you edit menu items h i w b h r c i t t d i depends on the context. Sometimes dir-bi e (sav w ≠ S 1 you select a value from several fixed Switch choices. Other times you need to enter a value, such as the SSID or IP address, in which case, you must change the Moving state value of a character by rolling the Waiting for move to complete wheel up or down. Figure 5—The state diagram describes the way software handles inputs from the scroll wheel. As soon as the Pressing the Select button moves software state machine detects a valid wheel-up or wheel-down event, the software looks for the next event. the cursor one character to the right, and the Clear button moves left. If you in the captured frame buffer. As you one input of each switch low. I con- press the Clear button when the cursor can see in Photo 1, I labeled the fields nected the other switch input to the is all the way to the left, you’ll cancel above the LCD. The information dis- microcontroller input and pulled it high the editing of the field. Pressing the played in the remaining three lines of with a resistor. As a result, the I/O line Select button while in the right-most the LCD depends on the type of frame is high when the switch is open and position accepts the displayed value. that’s involved. If you configure the low when the switch is closed. To stop SSID editing, scroll to a space WiFi SniFi to scan channels, it displays The switches open and close at differ- character and press the Select button. the channel it is listening to each time ent wheel positions; therefore, if you During normal network node or the channel changes. rotate the wheel at a constant speed, monitor operation, the Clear button In network node mode, the LCD dis- the switches produce the waveforms clears the LCD, leaving it blank until plays ARP and ping frames as they are shown in Figure 4. These out-of-phase the WiFi SniFi has new information to received. The WiFi SniFi does not save waveforms allow you to tell which way display. When you browse captured these frames to the captured frame the wheel is rotating. From the detent frames, the wheel selects the frame to buffer. When the status of the wireless marked “Up,” for instance, you’ll know be displayed. Pressing the Select but- connection changes (i.e., when the the wheel is rotating upwards if switch 0 ton toggles between two screens of WLAN card associates or disassociates goes high before switch 1. frame information, although some with an AP), the WiFi SniFi displays a Figure 5 describes the way I dealt frames have only one screen. message indicating the new status. with the wheel states and transitions. Because the LCD is small, the Note that the 2-bit values for each screen displays frame information in a THE MOUSE WHEEL state keep track of whether the state compact manner, using abbreviations The mouse scroll wheel handles machine has found a detent or is wait- for many fields.WWW.GiURUMELE.Hi2.RO You may download a almost all of the WiFi SniFi’s input ing for one; these values do not reflect list of these abbreviations and other needs. Only one other switch is need- the values of the wheel switches. terms from the Circuit Cellar ftp site. ed to act as the clear input. The wheel Aside from the initial state, the state They may prove useful for under- is also extremely easy to design in. machine includes three operating standing 802.11b-type networks. Rotating the wheel opens and closes states. The first state, Detent Found, In Monitor mode, the top line of the two switches (see Figure 3). The wheel involves waiting for a move (11). When LCD displays the same information for has small detents at regular intervals you enter this state, you save the value all frame types: the type of frame, the that you can feel as you rotate the of the switches, so you can tell whether channel that the card was configured wheel. Both switches are in the same or not a complete move has occurred. for when the frame was received, the state at each detent (both open or both The value also helps detect missed signal strength, and the frame number closed). In this implementation, I tied transitions. After exiting the state, save

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 53 one of the switch values so you know which way the wheel is moving. Listing 1—The code that implements the state machine shown in Figure 5 uses polling to obtain the con- The second state, Moving, entails dition of the scroll wheel switches. The code uses an interrupt for the WiFi SniFi’s Select button. It’s the only interrupt in this design. waiting for a move to end (10). A move is complete when you reach another //Get button (and switch) state, debounce inputs detent. If you return to the same bs = pollButtons(); //bs.WHEEL0 bs.WHEEL1 are the detent, you might have only rocked wheel switch inputs the wheel slightly, or you could have //State machine for scroll wheel (four possible states) missed several transitions. If you reach if (GS_WHEEL_STATE_1_BIT) another detent and a move is complete, { return the correct action code and tran- if (GS_WHEEL_STATE_0_BIT) { sition to the third state, Waiting for Detent. Even though you reach a //State 11: Detent Found, waiting for move, which is indicated by detent, the calling code may do some- the two wheel switches having different values thing as a result of returning an action if (bs.WHEEL1 != bs.WHEEL0) { code. So, to be on the safe side, look for GS_WHEEL_STATE_0_BIT = 0; //Go to state 10 a new detent when you are called again. GS_WHEEL_DIR_BIT = bs.WHEEL1; //Save direction The Waiting for Detent state involves } waiting for both switches to have the } else same value. When they do, transition { to the Detent Found state. Even if you //State 10: Moving and waiting for move to complete. Move is find a detent when you leave a state complete when both wheel switches are the same value (i.e., you (10), you need to wait for another have reached another detent), and this value is different from the previous detent value. If it’s equal to the previous detent, detent because a significant amount of you’ve either missed some events or the user only slightly moved time may have passed since you left the the wheel, and let it return to the original detent. previous state. Finally, note that the if (bs.WHEEL1 == bs.WHEEL0) initial state (00) allows the state { //Either go to Waiting for Detent (if you detect a move) or machine to operate properly with the waiting for a move (if you’re back at the original detent) state variable initialized to zero. GS_WHEEL_STATE_0_BIT = 1; The state machine tracks changes in if (!(bs.WHEEL1 == GS_WHEEL_DETENT_BIT)) a way that includes error checking. { //You’ve moved, so take action, and set the next state to Waiting The machine waits for a detent after for Detent. Even though you’re at a detent, you will likely detecting a move to make sure the have work to do, which will delay your next poll of the switch move ended. After a move, if the wheel states. If the wheel is being scrolled quickly, you may miss ends up back in its previous state, the many transitions. GS_WHEEL_STATE_1_BIT = 0; //Go to state 01 state machine returns no action. If the //Move complete. Action! move generates a different value, the if (GS_WHEEL_DETENT_BIT == GS_WHEEL_DIR_BIT) machine returns a wheel-up or wheel- return(BA_wheelUp); //Wheel up down event so software can appropri- else return(BA_wheelDown); //Wheel down, or else ately iterate through the menu items. go to state 11 Software polls the wheel switches } to detect changes, and the polling must occur often to keep up with } } rapid wheel movements. The wheel’s } Select switch activates an interrupt. else Listing 1 shows the code associated { with the scroll wheel. if (GS_WHEEL_STATE_0_BIT) WWW.GiURUMELE.Hi2.RO{ //State 01: Waiting for Detent. When wheel is in a detent PCMCIA INTERFACE position, both wheel switches have the same value. The microcontroller in the WiFi if (bs.WHEEL1 == bs.WHEEL0) SniFi interfaces to the WLAN PCM- { GS_WHEEL_STATE_1_BIT = 1; //Go to state 11 and CIA card via the microcontroller’s save detent value general-purpose I/Os (see Figure 6). GS_WHEEL_DETENT_BIT = bs.WHEEL1; The same is true for the I2C interface } to the serial EEPROM. Therefore, I } else implemented these interfaces in soft- { (Continued) ware. Listing 2 shows the code for the PCMCIA interface. The code is suit-

54 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO able for reuse in any application that involves a PCMCIA card. Listing 1—Continued. You may download a list of the sig- //State 00: initial state of state machine. This state is not nals in the PCMCIA interface from the necessary, but it’s implemented so that all possible state Circuit Cellar ftp site. The PCMCIA values are handled properly. It’s used at startup because the interface is asynchronous, so the micro- global state variable is initialized to zero, and this way you controller works well as the timing mas- don't have to initialize it to a special value. Go to state 01 Waiting for Detent. ter for the I/O bus. After looking at the GS_WHEEL_STATE_0_BIT = 1; PCMCIA timing diagrams, I initially } thought that I wouldn’t need delays in the read and write routines, but I found } it necessary to poll the *HWAIT line. return(BA_noAction); //If you make it here, nothing has happened. The polling loop probably exits after the first time the *HWAIT signal is polled, because putting a few NOPs in place of the polling loop also worked reliably. Listing 2—A direct interface between an 8-bit microcontroller and a PCMCIA card is a rare thing, especially To put the card into I/O mode, you when the interface does not use any PCMCIA byte operations. The code shown here implements the entire need to set the COR register appropri- interface using the microcontroller’s general-purpose I/Os. ately, because all PCMCIA cards power //Perform a 16-bit read of I/O space @param addr address to read up by default in Memory Only mode. from @return value read from card Because I had hard-coded the COR reg- __callt norec unsigned int ioRead(unsigned char addr) ister address, I did not need to read the { unsigned int temp; information from the attribute memo- //Configure K0 data port to Input mode ry to determine its location. To put the DATA_H_PORT_MODE = INPUT_PORT; card in I/O mode, however, I found DATA_L_PORT_MODE = INPUT_PORT; that I had to read the COR register //Set up address ADDR_0_3_PORT = addr; before writing it. As a result, the OE ADDR_4_5_PORT = (ADDR_4_5_PORT & ~ADDR_4_5_PORT_MASK) | signal had to be connected and used for ((addr>>4) & ADDR_4_5_PORT_MASK); the attribute memory read operation. //Move these to one register. REG- could be an OR of CE1- and I also discovered during the course CE2-, as REG is low during both I/O cycles and attribute memory cycles. Can REG- be tied low? Reg, ce* can be set low at the of development that I did not need to same time the address is presented. change the signals (*CE1 and *CE2) hreg, ce1, ce2 low #if 0 that control whether a bus access is for //CE1- and CE2- signals are always low, so you only perform 16- the high byte, low byte, or both. I can bit accesses CE_1_PORT_BIT = 0; tie the signals low because I am always CE_2_PORT_BIT = 0; performing 16-bit accesses. Even though #endif attribute memory is only 8 bits wide, REG_PORT_BIT = 0; //REG- may also be able to be tied 16-bit accesses ignore the upper 8 bits. low, not checked //Set IO read low. Implementing an 8-bit PCMCIA inter- IORD_PORT_BIT = 0; face would have reduced signal count only minimally and would have compli- #ifndef PCMCIA_SIM cated the development. The WLAN card while (!HWAIT_PORT_BIT); //Wait for hwait- high #else is documented to support 8-bit interfac- NOP(); ing, but I could not find information on NOP(); implementing the 8-bit option. Many of NOP(); the card’s internal buffers use autoincre- #endif menting of 16-bit addresses, so 8-bit //Read data operations on theWWW.GiURUMELE.Hi2.RO registers would raise temp = DATA_H_PORT; special cases. Implementing an 8-bit temp = temp << 8; interface also requires the use of *CE1, temp |= DATA_L_PORT; IORD_PORT_BIT = 1; *CE2, and A0, which is always zero //reg/ce1/ce2 high because all of the accesses are 16 bits. #if 0 Thus, the total interface width would CE_1_PORT_BIT = 1; only decrease by 5 bits. CE_2_PORT_BIT = 1; #endif Although the WLAN card decodes REG_PORT_BIT = 1; 10 address lines, six suffice for access- return(temp); ing all of the addresses required to } operate the card, with the exception of

56 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO the COR register in attribute memory. to handle the sharing with greater care. power supply for the PCMCIA card. Because the register access is the only The WiFi SniFi uses only one inter- (The design’s linear regulator is simple operation that needs the top four rupt line, and it’s for the Select but- but inefficient.) The PCMCIA card is address bits, I tied the lines to the val- ton. I wanted the button to be respon- by far the system’s largest power drain, ues required to access the COR register. sive to user inputs without continual so turning off the card while browsing Even though I connected the A0 line to high-frequency polling. That leaves captured frames would greatly the microcontroller, the connection is the main loop free to continuously improve battery life. unnecessary because the 16-bit-only poll the WLAN card, and it does so at In a similar vein, the WiFi SniFi accesses make all of the addresses even. a high enough frequency to keep up could use a more sophisticated charg- If you want to support generic PCM- fairly well with the packets. ing circuit. The microcontroller’s ana- CIA cards, you’ll need more address The other switch inputs—the wheel log input could monitor battery tem- lines to parse the card information and Clear—are polled fast enough to perature with a thermistor (along with structure (CIS) in attribute memory so be responsive after the WiFi SniFi is the voltage monitoring currently you can determine the card capabilities in Menu mode. Therefore, they do not implemented) to enable faster charging. and the COR register location. For the need to be interrupt-based. In addition to specific WiFi SniFi WiFi SniFi, I determined the COR regis- improvements, the device’s core func- ter address in the Linux development EXPANSION POSSIBILITIES tionality could be developed into a environment and hard-coded the address Every design leaves you wishing you platform that allows for the addition in the WiFi SniFi implementation. could do more. For the WiFi SniFi, it of wireless networking to a variety of The PCMCIA interface’s high pin would be nice to include a simple state- microcontroller-based designs. As the count did not pose a big problem, less TCP Internet server for downloading WiFi SniFi project proves, you can go because I reused most of the signals for captured frames to a PC. Additionally, wireless with a surprisingly small interfacing to other peripherals. For you could use the microcontroller’s seri- amount of hardware. I instance, 10 of the 11 bits in the LCD al port for interfacing to a GPS receiver, interface are shared with the PCMCIA so the WiFi SniFi could automatically Roy Franz earned a B.S. in Computer data bus. Polling the PCMCIA card record the location of wireless networks. Science from the University of eases the resource sharing. You could The WiFi SniFi’s power management California, Davis. He’s been developing still share interface pins in an inter- could be improved with a switching software for embedded systems for rupt-driven design, but you would have regulator and microcontroller-managed more than 10 years. His technical inter- ests include low-level code that inter- faces with hardware as well as systems that interact with their environment. When time permits, Roy enjoys hiking and rollerblading. You may contact him at [email protected].

PROJECT FILES To download the code and addi- tional files, go to ftp.circuitcellar. com/pub/Circuit_Cellar/2003/157.

RESOURCES F. Imdad-Haque, Inside PC Card: CardBus and PCMCIA Design, Butterworth-Heinemann, Newton, WWW.GiURUMELE.Hi2.ROMA, 1996. Host AP driver information hostap.epitest.fi/ SOURCES PRISM 2 WLAN Card Intersil Corp. www.intersil.com

µPD78F9418 Microcontroller Figure 6—The PCMCIA interface connects directly to the µPD78F9418’s I/O pins. The data bus lines are used for NEC USA, Inc. both the PCMCIA interface and the LCD, which works because they both have separate enable signals. www.necus.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 59 FROM THE BENCH by Jeff Bachiochi Spotlight on the Renesas H8 Family Hitachi and Mitsubishi Market MCUs for Embedded Systems

Whether you design medical, communications, or automotive components, you’re sure to find numerous applications for Renesas Technology’s H8 family of devices. So, before you begin your next project, you should familiarize yourself with the company’s vast suite of H8 products. To do so, take a look at Jeff’s comprehensive survey of the H8 family members and their specs.

“Effective April 1, 2003 Hitachi MEET THE H8 FAMILY cuit. The devices also include low-cost Semiconductor America has merged The H8 selection guide has nearly emulators that are available for real-time with the system LSI operations of 350 different microcontrollers to debugging when you’re using resources Mitsubishi Electric U.S. and created choose from. Trying to choose the built in the target hardware. Renesas Technology America, Inc.” right device for your application is The H8 family was designed for Hmm, that wasn’t exactly what I such a daunting task that you may be low-power, high-performance embed- had expected when I first attempted to inclined to look elsewhere. To help ded systems in the consumer, indus- access Hitachi’s web site. Upon further whittle down the giant H8 oak, I’ll trial, medical, communication, and investigation, I found that Hitachi and show you how a few typical devices automotive markets. The family Mitsubishi had reached an agreement stack up against one another. ranges from the 8-bit low-cost, low more than a year ago to integrate their The devices I’ve chosen are all avail- pin count, super low-power devices up LSI businesses. Utilizing the core able with flash memory. You’ll find that to the latest 64-bit, high-performance strengths (e.g., microcontrollers, logic, advantageous when developing applica- devices (see Figure 1). In this column, analog, and discrete devices) of both tions because you can change the code I’m concentrating on the 8- and 16-bit companies, the new enterprise plans to and update the device even when in-cir- MCUs in the H8 family and leaving concentrate on the mobile, network, automotive, and digital home elec- tronics markets. H8 MCU Family Renesas is organized into three areas: H8SX High performance, low power, wide range of peripherals MPU, SoC, and SiP; mixed-signal, RF, 32 bit and discrete devices; and flash memory H8S/2300 H8S/2600 and SRAM. The MPU line includes H8S/2200 H8S/2100 33 MHz 33 MHz 20 MHz Hitachi’s 4-, 8-, 16-, and 32-bit micro- 20 MHz General Automotive LCD, USB computers. The H8/SuperH family of LPC/ISAI/F purpose applications 16 bit microcontrollers touts upward code H8/300H compatibility throughout the entire fam- H8 Tiny le WWW.GiURUMELE.Hi2.RO20 MHz 25 MHz patiab Motor control ily. Smack dab in the middle of the fami- Low pin count de-com CAN, POR, LVD ard co ly stands the H8 8- and 16-bit devices. Upw This month, I will spotlight a num- 8 bit H8/300 SLP ber of devices within the H8 family. H8/300L 8 MHz With this information, you will be able 8 MHz LCD Low power Super-low power to make some sense out of the vast sea of Renesas devices. You’re sure to find this information to your advantage if Peformance/features you’re planning on entering a project Figure 1—Be sure to study the performance versus features lineup of the H8 family of MCU/MPUs. Although the in the Renesas H8 Design 2003: natural technological progression is for bigger, better, and faster devices, these are not reasons to choose only Everywhere You Imagine contest. from the newest devices for a particular design.

60 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com the high-performance 32- and 15 0 7 0 7 0 and decrease by one. Word reg-

64-bit SuperH group for E0 R0H R0L isters increase and decrease another time. by two (MOV R0, @-R1). Renesas combines fast E1 R1H R1L In Absolute mode, the in- H8/300L MCU speeds, ROM or flash E2 R2H R2L struction specifies the absolute H8/300L SLP memory, power-down modes, address of the operand in low EMI, and a convenient E3 R3H R3L memory (MOV R0, H’FF00’: development environment E4 R4H R4L 16). Immediate mode uses the with more than 100 different 8- or 16-bit value within the on-chip peripherals. As a E5 R5H R5L instruction as the operand H8/300H result, the H8 family is one E6 R6H R6L (MOV #H’1000’: 16,R1). H8/Tiny of the industry’s best cost- When the program flow is E7 R7H R7L per-performance values. A (SP) interrupted by a branch few of the industry-standard 31 15 0 instruction, the new PC value 23 15 interfaces that are supported PC is based on the old PC and a 2 include UART, SPI, I C, IrDA, 70 displacement. PC Relative

CAN, and smart card. CCR mode allows branching by byte or word displacements 7 0 H8S/2100 FAMILY ARCHITECTURE EXR H8S/2200 (BEQ @(+10:16,PC)). Jump The H8 uses a general-reg- H8S/2300 instructions can use Memory 63 41 330 ister architecture that con- Indirect mode, in which the Sign extension MACH sists of control and general- instruction holds the absolute MAC MACL H8S/2600 purpose registers (see Figure 2). 31 (only H8S/26xx) 0 address of a location where the The entire family has operand is located in memory Figure 2—The H8 family CPU is register-based. The general registers can be used 57 basic instructions that as data and address registers. The control registers include a 16-bit program PC (JMP @@(#H’0010’: 16)). treat the general registers as and a CCR. Note that upwardly compatible devices add to this base architecture. The H8/300L MCU has both data and address regis- 57 instructions including mul- ters. The eight general-purpose 16-bit containing the address of the operand tiply (byte × byte) and divide (word/ wide word registers (R0 through R7) in memory (MOV R0, @R1). byte). Table 1 separates these into their are accessed as eight high-byte and The Indirect with displacement respective functions. There are four eight low-byte registers (R0H through mode is similar to Indirect mode. basic MCU states. Figure 3 shows how R7H, and R0L through R7L). The last However, a second word (bytes 3 and 4) these states relate to one another. register, R7, serves as the stack point- contains a displacement that is added Any state applying power or activat- er that controls the stack space. to the content of the specified general ing the hardware reset can place the The control registers include a 16- register to obtain the operand address MCU in the reset state. When released bit program counter (PC) and an 8-bit in memory (MOV R0, @(2:16,R1). from reset, state transfer can only go condition code register (CCR). The Indirect with postincrement or pre- to the exception handler state, which PC’s least significant bit is ignored for decrement mode is also similar to the can execute priority code and transfer all instruction fetches because every- Indirect mode, but the general register control to the program execution state thing is based on 16-bit instructions. containing the operand is either incre- or place the MCU back in reset state. The CCR holds the status of operations mented after the instruction is execut- The normal code execution is per- except for the interrupt mask bit (I). ed or decremented before the instruc- formed in the program execution Upwardly compatible family members tion is executed. Byte registers increase state. From the program execution add extra functions to the basic CPU (i.e., 32-bit double-word registers). The 16-bit values are stored MSByte Function Instructions Number first on the even address boundaries. The WWW.GiURUMELE.Hi2.ROData transfer MOV, PUSH, POP 3 H8 family uses eight addressing modes: Arithmetic operations ADD, SUB, ADDX, SUBX, INC, DEC, ADDS, SUBS, DAA 14 Direct; Indirect; Indirect with displace- DAS, MULXU, DIVXU, CMP, NEG ment; Indirect with postincrement or Logic operations AND, OR, XOR, NOT 4 predecrement; Absolute; Immediate; Shift SHAL, SHAR, SHLL, SHLR, ROTL, ROTR, ROTXL, ROTXR 8 Bit manipulation BSET, BCLR, BNOT, BTST, BAND, BIAND, BOR, BIOR 14 PC Relative; and Memory Indirect. BXOR, BIXOR, BLD, BILD, BST, BIST In Direct mode, the register field Branch BCC, JMP, BSR, JSR, RTS 5 of the instruction specifies an 8- or System control RTE, SLEEP, LDC, STC, ANDC, ORC, XORC, NOP 8 16-bit general register containing the Block data transfer EEPMOV 1 Total: 57 operand (MOV R0, R1). Indirect mode has the register field of the instruction Table 1—Although POP and PUSH are available instructions, they are identical to a MOV using indirect with specifying a 16-bit general register postincrement or predecrement addressing (i.e., MOV.W R0, @-SP).

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 61 state, control can transfer to the Reset Subsleep mode freezes the CPU reset state, exception state, or cleared while the time base function of Reset state Exception-handling state program halt state. The program Reset TimerA, TimerC, TimerF, TimerG, halt state has various power- occurs SCI, AEC, and the LCD con- Reset Interrupt reduction modes and can only Reset Interrupt troller/driver operate on the sub- occurs occurs occurs occurs Exception- transfer to the reset state or the handling clock. In Watch mode, the CPU program exception state. complete halts, and the time base function

Program halt state Program execution state of TimerA, TimerF, AEC, and the H8 SERIES OPTIONS Sleep instruction LCD controller/driver operate on The entire H8 family is based on executed the subclock. the aforementioned CPU architec- Figure 3—The MC has four states. Now you know where execution In Standby mode the CPU and ture, and it is divided into a series can be transferred between states. all of the on-chip peripheral func- of devices with similar purpose. tions are paused. Module Standby Each series contains devices with differ- bility make the device ideal for battery- mode allows individual on-chip periph- ent peripherals. Each device is available powered hand-held applications that eral functions specified by software to with varying memory size and type. require a customized or standard LCD. enter Standby mode. Take a look at the differences in the If you require long battery life, you A number of I/O bits are responsible flash memory devices listed in Table 2. can reduce current consumption by for setting the MPU’s programming Each device was chosen from one of placing the micro in Sleep mode. Power mode. In User mode, flash memory pro- four different H8 series. Table 3 lists is a function of the amount of time gramming is handled via user program the special features of each series as well the micro spends in Operating mode control by 1- and 28-KB erasures and as a few sample applications that may be between sleep cycles. In many applica- 128-byte block writes. In Programmer appropriate for devices within the series. tions, the oscillator stabilization period mode, the MPU is programmed using To save space, I combined function is longer than the actual time of code a PROM programmer. diagrams of the devices into one chart execution before going back to sleep; In Boot mode, boot code is executed (see Figure 4). Use the chart to learn therefore, it’s a major factor in current that uses the UART (TX/RX) to com- how the devices stack up function for consumption. The oscillator stabiliza- municate with an external host pro- function. As I describe each device, tion time for the SLP series is on the gram. The boot code auto bauds on refer to Figure 4 and the combined order of microseconds as opposed to incoming data (H’00’), and acknowledges memory map in Figure 5. milliseconds, so it can save precious and erases the flash memory. (Note that power at each wakeup. the data rate is automatically deter- H8/300L SLP SERIES There are three clock speeds for pro- mined by analyzing the datastream via The H8/300L super low-power series gram execution. In Active High Speed the auto baud process.) The host indi- runs on reduced voltage (some devices mode, the CPU and all of the on-chip cates the length of the code (word) it down to 1.8 V). Most are in the 3- to 5-V peripheral functions are enabled, and wants programmed followed by the data. range. Multiple power-down modes, execution occurs via the system After all of the data has been acknowl- module standby, dual clocks, and fast clock. In Active Medium Speed mode, edged, the MPU can reset to User mode oscillator stabilization times help reduce the CPU and all of the on-chip periph- for user program execution. power consumption to a minimum. On- eral functions are enabled, and execu- chip LCD drivers and an internal voltage tion proceeds via a divided system H8/TINY SERIES booster simplify external LCD interfac- clock. Finally, the CPU executes from The H8/Tiny series has an internal ing. High-current output can drive LEDs the subclock in Subactive mode. 16-bit architecture that runs on 3 or without an external current driver. The sleep instruction has seven pos- 5 V. (An internal step-down unit is used The 300L SLP includes several sible power-down modes. Sleep in when 5 V is supplied.) The general peripherals: 8- and 16-bit multipur- High Speed mode halts the CPU while registers are increased to 32 bits wide pose timers, an asynchronous event the on-chip peripherals function via the (double word), which can be used as counter, 10-bit PWM, a serial commu- system clock. Sleep in Medium Speed 16/16-bit registers, 8/16-bit registers, nications interface,WWW.GiURUMELE.Hi2.RO a watchdog timer, mode stops the CPU while the on-chip and 16/8-bit registers. and a 10-bit A/D converter. The low- peripherals functions via the divided Additional functions were added to power consumption and LCD drive capa- system clock frequency. the basic H8 instruction set to make

H8 Series Device CPU Pins Speed (MHz) Instructions RAM Flash memory Address space

300L 38024 8 bit 80 8 55 (57) 1 KB 32 KB 64 KB H8 Tiny 3687 16 bit 64 20 62 (64) 4 KB 46 KB 64 KB 300H 3048B 16 bit 100 25 62 (64) 4 KB 128 KB 16 MB H8S 2329 16-bit static 120 33 63 (65) 32 KB 384 KB 16 MB

Table 2—The four devices represent a sampling of the wide range of technology available within the H8 family.

62 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com MOTOROLA and the Stylized M Logo are registered in the U.S. Patent and Trademark Office. All other product or service names are the property of their respective owners. © Motorola, Inc. 2003. This product incorporates SuperFlash® technology licensed from SST. DURACELL and the colors copper and black as applied to a battery are registered trademarks of The Gillette Company and are used with its permission. xesv eilcmuiainwt Cs P,ad1I 1 and SPI, 1 SCIs, 2 with communication serial Extensive • nertdtidgnrto 2 irnFahmemory Flash micron .25 third-generation Integrated • pt rgambetmrcanl /cne-o deaindPWM edge-aligned or center- w/ channels timer programmable 8 to Up • noaieo-hptigradtaedbginterface debug trace and trigger on-chip Innovative • 0btaao-odgtlcnetrdw o18V 1.8 to down converter analog-to-digital 10-bit • ihpromne8btHS8CUcr u o2 aieMIPS) native 20 to (up core CPU HCS08 8-bit High-performance • OGO ATR LIFE. BATTERY ON LONG PERFORMANCE, ON BIG THAT’S MCU 8-BIT AN NOW C0 eeoe Kit Developer HCS08 oeadat aeu ie oe–tenew the are MCUs – HCS08 mode timer wake-up auto and mode mode power management multiple of advantage Taking one bit. performance sacrificing without – to V down 1.8 operate that additions new with 8-bit MCUs of family Motorola’s expanded We’ve ntuto yl t2 H u.Adyul speed to you’ll time And your bus. MHz minimum 20 ns at 50 cycle instruction as fast as performance with that ihPoesrExpert combined Processor be with can and hardware, debug buffer trigger and on-chip innovative with come also They battery. CS8B&G AIYKYFEATURES KEY FAMILY GT & MC9S08GB WWW.GiURUMELE.Hi2.RO akt eas h C0 aiyis family HCS08 the because market, eindt e h ototo any of out most the get to designed s–a20nA TM owr o o oa.Lanmr o tmotorola.com/mcu at combination now powerful more that Learn put today. to you need for you work information to and tools the has Kit Developer HCS08 our – life battery longer and performance Big-time products. sensor and analog Motorola all with compatible uocd eeao.All generator. auto-code power-down 2 C oiydm oeo eeo e oe rga n eu using debug and program code, new develop or code demo Modify • CS8B0dmntainboard demonstration MC9S08GB60 • hog B eilpr n nlddcable included and port serial DB9 through reCodeWarrior free atr-prtdwt ulR22sra ot,sice,LEDs, switches, ports, serial RS232 dual with Battery-operated – ml rttp ra n eosrto code demonstration and area, prototype small ® eeomn ut o CS0 pca Edition Special HC(S)08 for Suite Development CO XED ATR LIFE BATTERY EXTENDS HCSO8 Peripherals for this device include a H8 Series Special features Applications real-time clock, 8- and 16-bit timers, 2 38024 Super-low power Utility meters PWM, UARTs, I C, and a 10-bit A/D LCD Drive Glucose meters converter. The H8/300H series is suit- Low EMI Bar code scanners able for home appliances and electron- High EMS Battery-powered security devices ics, small DC motor control, the Single-supply flash memory HVAC Home electronics mechanical control of office machines, 3687 Low pin count Kitchen appliances and automotive control modules. Small packages Home electronics Dual synchronous/asynchronous Single-supply flash memory Automotive control systems UARTs and an I2C interface (master/ POR Motor controllers LVD slave) give the ’3687 plenty of commu- CAN nication power. There are eight analog 3048B External SRAM bus HVAC inputs to the 10-bit ADC. A conver- DMA Controller Industrial control systems sion takes a maximum of 134 clock Single-supply flash memory Motor controllers Motor control unit cycles. Single and continuous conver- 2329 Smart card interface Label printers sions are handled on a single- or mul- Single-supply flash memory CD R/W Drives tiple-channel basis. Power-on reset, a DMA Controller GPS Systems watchdog timer, and low-voltage On-chip debugger Blood oxygen monitors LAN Hubs detection circuitry help keep the MCU’s operation stable. Table 3—I’ve decided to highlight four groups within the H8 family. Designed with specific features, each series is Two clock speeds are available for aimed at a particular market segment. program execution. In Active High Speed mode, the CPU and all of the use of the 16-bit architecture. These down modes, module standby, dual on-chip peripheral functions are include signed multiply and division, clocks, and fast oscillator stabilization enabled, and execution occurs via byte-to-word and word-to-double word times help reduce power consumption. the system clock. The Subactive sign extension, as well as software inter- High-current output can drive LEDs mode has the CPU executing from

rupt vectors (TRAPA). Multiple power- without an external current driver. the subclock. C/P TCP/IP

NEW Products

µFlashTCP-EP* LogicFlex* Dual-E* LogicFlex-EPX* Solutions 10Base-T Ethernet 10Base-T Ethernet 2 Ethernet Ports 10Base-T Ethernet 2 Serial Ports 2 Serial Ports 2 Serial Ports 2 Serial Ports 7-34 VDC 46 Digital I/O’s 3 Counter / Timers 16 Opto-Isolated inputs Optional I/O Interface Programmable Xilinx CPLD 5 Digital I/O’s 16 Relay Outputs @ 500mA ea. Rugged Enclosure w/ Hardware Clock/Calendar Onboard Connectors Quick-Disconnect Connectors WWW.GiURUMELE.Hi2.ROIndustry Standard Expansion Bus for USNET TCP/IP Rack Mount Enclosure Connectors Peripheral Boards Software in Kits LCD & 6 Pushbuttons Starts at $229 Starts at $189 Starts at $199 Starts at $499

*All products based on the Intel 386Ex with DOS and NE2000 compliant, 10Base-T Ethernet. Standard memory includes 512K RAM & 512K Flash plus DIP socket to accept an M-Systems DiskOnChip. Development systems contain necessary hardware and software tools for fast development. Tools to Move Data

JK microsystems connects you with embedded control solutions. Our cost-effective DOS based controllers are ideal for data acquisition, networking or industrial technology applications.

1403 Fifth St., Suite D Visit us on the web www.jkmicro.com JK microsystems, Inc. Davis, CA 95616 USA Call 530-297-6073 Fax 530-297-6074

64 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO The sleep instruction has USER after the data has been six possible power-down recognized. modes. Sleep in High Speed mode halts the CPU while H8/300H SERIES the on-chip peripherals func- The H8/300 series has a tion via the system clock. 32-bit architecture similar to Subsleep mode halts the CPU the H8/Tiny; however, with while the time base function a 64-KB address space, the of TimerA, TimerC, TimerF, ’3048 can make full use of TimerG, SCI, AEC, and the the 23-bit PC and 16-MB LCD controller/driver operate address. The address space on the subclock. In Watch can be divided into eight mode, the CPU stops, and the areas, each with separate bus time base function of specifications. Enhanced TimerA, TimerF, AEC, and addressing and instructions the LCD controller/driver Photo 1—Renesas’s HEW has the GUI interface most software engineers are help make full use of the familiar with. Project generator wizards help you move through configuration operate on the subclock. In options quickly, so you can get right at the application code. address space and 32-bit data Standby mode, the CPU and registers. A 16-bit DRAM all on-chip peripheral func- controller has multiple tions freeze. Module Standby mode block erasures in addition to 128-byte refresh modes. A direct memory access allows individual on-chip peripheral block writes. Note that this is similar (DMA), integrated timer unit (ITU), and functions specified by software to for the H8/300H and H8S series. timing pattern controller (TPC) were enter Standby mode. Programmer and Boot modes operate added to the standard UART, ADC, and A number of I/O bits are responsible in the manner described in H8/300L DAC peripherals. for setting the programming mode for SLP section of this article. To reiterate, The ’3048 series handles apps that the MPU. In User mode, flash memory the host indicates the length of the require additional processing power. It’s programming is handled under user pro- code (word) it wants programmed fol- useful for HVAC, AC motor control, gram control by 1-, 8-, 16-, and 28-KB lowed by the data. The MPU resets to color copiers, and diagnostic equipment.

WWW.GiURUMELE.Hi2.RO

66 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com (*STBY), thereby disabling internal 32-kHz clock peripherals and placing outputs in a CPU high-Z state. This is also accom- System clock H8/300L H8/300H H8/300H H8S/200 plished through Software Standby mode by setting the SSBY bit in the

RAM Flash memory SYSCR register before going to sleep. In User mode, flash memory program- 1 KB 4 KB 4 KB 32 KB 32 KB 56 KB 128 KB 384 KB ming is handled under user program

8-bit Timers A/D converter (channel/bits) control by 1-, 28-, and 32-KB block erasures and 128-byte block writes. 3 3 2 8/10 8/10 8/10 8/10 Because this handles up to 64 KB of 16-bit Timers D/A converter (channel/bits) 1 2 5 6 2/8 2/8 code and the ’3048 has 128 KB of flash PWMs (channel/bits) memory, you cannot directly use this method to program the additional 64 KB. 2/10 6/16 1/14 5/16 Data transfer controller (channels) You must supply code that will establish Asynchronous event counter (8/16 bit) 85 a new boot format to accept data and 2/1 DMA Controller (memory-I/O/memory-memory) 4/2 place it anywhere in the flash memory Real-time clock Programmable pulse generator (bit) address space (i.e., the S-record file).

16 H8S SERIES UARTs Time pulse unit The H8S/2000 series CPU has a 1 2 2 3 Timing pattern controller 32-bit architecture that can cover a 2 I C 16-MB address space. Address space Integrated timer unit can be divided into eight areas each

I/Os/high current with separate bus specifications. Interrupts (external/internal) 66/6 53/8 78/28 95 Enhanced addressing and instructions 13/9 38/11 30/7 52/9 help to make full use of the address space and 32-bit data registers. Watchdog Smart card interface Key 38024 A DRAM interface handles up to

3687 8 MB of DRAM. A direct memory access LCD controller (segment/common) (DMA), data transfer controller (DTC), 32/4 3048 and timer pulse unit (TPU, which is 2329 similar to the ITU), and programmable pulse unit (PPG, which is similar to Figure 4—Use this combined function comparison chart to learn how the devices stack up against each other. You the TPC) are added to the standard should be able to select a device based on the application requirements. UART, ADC, and DAC peripherals. The ’2329 series takes on applica- The DRAM controller produces the The 16-bit ITU has five timer chan- tions that require more processing CAS and RAS signals in support of 8- nels. The ITU allows for synchronizing power. You’ll find it useful for touch- or 9-bit column address multiplexing. the timers (i.e., five synchronized PWM screen controllers, CD R/W drives, The on-board bus controller allows outputs) and triggering the TPC, which medical monitors, LAN hubs, GPS external devices requiring different can output 16-bit data (groups of 4 bits) systems, and bar code scanners. bus specifications to live in harmony synchronized with the ITU. In addition The DRAM interface produces all of by segregating them into one of eight to the dual standard UARTs, the ’3048 the CAS and RAS signals to support address areas. Each area can have spe- contains a smart card (SC) interface. external DRAM in address areas two cific wait states generated for them. The asynchronous serial clock and data through five. The on-board bus con- The bus master also arbitrates bus I/O format of the SC interface is similar troller allows external devices requir- rights between WWW.GiURUMELE.Hi2.ROthe CPU, DMAC, refresh to the asynchronous UART 8-bit format ing different bus specifications to live controller, or an external bus controller. with parity. However, the receiving in harmony by segregating them into The DMAC transfers up to 64 KB of device can indicate a parity error (dur- one of eight address areas. Each of byte/word data one time in a block ing the normal stop bit time) for an these areas can have specific wait move (or to the same address), or it automatic retransmission of data. states generated for them. repeats the operation continuously. The ’3048 has three power-down The bus master also arbitrates bus DMA Short mode uses an 8-bit source states for reducing power consump- rights between the CPU, DMAC, and 24-bit destination. Long mode uses tion. Sleep mode halts the CPU while DTC, or an external bus controller. a 24-bit source/destination. The DMA on-chip peripherals function via the The DMAC can transfer up to 64 KB has resources for four short or two long system clock. Hardware Standby mode of byte/word data once in a block DMA channels that run simultaneously. requires a logic low on the input pin move (or to the same address), or it

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 67 can repeat the operation 64 KB. You must supply continuously. DMA Short Address 38024 3687 3048 2329 code for a new boot format. mode uses an 8-bit source H'000000' Interrupt vectors Interrupt vectors Interrupt vectors Interrupt vectors H'000029' and 24-bit destination, and H'00002A' Flash memory SUPPORT TOOLS Long mode uses a 24-bit H'000041' Renesas offers products to Flash memory source/destination. H'000042' cover each stage of your H8 H'0000F3' Therefore, the DMA has H'0000F4' Flash memory development. Low-cost or resources for four short or H'00016F' no-cost tools enable quick two long DMA channels H'000170' investigation of H8 capabili- H'007FFF' that run simultaneously. ties. The Hitachi Embedded H'008000' Not used Flash memory The DTC is similar to H'00E7FF' Workshop (HEW), which is DMAC because it’s used H'00E800' User RAM a software and debugging H'00EFFF' for transferring data. H'00F000' Not used environment, puts the However, unlike the H'00F01F' power of your PC to work DMAC, the registers used H'00F020' Internal I/O by providing a familiar GUI H'00F02B' registers for transfer control are atmosphere in which to H'00F02C' Not used located off the DTC and in H'00F6FF' write your application. You (on-board) RAM. Although H'00F700' Internal I/O can use assembly or C/C++ H'00F73F' registers the throughput is nearly H'00F740' to assemble or compile a LCD RAM six times slower, it is not H'00F74F' file that’s ready for down- limited to the 4/2 chan- H'00F750' Not used loading on known working H'00F77F' nels of the DMAC. hardware (either your own H'00F780' Work area for Work area for The 16-bit TPU has six H'00FB7F' reprogramming reprogramming design or one of the many flash memory flash memory timer channels. The TPU evaluation boards). H'00FB80' User RAM User RAM allows for the synchroniz- H'00FDFF' Photo 1 shows the HEW ing of the timers (i.e., mul- H'00FE00' environment on my laptop. H'00FF7F' tiple synchronized PWM From here I can create a H'00FF80' Internal I/O Internal I/O outputs) and triggering of H'00FFFF' registers registers project, edit it, make it, the PPG. The PPG can H'010000' and debug it. HEW is free output 16-bit data (groups H'01FFFF' (sorta, kinda). It comes H020000' Not used of 4 bits) synchronized H'05FFFF' bundled with some evalua- with the TPU. H'060000' Not used tion kits, and it’s either In addition to the three H'0FEF0F' time or size limited. If you H'0FEF10' User RAM standard UARTs, the ’2329 H'0FFF0F' want the full version— contains an SC interface. H'0FFF10' Not used which includes a simula- H'0FFF1B' The asynchronous serial tor, profiler, map editor, H'0FFF1C' Internal I/O clock and data I/O format H'0FFFFF' registers and stack analyzer—you of the SC interface is simi- H'100000' will need to upgrade lar to the asynchronous H'FF7BFF' through a distributor. H'FF7C00' User RAM UART 8-bit format with H'FFFBFF' The Hitachi Debugging parity, except the receiving H'FFFC00' Not used Interface (HDI) launches device can indicate a pari- H'FFFE4F' from the HEW. With the H'FFFE50' Internal I/O ty error (during the nor- H'FFFF07' registers HDI, you have a common mal stop bit time) for an H'FFFF80' Not used GUI to any of the supported H'FFFF27' automatic retransmission debugging platforms, a H'FFFF28' Internal I/O of data. H'FFFFFF' registers ROM-resident monitor, an There are twoWWW.GiURUMELE.Hi2.RO clock on-chip emulator, or an in- speeds available for pro- Figure 5—Note that the address scale on this memory map comparison is not linear. circuit emulator. The serial gram execution: Active The ’3804 and ’3687 are limited to 64 KB, but the ’3048 and ’2329 can address 16 MB. port allows you to down- High Speed mode and load a ROM monitor and Active Medium Speed mode. In User mode, flash memory pro- take control of executing your code. The ’2329 has three power-down gramming is handled via user program You can read/write registers and states to reduce power consumption. control by 4-, 32-, and 64-KB block memory as well as execute your Like the H8/300H series, the H8S series erasures and 128-byte block writes. code with a breakpoint. On-chip features Sleep, Hardware Standby, and Because this series handles up to emulators connect via resources built Standby modes. Additionally, the 64 KB of code and the ’3048 has 128 KB into the target hardware to provide a H8S series includes Programmer and of flash memory, this method cannot be debugging interface for real-time Boot modes. used directly to program the additional debugging. The PCI- or PCMCIA-

68 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com based emulators offer 255 break- ment toolkit (FDT) is a free stand- will help you get your application up points, multiple-level execution trace, alone, easy-to-use utility. The FDT and running, debug it, and make code and source-level debugging. uses the aforementioned in-circuit changes without ever removing the For advanced real-time debugging, programming functions. The MPU MPU from its target PCB. an in-circuit emulator presents more uses a serial interface and has a built- In following with its well-known ways to track down illusive bugs. in boot function, which allows the slogan “Inspire the Next,” Hitachi Emulation memory is mapped to the flash memory to be erased and code has seen fit to join with Mitsubishi in target processor’s address space, the to be downloaded and executed. separating their semiconductor opera- 32-KB trace buffers can be examined After a program exceeds the 64-KB tions into a new LSI giant. With this during execution, and event sequenc- size of the internal boot code loader, extraordinary base, Renesas has begun ing is possible via a complex event things get more complicated. The exploring new horizons. For them, system (CES). The CES lets you specify FDT takes care of downloading a boot inspiration moves beyond the next and the exact set of conditions you want kernel to takeover from the boot code into “Everywhere You Imagine.” I to examine. Break, trace, or timing and handle the programming of larger functions are triggered using event or flash memories. range criteria. Up to 12 hardware Jeff Bachiochi (pronounced BAH- breakpoints can be triggered via com- CHOICES key-AH-key) has been writing for plex event and range conditions or Don’t be intimidated by your first Circuit Cellar since 1988. His back- four user-logic inputs. glance into the vast sea of Renesas H8 ground includes product design and The event sequencer is used to gen- products. After you have an applica- manufacturing. He may be reached erate an event based on the proper tion in mind, surfing the product at [email protected]. sequence of other events. This flexi- lines will allow you to focus on the bility gives the in-circuit emulator correct MPU based on peripheral the means to track down even the requirements. SOURCE nastiest of bugs. Evaluation PCBs are available for H8 Microcontrollers If you merely want to get your code each series. On-chip emulators and an Renesas Technology America, Inc. into an H8 without all the emulating in-circuit emulator are also available. (408) 433-1990 hardware, the flash memory develop- The flash memory microcontrollers www.america.renesas.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 69 APPLIED PCs by Fred Eady Mission Possible: Achieve Cheap USB Connectivity

Exorbitant USB licensing fees and the high price of analysis tools have denied many of you access to the USB marketplace. A champion of the individual designer, Fred is on a mission to prove that it’s possible to achieve personal USB connectivity without breaking the bank.

I just received a PICkit 1 Flash starter official USB web site are useful for pre- company’s actions indicated that it isn’t kit, and, to my surprise, the program- paring a product for USB certification. interested in showing you its products. ming interface is USB! Imagine that— USB license fees are small change to So, I’ve decided to prove that you can a USB port on the most basic of large companies. Unfortunately, $2500 obtain personal USB connectivity with- Microchip’s development boards (see or even $1500 may prevent a smaller out spending tens of thousands of dollars Photo 1). Although I think the PICkit enterprise from entering the USB mar- on license fees, lab certifications, USB 1’s USB programming port is a good ket, because the license fee is just a vendor logos, and expensive USB analy- thing, I still have some problems with small part of what is needed to seri- sis tools. I am officially on a mission. USB when it comes to pulling a per- ously develop USB devices. sonal USB project together. I had wanted to show you some of TRACKING DOWN USB Thanks to folks like Microchip, the devices, so I contacted a well- After I had decided to write this Cypress, and National Semiconductor, known producer of USB analyzers. The article, I set out to find a suitable and USB hardware is relatively cheap and company’s least expensive analysis tool inexpensive USB analysis tool. To do easy to obtain. All of the companies go runs for approximately $8000, and its so, I started my e-mail engine and out of their way to provide useful exam- top-of-the-line USB analyzers top out donned my telephone headset. In less ple code, and some even offer compre- at more than $30,000. There are several than a day, I located and obtained the hensive USB tutorials aimed at their negative words I could use to describe holy grail of USB, an Ellisys USB products. On the other hand, if you our conversations. Anyway, as you read Tracker 110 (see Photo 2). want to market a USB-equipped product, this article, you won’t find any of the The USB Tracker 110 is a small hard- you have to either fork out $2500 per company’s equipment pictured or men- ware device that traps, decodes, and dis- year to join the club (i.e., USB tioned. The bottom line is that the plays a USB datastream flowing between Implementers Forum) or obtain the USB device being tested and a USB vender ID (good for two a PC. Installing the USB Tracker years) for a measly $1500. Either 110 was a snap: I downloaded the way, your product must pass var- latest version of the analysis soft- ious tests to be certified. When ware, UsbShow (www.usbtracker. the words “test” and “certifica- com), and after a few mouse tion” are used, it usually means clicks, the USB Tracker 110 soft- more money outWWW.GiURUMELE.Hi2.RO of your pocket ware and driver set were installed. that has to be offset by raising The next step involved con- the product’s market price. necting the USB Tracker 110 to You can’t get something for the analysis computer. After the nothing, and I’m sure the USB standard “I have found a new license fees are used to enhance USB device” Windows message the processes and tools imple- had appeared, I manually direct- mented by the USB development Photo 1—The PICkit 1 Flash starter kit is designed to program and read the ed the installation wizard to community. It looks like the pro- new 14-pin flash memory PICs and the legacy 8-pin flash memory parts. The install the USB Tracker 110 PICkit 1 comes with an extensive software and firmware library that includes ceeds are being put to good use, source code for the host and PIC USB interface. I populated the snap-off drivers that I had previously because the free USB tools on the part of my PICkit 1 with a Sipex SP232ACP and supporting components. downloaded. I got a magic wand

70 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com from the Windows installation wizard, of the MPLAB IDE. Although being able and the USB Tracker didn’t smoke, so to run PicBasic Pro and MPLAB in a sin- all was going well. gle IDE is a good thing in terms of devel- This is a good place to pause the USB opment, there is another upside to this Tracker 110 discussion and comment union: PicBasic Pro generates a standard on the USB hardware I collected for .cod file that allows for debugging using analysis. I have two USB development the MPLAB ICE 2000 hardware. boards and a PICkit 1 that can connect After plugging in the MPLAB ICE Photo 2—You don’t need anything but this little box, a to my newly acquired USB Tracker 110. downloadable software application, and three USB 2000 PCM16XQ1 USB processor mod- Let’s begin by looking at ME Labs’s cables to help unlock the mysteries of USB. It costs ule and attaching a 40-pin DIP device PICProto USB development board. less than $900. attachment module to the end of the processor module’s cable, I carefully PICProto USB On the PICProto USB development plugged the MPLAB ICE 2000 device The reader response to my column board, the 28-pin PIC16C745 IC sock- attachment’s gold-plated 40-pin DIP titled “A P89C668 Development Board et lies inside the 40-pin PIC16C765 IC header into the 40-pin header socket for 8051 Fans” was enough to tell me socket. I wanted to be able to mount that I had installed on the PICProto that the BASIC programming language either the 40-pin PIC16C765 or the USB development board. Then, I is—as it relates to the 8051, PIC, and 28-pin PIC16C745 on the PICProto jumpered the PICProto USB develop- AVR—alive and well (Circuit Cellar USB development board. So, I used ment board for USB-supplied power. 151). ME Labs offers a good PIC BASIC machined header pins to populate the At that point, I loaded the PicBasic compiler called PicBasic. I got a copy of 40-pin socket pads instead of a standard Pro USB demo, USBMOUSE.BAS, in the PicBasic Pro because it’s more than a 40-pin socket. This allowed me to sol- MPLAB IDE. I couldn’t get a good reset decent BASIC compiler. The professional der a standard 0.3″ 28-pin socket inside on the MPLAB ICE 2000. After clicking version is relatively inexpensive, and it the 40-pin socket footprint. My com- the MPLAB IDE Run icon a few times supports Microchip’s flavor of low-speed pleted PIC-less PICProto USB develop- without success, I figured that some- USB, which is driven by the PIC16C745 ment board is shown in Photo 3. thing wasn’t working correctly. and PIC16C765 microcontrollers. Because there is no “F” in their names, I first took the software problem The PICProto USB development the PIC16C745 and PIC16C765 micro- determination route. (After all, my sol- board was refreshing because I had to controllers are available as either dering should be perfect.) I muddled build it completely from scratch. I had windowed ultraviolet erasable parts or around, trying this and that with files to fly in two components, a 6-MHz one-time programmable (OTP) parts. I and such with no joy. OK, maybe I did ceramic resonator and a series-B USB have a fancy timer-equipped EEPROM have a problem with the PICProto USB connector. Otherwise, the through- eraser, but I’ve been spoiled by the easy- development board hardware. So, I dis- hole assembly process was quick and to-program, flash memory-based PICs. connected the PICProto USB develop- easy. A schematic and bill of materials Because the new generation of flash ment board and took it to the bench for are included with the bare silk- memory-based USB PICs wasn’t avail- a look under the magnifier. As I had screened PICProto USB PCB. able when I started this article, I used expected, all was well with the solder- For a complex interface, the USB the MPLAB ICE 2000 and a PCM16XQ1 ing job and component placement. hardware is just as simple as basic RS- processor module to stand in for the I did not cut any of the default 232 hardware. In fact, I’ll go out on a windowed PIC16C745 and PIC16C765. limb and say that a PIC-based USB hard- Before attempting to read the PIC- ware interface is actually simpler than a Proto USB development board’s USB PIC-based RS-232 hardware interface. datastream with the USB Tracker 110, The PIC16C745 and PIC16C765 USB it may be a good idea to check to see if microcontrollers are self-contained and all of the solder joints took. A small don’t require any of the auxiliary level- USB demo program that moves the test shifting circuitry that is common for computer’s cursor is included with the true RS-232 implementations.WWW.GiURUMELE.Hi2.RO Using PicBasic Pro compiler. I loaded that the PIC16C765 or PIC16C745, a bare- puppy into the MPLAB ICE 2000 to bones USB hardware interface consists see if I could twirl the cursor. of the PIC, a couple of 0.1-µF bypass Using the MPLAB ICE 2000 instead capacitors, a VUSB filter capacitor, a of the real thing required that I invoke ceramic resonator, a resistor, and the the MPLAB IDE. Normally, that would series-B USB connector. Even though have meant loading and running a sep- the PIC USB solution provides for a arate IDE for the PicBasic Pro compil- Photo 3—All of the goodies that complement the every- simpler hardware interface, USB com- er. Not in this case. The PicBasic Pro day PIC are included with this board. There are a couple of potentiometers, a pair of LEDs, and two push-button munication requires much more effort compiler is capable of running as a lan- switches. The 25-pin connector pad layout suggests that to implement. guage toolset within the latest version a serial-to-USB thing could happen in the prototype area.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 71 to compiling the USB demo include file (16C765.INC) to fool the code and controlling a cur- MPLAB IDE assembler, but the MPLAB sor. Well, not quite on my IDE assembler didn’t bite on the con- way. I clicked the MPLAB tents of the newly monikered file. IDE’s Build icon and was I checked my Win2K path variable greeted with what seemed and indeed the entry for the Microchip to be a million error mes- MPLAB IDE include files was there. sages, which wasn’t good. Without question (I was desperate), I My first clue was the first simply copied the Microchip-provided error, which stated that it MPLAB IDE P16C765.INC and could not open a particular P16C764.INC include files into my include file, P16C765.INC. PicBasic Pro USB project directory. That’s easy enough, I said to Here we go. After clicking on the myself. I’ll just rename the MPLAB IDE Build icon, I was hum- PicBasic Pro 16C765.INC to ming my favorite Bob Marley tune, P16C765.INC and things “Jammin’.” After another click on the will once again be good. Ha! MPLAB IDE Run button, I was grow- My mouth was still open ing dreadlocks. The test machine’s cur- when the dust stirred by a sor was going in circles and dancing to million more error mes- the reggae beat. It was good indeed. sages had settled. OK, maybe the list file would BACK ON TRACK(ER) reveal an answer. Duh. My If you’re a drag racing fan, you know second clue was on the first that most of the real work is done in Photo 4—I wanted to show you the USBInit instruction and the MPLAB ICE 2000 breakpoint. Now you should have an idea of how error line of the listing. the pits before the race. The same can PicBasic Pro fits inside an MPLAB IDE session. Note that only two MPASM header was the be said for working with USB. Before PicBasic Pro USB commands are used, USBInit and USBOut. comment beside the lost powering up the PICProto USB develop- P16C765.INC file. ment board, I reread Jan Axelson’s jumpers on the PICProto USB develop- You can configure the PicBasic Pro to book, USB Complete: Everything You ment board. The only live jumper pins use either the MPLAB assembler Need to Develop Custom USB were the power-source pins. I decided (MPASM) or the internal PicBasic Pro Peripherals. [1] In addition, I perused to reattach the MPLAB ICE 2000 and assembler (PM). Well, there’s a big check the Microchip USB documentation and move the powered-by jumper from mark in the “Use MPASM Assembler” datasheets to get the particulars on the USB to external. The MPLAB ICE 2000 box under the MPLAB IDE’s project PIC16C765 and PIC16C745 USB micro- reset was successful, and I was able to build options. I had renamed the PM controllers. A good collection of USB configure the MPLAB ICE 2000 to use the PICProto USB development board’s power and clock. Obviously, the emu- lator and associated electronics drew a bit more current than the USB was willing to supply at that point. Despite the little drawback, it was good. I had already created a project directo- ry and copied the USBMOUSE.BAS file into it. A study of the USB documenta- tion that was included with the PicBasic Pro compiler indicated that I would need to add supportingWWW.GiURUMELE.Hi2.RO files to the project as well. These files, which were included with the compiler, pro- vide a basis for the USB hardware layer that is intended to reside in the PIC firmware. The PicBasic Pro USB support files are based on the original Microchip USB support files and have been modi- fied to compile under PicBasic Pro. Having put my emulator hardware Photo 5—I couldn’t possibly show you everything, so I’ve decided to give you copies of all of my traces. You can problem behind me, I was on my way view them using the USB Tracker 110 display software, UsbShow.

72 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO September 15 – 18, 2003 retool with intelligence Hynes Convention Center Boston, MA

37 industry experts sharing their expertise Save up to $650 in 78 classes and full-day tutorials at the Register by July 15th East Coast’s premier event dedicated to Flexible conference processor-based design packages start at $445 What’s New for Boston 2003: Save up to $450 > NEW Flexible Conference Packages The Embedded Systems Conference Boston now Register by August 19th offers you more flexibility than ever before with new customizable 1 to 4-day conference packages. Choose the 4-Day VIP package to save hundreds of dollars while gaining new skills and techniques.

> More classes dedicated to hardware and software design Designing the Next Generation of Handheld Devices, FPGA Design for Software Engineers, and Mastering Design Patterns are just a sample of challenging courses we have to offer

> Meet with more than 150 leading vendors The Boston exhibit floor is your opportunity to meet with embedded vendors, preview exciting innovations, and catch up with what's going on in the embedded industry. See the industry giants and innovative up-and-comers in person and talk with field application engineers to get answers to WWW.GiURUMELE.Hi2.ROyour toughest design questions.

To register or to view a complete list of courses and events, visit: embedded.com/esc Be sure to use this source code when registering Source Code: MKL

Conference Sponsors data comes with Microchip’s PICDEM you should be able to investigate the par- host expects to be able to talk to the USB development board. ticulars of the USBINIT command. Let’s newly found device at the 0x00 address After working out the initial emulator work through an example. You can fol- using the bidirectional endpoint zero. and compiler bugs, I decided to test run low along using the USB Tracker 110 The default state endpoint and device the USB Tracker 110. I used the result- trace data in Photo 5 and either the origi- addresses (0x00) are verified in the first ing USB trace in conjunction with nal USB specification or USB Complete. GetDescriptor(Device) trace entry. Axelson’s book and the USB specifica- According to both sources, after a The first transaction after the forced tion to determine what was needed from successful initial USB hardware reset reset from the host is a set-up transac- a firmware standpoint to be successful sequence, the host PC will issue a tion aimed at device zero, endpoint zero. with USB. Now, I’ll explain how it went. GetDescriptor request. At power-up, the As you can see in Photo 6, the USB Slow-motion photography is often PIC-based USB device goes into a pow- Tracker 110 and UsbShow trace pro- used to study the minute details of a ered state with its interrupts enabled. gram are able to show and decode the fast-moving event. You can do a simi- When the PIC is able to execute instruc- bit fields inside common USB packets. lar thing electronically using an emu- tions, the USBINIT macro invokes They also display the raw packet data. lator like the MPLAB ICE 2000. So, I the InitUSB code that resides in the You can pick out all sorts of details added a breakpoint to the PicBasic Pro Microchip-supplied USB_CH9.asm mod- from the packet information provided compiler demo USB code to see if I ule. When the host sees that the device by the USB Tracker 110 and UsbShow. could stop the USB process and exam- is powered, it issues a USB reset to the For instance, in the data packet of the ine it up to that point (see Photo 4). powered device. Looking at the USB SETUP transaction, the packet iden- The PicBasic Pro compiler only sup- trace, the Extended SE0 (26.3 ms) is tifier (PID) is actually the least signifi- ports three USB BASIC commands: most likely the USB reset from the host. cant nibble of the PID. The most sig- USBINIT, USBIN, and USBOUT. After starting the USB trace, it took a nificant nibble of every PID is a com- According to Axelson’s book and the few seconds to plug in the PICProto plement of the PID’s least significant USB specifications, three simple USB USB development board’s USB cable and nibble, which, along with a CRC commands won’t cut it. However, I start the MPLAB ICE 2000 emulator. word, helps to ensure data integrity. saw two of those simple little com- The host USB reset then triggers the In the aforementioned example, the mands wiggle a cursor using a rudi- PIC’s USB reset interrupt, which con- token packet is followed by a data mentary PIC circuit and USB. It was figures the PIC’s USB address to 0x00 packet, which contains the set-up time to sip from the Holy Grail. and enables endpoint zero. This collec- request information. Axelson says that I inserted the USB Tracker 110 into tion of zeros is in the default state although the host asks for 64 bytes, it the loop with the analysis computer at because every USB device must have will only read the first 8 bytes because the USB Tracker 110 analyzer tap. The an active endpoint zero at that point. all it really wants is the eighth byte of test computer and PICProto USB devel- In the default state, a USB address has the device descriptor, which contains opment board were plugged into the not been assigned by the host, and the the maximum packet size. She’s right. USB Tracker 110’s device under test sockets. According to the PicBasic Pro Basic compiler description, the USBINIT command initializes the USB device and completes when the USB device is con- figured and enabled. I knew from my reading that the USB device must first enter the powered state and then pro- ceed to the default, addressed, and con- figured states (in that order) before being able to intelligently communicate with the host. That is called enumeration. But how does the PicBasic Pro USBINIT command do itWWW.GiURUMELE.Hi2.RO all? Behold the screen shot in Photo 5, which is the USB Tracker 110’s view of everything USB that transpired between the test PC and the PICProto USB devel- opment board from the time the board was powered up. Wow! Think about what you could do with this informa- tion. With the trace, you could correlate Photo 6—This is a handy feature. Before obtaining a USB Tracker 110, I found myself searching through the the trace data to a corresponding seg- pages of the USB specification and Microchip USB source code looking for the tables and declarations that defined ment of PicBasic Pro source code, and the various bit fields.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 75 rest of the USB enumeration process software will display the USB traces will flow. Looking at the trace, you I’ve provided and the detail contained can see that device, configuration, and within them. However, you won’t be string descriptors are collected from able to take your own USB traces with- the PICProto USB development board’s out a USBTracker 110. The USB firmware as the USB enumeration Tracker web site also has a great picto- sequence progresses. The Windows OS rial overview of what the USB Tracker assimilates all of the data collected 110 and UsbShow can do. Reviewing from the PIC and finally sends a the overview will make it easier to SetConfiguration request, which interpret the USB traces. USB is com- Photo 7—If you prefer an assembled alternative to the ultimately results in placing the devel- plicated, but at least it’s embedded. I PICProto USB, the Microchip PICDEM USB provides opment board in the configured state. the basic functionality of the PICProto USB in addition After configuration, the development Fred Eady has more than 20 years of to the ability to experiment with using USB to control an board can pass data to and receive data LCD and game pad. The PICDEM USB LEDs, which experience as a systems engineer. He can be switched out with a jumper or at the firmware from the host PC (the test computer). has worked with computers and com- level, illuminate to signal each state of enumeration. munication systems large and small, THE SONG REMAINS THE SAME simple and complex. His forte is Axelson’s Carnac-inspired foresight I unplugged the 40-pin MPLAB ICE embedded-systems design and com- is reinforced by an information mes- 2000 device adapter from the PICProto munications. Fred may be reached at sage that UsbShow posts for the SETUP USB development board and plugged it [email protected]. transaction. The UsbShow message into the 40-pin PIC16C765 socket on tells you that the retrieval of less than my PIDCEM USB development board. PROJECT FILES 64 bytes is not an error and that the I clicked on the MPLAB IDE Run icon host would later ask again for the and, lo and behold, the PICProto USB To download the UsbShow files, go to device descriptor information. Looking development board demo code ran on ftp.circuitcellar.com/pub/Circuit_ ahead in the trace shows you that the the PICDEM USB as it should. Cellar/2003/157. entire device descriptor is read in after Although cosmetically modified to the device address is established. compile inside PicBasic Pro, the core RESOURCES Using the ’16C765 and ’16C745 USB USB code and fundamental hardware USB Tracker 110 distributors micros eliminates a great deal of USB design are identical. The PICDEM USB Saelig Company configuration confusion because they’re development board differs from the ME www.saelig.com low-speed devices. Low-speed devices Labs PICProto USB development board are limited in many ways, one of which only in the amount of on-board equip- USB Wholesale is the maximum packet size, which is ment. The former comes assembled with www.usbwholesale.com set at 8 bytes. You can see the 8-byte a USB CD-ROM containing support code limit enforced throughout the USB trace. and documentation, a preprogrammed REFERENCE Moving to the next transaction, the PIC16C765 full of demo code, a 3′ USB [1] J. Axelson, USB Complete: IN transaction pulls the 8 bytes of A-B cable, a blank ’16C745, and a blank Everything You Need to Develop the 64 bytes of requested data from the ’16C765 (see Photo 7). It also includes a Custom USB Peripherals, Lake- PICProto USB development board’s PIC serial port, a game port, a PS/2 key- view Research, Madison, WI, 2001. firmware. The host has just enough board/mouse port, enumeration status information and status to grant the LEDs, and a backlit LCD landing pad. SOURCES PICProto USB development board a USB I wasn’t able to show you every detail USB Tracker 110 address. But before knighting the devel- of the USB traces, and I would need a Ellisys Sarl opment board, the host wisely resets it few more pages to take a complete look www.ellisys.com to make sure it is in the default state at the features offered by the USB before sending WWW.GiURUMELE.Hi2.ROthe SetAddress request. Tracker 110 and UsbShow. So, instead MPLAB ICE 2000, PIC16C745, After the SetAddress request is of leaving you hanging, I’ve included all PIC16C765, PICDEM USB, and acknowledged, the PICProto USB the USB trace data that I took from the PICkit 1 starter kit development board is considered to be PICKit1 Flash starter kit, the PICProto Microchip Technology, Inc. in the addressed state. As you can see USB, and the PICDEM USB. You may www.microchip.com in the trace, the development board download the data from the Circuit PicBasic Pro compiler, PICProto USB was reset and assigned an address (2). Cellar ftp site. The core USB source microEngineering Labs, Inc. Remember that everything in USB is code is on Microchip’s web site. www.microengineeringlabs.com about the host. So, IN means to the If you’re wondering how you’re going host, and OUT is from the host. to read the USB traces, simply down- SP232ACP Transceiver From what you’ve seen thus far, you load your freeware copy of UsbShow Sipex Corp. probably have a good idea of how the (www.usbtracker.com). The UsbShow www.sipex.com

76 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com SAELIG BRINGS YOU SOLUTIONS! Industrial PCs PC Scope Adapters USB-Serial Adapters Ruggedized Industrial ATX PC systems to suit almost Turn your PC into a high- US232 is a 6ft USB-RS232 any budget or PC application. speed scope. Sampling self-powered converter Easy maintenance, economy rates up to 100MS/s for sin- cable which instantly and and reliability. $899 version gle shot signals (and up to reliably solves the problem features AMD Athlon XP1700, 5GS/s for repetitive signals) of laptops with no serial shock-mounted 40GB harddrive. with 12-bit resolution. With Lockable front doors prevent ports, or legacy RS232 FREE software, your PC tampering. Full Burn-in and devices that need to be Test Report with every system. becomes a powerful 2-chan- updated to USB IN ONLY 5 LED system status indicators. nel scope and spectrum MINUTES! Buy in bulk to CE EMC certified. More info at www.amplicon.co.uk analyzer. ADC-212/100 $1090 update your products - $39! Manufacturing Software RS232<>422/485 Isolated USB<>RS485 "After looking at a number of packages K2 9p-9p self-powered RS-422/485 converter USB-485i offers self- both large and small we have found K3 9p-9p isolated RS-422/485 converter TM TRAKIT powered USB to RS485 TRAKIT to be the most cost effective manufacturing K3-232 9p-9p isolated RS232 converter solution for inventory management in the conversion with optical - Inventory Management K232-ISOL 25p -25p RS232 manufacturing environment available for isolation to 1kV. Baud the small to medium size company. It - Bills of Materials K422-ISOL 25p -25p RS422 contains most of the commonly used - Build Schedule K485-ISOL 25p -25p RS485 rates 184bps - 3Mbps. features of the larger programs as well as - Sales Orders KD485-STD DINrail-mount Link-selectable half-duplex maintaining the user ease of the smaller - Instant Builds RS-232/485/20mA isolators - Purchase Ordering mode enables the 485 programs. Some of the more advanced KD485-PROG DINrail-mount features of Trakit are more successfully - Request for Quote transmit-buffer when data RS-232/485/20mA isolators implemented than packages costing - Reminders ready. Three-point isolated many times more. Better and easier to - Reports C-programmable for protocol/MODbus use than P&V" (S.P. Ltd) conversion. Program to convert custom needs. serial communciations. RS485 factory control I2C for PCs Logic Analyzer Easily construct small control systems communicating Make PCs talk I2C easily with this industry-standard At last! This tiny pocketable USB-based and USB- powered device is the answer to your need for an eco- through Intranet/Internet. BIT2000 is the ideal solution card, available in 2 - 6V bus version for low-volt I2C for process control, building nomical logic analyzer that you can take anywhere. systems. Optional WINI2C/PCI software gives you a monitoring, data logging, About the size of a small matchbox, ANT8 can sample alarm systems and other windows-interface to develop eight channels at up to 500 million samples-per-sec. industrial uses. BIT2000 and debug I2C bus systems. ANT8 offers simple or complex can communicate with Monitor software lets you triggering, upgradeable soft- ware. View the captured eight many types of equipment transparently monitor I2C bus through the fast multidrop digital channel traces on your activity . NEW - USB VERSION RS485 based bus and a PC. Save or print screens for standard RS232 serial port. UCA93LV: 400kHz monitoring! reference or labnotes! $199! Crystals & Oscillators Datalogger/Controller USB Bus Analyzer Euroquartz is one Europe’s largest manufacturers and Build a custom PCMCIA or CF USB protocol analyzer displays USB packets sent, supplier of quartz crystals, oscillators, filters and card datalogger or controller decodes descriptors, detects errors in peripherals or frequency-related products. They design & manufacture - quickly! Wizard high-level drivers and measures their performance. a comprehensive range of frequency-related components software completes your Ideal for anyone developing including custom-made filters, high project in hours not weeks. USB peripherals, reliability oscillators for defence Store GPS or CANbus data. applications and radiation tolerant TDS2020F is the low-power embedded soft- oscillators for high-altitude apps. controller of choice for sure ware or drivers. EQ-HM oscillators reduce EMI using LONGEVITY - this one won’t Software is easy Spread Spectrum Technology disappear like so many other to use - learn all to slowly shift center frequency. obsolete boards. Ask us why! about USB. $799! Easy USB in one IC! CANbus Cards USB PC Scope Join all the industry leaders who are using this easy-use CANbusStarter Packs available for almost 200 kS/s 12-bit dual-channel USB scope adapter for USB ic. Single chip USB-232 solution comes with all any board format: PCI, ISA, PCMCIA, PC104, PC. Unique software looks like a “Digital Scope” right Windows/Mac/Linux drivers. UART ASIC-based so no VME, cPCI, etc. with software for most OS’s software development is needed! on your PC screen! Built-in inc. all Windows, Linux, QNIX, etc. No USB knowledge required! Byte- squarewave generator. CAN/Ethernet bridges, industrial wide ic version FT245BM too! by Janz Weighs less than 8oz so computing and automation solutions FT232BM is in the ready-made for all you can take it anywhere. Industry leaders worldwide trust and computers US232 cable (USB-serial) - see top Only $189!! For details: right panel. Instantly update your specify Janz AG’s ISO9000 systems. www.usb-instruments.com legacy serial RS232 products! Janz AG - a leading CANbus supplier. BasicWWW.GiURUMELE.Hi2.RO modules Standalone Dataloggers SM PCB Adapters BASIC Tigers are tiny multitasking Self-contained in 2” x 3” box, these These SM miniboards have two foot- modules for quick project development. battery-powered standalone analog prints on either side, allowing you to Powerful features and low prices make Tigers a number one choice: super-fast and digital loggers store events, use ultra fine pitch SMD components development cycle, high reliability prod- voltages, currents or pressures for with a more useful array of 0.1" ucts, >100,000 instructions/s, up to 38 I/O days to weeks. Download detailed spaced holes. 1-to-1 pinout for circuit lines, A/D, D/A, I2C, SPI, text/graphic LCD time and data via serial port and probing during design and testing. interface. NOW - SmartCard Interface! review results with graphic software Each unique miniboard (pat-pending) iCOM200 ready-made controller with LCD can fit several different devices. and keypad. Touch240 controller - with or upload to an Excel spreadsheet. touchpad and LCD display. More details at - www.abidata.be More at www.omega-research.co.uk

ALSO: SCALABLE LED DISPLAY PANELS, TEMP-HUMIDITY Saelig Co. brings to USA unique, easy-to-use control and MONITORS, THERMOCOUPLE P.C. ADAPTERS, ENVIRONMENT instrumentation products from overseas. Customers inc: MONITORING SYSTEMS, EDUCATIONAL SCIENCE PROJECTS, Saelig Co. Inc. Intel, Philips, NEC, Kodak, Nokia, US Military, Microsoft, GRAPHICS SOFTARE, AutoCAD PROGRAMMING COURSE, USB-PIC Dell, Xerox, Universities, T.I., Harris, Sony, J&J, BOARDS, FLASH PROGRAMMERS - IF YOU DON’T SEE WHAT YOU 585-425-3753 • fax: -3835 Thomson, Sandisk, General Dynamics, H-P/Compaq, etc. NEED MAYBE WE CAN FIND IT FOR YOU? - JUST ASK FOR ALAN! www.saelig.com • [email protected] SILICON UPDATE by Tom Cantrell

Switch Hitter The MC33993 was designed with automotive applications in mind, but that doesn’t mean that intelligent engineers in other fields won’t find it useful. This month, Tom delivers an introduc- tion to the chip’s features in addition to discussing its applicability outside the auto industry.

As a first-hand observer of much of naked city. I’m not talking DIP switches ing about the blue-collar, big-iron the IC revolution, after almost 30 years or little togglers that live happily ever switches that get down and dirty con- I still get a thrill from the march of sili- after in a pristine digital gated communi- necting with the real world. They go way con, something I’m very thankful for. ty behind white picket fences and nicely beyond simple on/off and ones and zeros I’m quite sure I wouldn’t be able to regulated and filtered supplies. I’m talk- by actually doing some heavy lifting in say the same had I ended up selling insurance, for example. Don’t you just love this business? You bet I do! 5 V V SP0 I think of the mass of humanity VPWR PWR 16 mA 2 mA VPWR V around the globe mousing away at VPWR, VDD, 5 V PWR POR VDD their PCs or starting their micro-laden SP0 Bandgap SleepPWR GND cars who have little understanding or SP1 + 4-V Ref – To SPI SP2 16 mA 2 mA respect for the 100 million transistor Comparator CPUs and billion transistor DRAMs SP3 5 V SP4 SP7 Oscillator under the hood. They take for granted, VPWR VPWR SP5 and clock V rightfully, they’re owed more chip for 16 mA 2 mA control PWR SP6 less money, just as it’s always been. SP7 5 V Yet for me, it’s still the little chips + To SPI 4-V Ref – Temperature 5 V 16 mA that are most inspiring. Intel’s 8-bit 2 mA monitor and Comparator 8080 saved me from a life of, if not sell- control 5 V 125 kΩ ing insurance, perhaps working in a big VPWR VPWR SG0 company MIS bureaucracy maintaining 5 V 16 mA 2 mA VPRW COBOL programs or something equally *Wake SG0 grim. A computer where me, myself, Wake control SG1 + and I was the MIS department—cool! 4-V Ref – To SPI SG2 It’s more than just nostalgia, though. Comparator VDD SG3 SPI Interface and control It may seem that someday the entire SG4 125 kΩ world will get integrated on a single SG5 *INT chip, but in fact there will always be a SG6 *INT Control VDD need for simpleWWW.GiURUMELE.Hi2.RO little chips that do sim- SG7 SG8 MUX Interface 40 µA ple little things. What’s the biggest of *CS the simple little things the simple little SG9 VDD SCLK SI SG10 SG13 SO chips need to do? It’s to save the butts VPWR VPWR SG11 of the complicated big chips. Read on, 16 mA 2 mA SG12 VDD and you’ll see what I mean. Analog MUX SG13 + output AMUX + – THE NAKED CITY 4-V Ref – To SPI With apologies to a long ago TV Comparator show, there are eight million switch- Figure 1—MC33993 is the name, and switching is the game. Twenty-two switch inputs are provided, 14 of which es—and the requisite shorts, glitches, are switch-to-ground and eight are programmable as switch-to-ground or switch-to-VPWR. In addition, any switch and transients to go with them—in the input can be routed via the analog multiplexer to the AMUX pin.

78 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com rather harsh environments. transferring a bit in each direction VDD As usual, the automobile pro- VBAT Power supply every SCLK cycle. For the ’993, vides a good setting for a reality- LVI each transaction requires 24 bits. VBAT based switch story. Yes, it’s going, MCC33993 *Enable MCU The outgoing bits issue specific Watchdog going, gone digital in many ways, SP0 VPWR commands, while the returned SP1 VDD Reset but under the hood, it’s still a pret- V bits comprise the 22 bits of V DD ty rough neighborhood. And BAT switch state (open or closed) and though a good example familiar SP7 *Wake two status bits. One, INTFLG, is MOSI to all, the grittier aspects are also SI a mirror image of the INT pin SG0 SCLK SCLK SG1 found in a variety of consumer *CS *CS state for use in polling situations, and industrial applications. SO MISO and the other, THERMFLG, Enter the Motorola MC33993 SP12 *INT *INT denotes the thermal shutdown (see Figure 1). Like its e-field chip I AMUX AN0 state, which I’ll discuss later. SP13 wrote up in Circuit Cellar 155, the GND The chip operates in Normal ’993 is another example of taking a and Sleep modes. It powers up chip defined for automotive apps Figure 2—The MC33993 connects easily to any MCU via a hardware (VPWR) in the former (4 mA), and and running it up the flagpole to see or bit-banged clock serial interface. stays that way until the MCU if there’s broader market interest. issues a Sleep command. After In principle, the chip is quite simple. Murphy is quite at home behind the sleeping (100 µA), the chip wakes up In essence, it’s little more than a shift wheel (if it can, it will go wrong). on a change of switch state (for the register connecting 22 parallel I/O lines As shown in the ’993’s block dia- switches programmed as wake-up to and from a clocked serial port. The gram, the real-world side of the chip sources) or assertion of *CS, *INT, or story of the ’993 is less about what it accomodates up to 22 switch inputs. *WAKE. The *CS and *INT wake-up does than how it does it. Actually, there Eight are programmable as switching to features work only if VDD is applied. are interesting outside-the-box poten- battery voltage, which powers the chip The *WAKE pin works without VDD, so tials, but for now let’s look at the basics. (VPWR) or ground, while the other 14 you can use it to enable the VDD supply And those basics start with the fact are dedicated to switch-to-ground. powering the ’993 and the MCU. that automotive electrical systems There’s a separate digital logic supply There are also a couple of automatic were designed to serve headlights and (VDD ), but its primary role is to establish wake-up schemes relying on timers starter motors, not chips. Though the voltage levels (e.g., 3.3 or 5 V) for the inside the ’993. An interrupt timer nominally 12 V in theory, actual prac- SPI-clocked serial port connection to an periodically wakes up the chip and tice finds even routine operation cov- MCU. In fact, the supply can be turned generates an interrupt (INT); it’s pro- ering a range of perhaps 10 to 16 V. off much of the time if you’re so grammable with a period (eight selec-

Unfortunately, that’s just the begin- inclined. But, because VDD draws only a tions) of 32 ms to 4.096 s. ing. The instantaneous voltage is sub- fraction of a milliamp and its absence No, that’s not a misprint: there is no ject to wild mood swings as transient compromises some of the chip’s opera- option to turn it off, and if you use the loads come and go. And I’m not talk- tion, it may not be worth the bother. Sleep mode, you will get INTs and have ing about turning the radio on and off Hardened against the vagaries of the to repeatedly issue the Sleep command. I or using the cigarette lighter, but big real world, the chip is designed to hitters like an AC compressor or radi- operate across a remarkably wide ator fan. And let’s not even get into VPWR range from 5.5 to 26 V. But, in the problems engendered by shade- fact, the switch inputs themselves can tree mechanics other than to say that tolerate even more abuse, living through extremes from –14 to 40 V (not to mention 25-kV ESD protec- tion). Try feeding something like that to your little MCU if you dare, but WWW.GiURUMELE.Hi2.ROjust keep a fire extinguisher handy.

SPI WITH ME The ’993 relies on the popular SPI- clocked serial interface to connect to your favorite MCU. The bus frequency (SCLK) is up to 6 MHz, and, as I men- tioned earlier, the voltage thresholds Photo 2—Take a look at the MC33993 EV board in are determined by V (see Figure 2). action, including the 24 SCLK pulses that go with each Photo 1—Combining the Sleep mode with automatic DD *CS. The PC parallel port bit-banging scheme is kind switch scanning yields a good compromise between With dedicated input (SI) and output of slow, so each *CS cycle takes a few milliseconds power consumption and switch response. (SO) pins, SPI is a full-duplex scheme instead of the few microseconds the chip requires.

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 79 suppose this is intended to of little more than the chip have the ’993 play a watchdog itself, 22 DIP switches, a role that might be appropriate couple of LEDs (INT and for some applications but WAKE), and a connection for unlikely so for others. a PC parallel port. The kit The other timer handles comes with a cute piece of switch scanning and can be software, SPIGen, which turned off (no scanning). If allows you to easily issue enabled, it will frequently various commands and even scan the switch status (range define multicommand if 1 to 64 ms), and compare it sequences (see Photo 3). against the prior state. If a change is detected, the ’993 HEAVY METAL wakes up (i.e., enters Normal Photo 3—No need to get bogged down in the bit-by-bit, blow-by-blow details. The EV Getting back to the real- kit comes with SPIGen software that makes experimenting with the various commands mode) and generates an *INT. easy. The ability to define your own custom command sequences is especially useful. world (i.e., switch) side of the Otherwise, the chip goes back chip, the ’993 offers interest- to Sleep mode and waits for the next There’s a calibration command to fine- ing features including contact wetting scan-timer wake-up call (see Photo 1). tune the on-chip timebase. After the cal- and an analog mux. Humidity, salt air, Note that the entire scan and com- ibration command is received, the ’993 and so on can cause oxidation to form pare process takes only a couple of waits for a 512-µs pulse on the *CS line. on switch contacts, causing glitches or hundred microseconds, so the combi- The datasheet doesn’t elaborate on the switch failure. Contact wetting refers nation of Sleep mode and scanning feature, but you can adjust the timebase to delivering an extra shot of current to offers the potential for significant (e.g., to achieve a 4-s rather than 4.096-s switch transitions to stop the crud before power savings. Even at the fastest interrupt timeout) by tweaking the it spreads. Here’s how it works. scan rate (1 ms), the duty cycle is only calibration pulse accordingly. The state of each switch input can be one-fifth, so average power consump- Checking out the ’993 is easy and individually programmed to deliver 2 or tion would be cut significantly, and cheap thanks to the $99 evaluation kit 16 mA of current (or go tristate as well). much more so for slower scan rates. (see Photo 2). It’s quite simple, consisting The wetting feature uses a 20-ms timer

TO emBEdded OR NOT TO emBEdded DM&P Group Embedded Small World -- Small Footprint X86 Embedded Modules

Customer-made Thin Client

NEW Power Supply RSIP Server & WWW.GiURUMELE.Hi2.ROfor Embedded Applications Tiny and Mity SoC Modules Fingerprint Reader Design ICOP 386SX Modules into: · Supports small footprint headless DOS and Linux kernels. èPoint of Sales · Provides complimentary software utilities and libraries for program developing. è · DSock Library: Sample Codes for BOOTP/DHCP, FTP, SMTP, HTTP, and TELNET Servers. Information Kiosk · Software Utilities are programmable in C, C++ and Assembly Languages. èMedical Device èAutomation Control ICOP Technology Inc. USA Tel: 1-626-444-6666 email:[email protected] Taiwan Tel: 886-2-8990-1933 email: [email protected] www.icoptech.com Japan Tel: 81-3-3265-1508 email: [email protected] China Tel: 86-755-2661-1770 email: [email protected]

80 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com EmbeddedSolutions. DozensofEmbeddedControllerswithCountlessConfigurationstofit ANY Industry.

Micro Modules Communications Controller Boards Micromint Chips Basic Interpreter 56k down to 2400 Stackable - RTC Basic Interpreter (on board) baud socket modems Backplane - BCC On a Chip Assembly or C Conexant Comp. Basic Interpreter No Dev Tools Req. Tiny: .85" x 2" sq. Caller I.D. Assembly or C X10 PLIX Chips Weather Proof Parallel Line Processor Boards Serial No Dev. Tools Req. Sensing Expansion Boards Parallel Controllers RF Modules - Tiny Relay Boards 8051 Core Data Acquisition 433 MHz 3.5" x 3.5" Low Cost ADA, DAC, I/O, RTC, 900 MHz Custom Configurable DIP or PLCC LCD, Keypad... X10 PLIX Interface ADA, DAC, Opto Floating-Point Math Stand Alone RS232 to RS485 Isolated I/O, RTC, Commercial or or Networked Interface LCD, Keypad... Industrial StartingasLowas StartingasLowas StartingasLowas AsLowas $29–single qty $39–single qty $129–single qty $7–1k qty

Datasheets,OnlineOrderingandaCompleteCatalogofProductsat... www.micromint.com ReduceYourTimetoMarket. Minimize your time from conception to production by utilizing one of Micromint’s market-proven controllers. WhetherWWW.GiURUMELE.Hi2.RO your concerns are digital or analog, inputs or outputs, Micromint has a product to fit your needs. Order quantities of one to thousands. Custom design and configurations are available. With over 500,000 controllers in the marketplace, Micromint has been providing innovative, turn-key solutions to the OEM market for 24 years—from design through production, as well as packaging and shipping the final product. Our broad line of embedded controllers and turn-key solutions can turn your imagination into reality.

Visitourwebsite@www.micromint.comtoseeourcompletelineofOEMSolutions.

115 Timberlachen Circle | Lake Mary, FL 32746 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069 that automatically kicks up the current collar. Just for laughs, if you perform status register, and generate an interrupt. to 16 mA when a switch input changes the calculation, you’ll find that’s more The THERMFLG bit is automatically state (i.e., crosses a 4-V threshold). After than 9 W, which is far more than the cleared (updated on the rising edge of the timer expires, current is cut back to chip’s absolute maximum rating (1.7 W every *CS) and previous current set- the 2-mA “sustain” level (see Photo 4). at 25°C) and small plastic package tings are restored after the temperature However, the timer for each switch can allow. Believe me, the last thing a car cools to a safe level. be individually disabled, in which case maker wants to deal with is electrical The other interesting feature is a 22:1 16 mA will continue to flow. gadgets that spontaneously combust! analog multiplexer that connects any Here’s where the thermal flag To that end, the ’993 includes its own one of the switch inputs to the AMUX (THERMFLG) in the status word comes temperature sensor. If things get too hot output pin. The connection is buffered, into play. Clearly, with up to 22 switch for comfort, the chip will automatically and the output is clamped to the maxi- lines carrying 16 mA at up to 26 V, the throttle back all 16-mA current sources mum level defined by the VDD supply. potential exists to get hot under the to 2 mA, set the THERMFLG bit in the THE MORE THE MERRIER You can expand the ’993’s by using multiple chips. The SPI interface sup- ports two ways of doing so: daisy-chain- ing and individual chip-by-chip access. The former approach lines up multiple ’993s in a string with each chip’s SO out- put connected to the next’s SI input. The first chip’s SI input and the last chip’s SO output are connected to the MCU. A sin- gle chip select line from the MCU drives the *CS pin of all the ’993s. The entire lash-up appears as one big circular shift register of 24 stages per chip. Regarding the software, the length of the basic transaction is extended accordingly (e.g., 48 bits for a two-chip setup). The parallel approach devotes a chip select to each ’993 allowing individual access. The INT pins can be combined or presented seperately to the MCU. The latter makes more sense in this case. If they are combined, the MCU has to interrogate all of the chips to find the interrupting one, so the advantage of individual access is wasted. Another alternative is to just throw more MCU pins at the problem and dedi- cate an interface to each chip. There are different ways to do this depending on what’s important to you. Dedicated SI and SO with a common *CS and SCLK would support synchronous access and control at highest speed (i.e., 24 clocks WWW.GiURUMELE.Hi2.ROno matter how many chips). Dedicated *CS (or SCLK) lines would further sup- port individual access. If you’re using multiple chips, there are a few hazards to watch out for. For example, it’s possible that a switch change-of-state may occur during the issuance of the Sleep command (i.e., while *CS is asserted). In such a situa- tion, the chip will not go into Sleep mode when the command is issued (i.e.,

82 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com *CS deasserted). That means to serve a variety of applications. VBATT you could end up with some None of the limitations (e.g.,

chips sleeping and others LOAD SG0 unable to turn the INT timer off) V remaining awake. It turns out PWR VPWR seem like showstoppers, but who that you have to issue a 16 mA 2 mA needs the extra headscratching? Ω dummy command to wake 1.5 k SG0 AMUX The virtue of the strategy is the sleeping chips, and then that the auto biz is the driver 100 kΩ + issue another to read the actu- 4-V Ref. – To SPI for technology in the deeply al switch states because Comparator embedded space, much as the there’s a delay (10 to 20 ms) PC market prods the big silicon SP0 required after wake-up for VPWR VPWR to the bleeding internal voltages to stabilize. edge. Auto apps push the limits 16 mA 2 mA when it comes to dealing with LIGHT VS. SWITCH SP0 the harsher realities of life, In summary, the ‘993 can 2 mA offering extended temperature 16 mA + To SPI deliver 16 or 2 mA (or no cur- 4-V Ref. – operation (the ’993 is specified rent, i.e., tristate) as well as the Comparator for –40° to 125°C) and a robust option of directly measuring electrical interface. the voltage level (via AMUX) The other good news is that SG13 on a certain pin. This flexibility VPWR VPWR the volume of chips shipped to enables some alternate applica- 16 mA 2 mA the automotive market helps tions that supplement the chips SG13 drive the price. The ’993 is quot- basic role as a switch master. ed at $1.63, and that’s at intro-

For example, 16 mA is more + To SPI duction and for 1000 pieces, 4-V Ref. – than enough to drive a typical Comparator according to Motorola’s web site. LED or power MOSFET (see As time goes on and volume Figure 3). It’s a simple matter of Figure 3—In addition to normal switch duties, clever designers can trick the ramps up, the price will surely issuing various commands (e.g., MC33993 into handling other tasks, such as driving a power MOSFET or LED. fall. On the other hand, I’d be a reconfigure switch_to_ground little concerned about shortages and switch_to_battery settings or duties. You can get even more power by through the peaks and valleys of the enable/disable tristate) to control the paralleling channels (e.g., 32 mA from automotive biz. Motorola will have to be load. Using an external pull-down resis- two channels). Just remember to keep careful to support the little guy when tor, you can check for an open load by the overall power dissipation within the Big Three are clamoring for parts. tristating the pin. If the load is connect- limits to avoid thermal shutdown. The ’993 serves to remind us that ed, the switch input will pull up to Another idea is to use the ’993 to sup- there’s more to the story than cram- VPWR; however, if it’s open, the resis- ply power and bias voltage to a sensor. ming everything on a single chip. tor will pull it down to ground. There’s even a way to hack an ADC for Remember, the bigger the chip, the Indeed, 16 mA is enough to drive all a resistive sensor using two lines as harder it will fall victim to real-world manner of add-ons, such as a logic chip current sources and an additional fixed glitches and gotchas. A little protection, or even an LCD. You might have an resistor to establish a reference. This and a little chip, can go a long way. I application that could take advantage of relies on the fact that the channel-to- the ’993 as a virtual power strip that’s channel current matching is fairly accu- Tom Cantrell has been working on able to control a myriad of loads in addi- rate (2% typical, 4% worst case). More chip, board, and systems design and tion to its normal switch-monitoring precise factory calibration measures the marketing for several years. You may actual difference between two particu- reach him by e-mail at lar channels and stores a calibration [email protected]. WWW.GiURUMELE.Hi2.ROfactor in MCU EEPROM. MIXED SIGNALS RESOURCE Motorola’s strategy of offering special- Motorola, Inc., Multiple Switch ized automotive chips to the mainstream Detection Interface, MC33993/D, market has promise, but I must admit to rev. 1, 2002. some mixed feelings. The downside is that the ’993 forces you to live with the decisions another designer made to fur- SOURCE ther their and not necessarily your appli- MC33993 Detection interface Photo 4—The contact wetting option provides 20-ms cation’s cause. The chip is less versatile Motorola, Inc. of high current to counter oxidation of switch contacts. than it would be if designed from scratch www.motorola.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 83 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 submis- sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail [email protected]. For more information call Sean Donnelly at (860) 872-3064.

Suppliers Directory now available online. Check out our web site www.circuitcellar.com to see who has what and how to get it!

phyCORE® New Generation Single Board Computer

I Insert-ready Single Board Computer modules in sub-miniature dimensions (as small as 47x55 mm) populated by:

8-bit: ADuC812, AT89C51CC01, DS80C390, P87C591, P89C51Rx2, P89C66x, P89C51MX 16-bit: C167CR, C167CS, XC161CJ, XC167CI, PXAC3, PXAG49, ST10/168, ST10/269 32-bit: AT91M55800A (ARM7TDMI core), Elan SC520, MPC555, MPC565

I applicable controller signals extend to standard pin header (2.54 mm) or high-densityWWW.GiURUMELE.Hi2.RO Molex (0.625 mm) connectors, enabling SBC to be plugged like a “big chip” into OEM targets

I Low EMI design achieved via GND circuitry, multi-layer PCB, by- pass capacitor grid and short signal traces achieved via small footprint and use of 0402 SMD passive components

I 32 KB to 64 MB external SRAM and /lash (controller-dependent)

I CAN, Ethernet, RS-232 and RS-485 interfaces; ADC, DAC (controller-dependent); freely-available /CS and I/O lines

I available in Rapid Development Kit including Development Board, AC adapter, serial cable and SPECTRUM CD with eval software tools, electronic documentation and demos

I Stick It In!: insert-ready PHYTEC SBC modules accompany you from evaluation through protyping to end production... accelerating your design cycle and reducing your time-to-market

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

84 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com PC KEYBOARD EMULATION Interface Keypads, Switches, or RS-232 to your PC Keyboard Input MODEL KE24 ONLY $9995 • Up to 12 x 12 matrix • Programmable • RS-232 Port • Macro Capability

The KE24 is the ultimate in flexibility. Inputs or serial data can emulate any of the 101 keys from a standard keyboard.

MODEL KE18 ONLY $4495

• Up to 9 x 9 matrix • 2.5" x 3.0" Size • PC Keyboard Port • PCXT, AT Compatible

The KE18 combines a multitude of features with small size at an economical price. Custom units available.

HAGSTROM Toll ree: 888-690-9080 Phone: 607-533-4441 $ax: 607-533-4443 ELECTRONICS www.hagstromelectronics.com 11 $iddlers Green Lansing, NY 14882 NEWRS232 toto TCP/IP

TCP/comtmTM v20, RS232 to TCP/IP software Plus TCP/IP to RS232

tm WinWedge,R RS232 or TCP/IP data direct into any Windows app - Excel, Access, etc

Free 30 day evals at wwwtaltechcom

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 85 lashlite 186

l186 processor @ 33 MHz lDOS w/ Flash File system l44 Digital I/O lines w/ CPLD $69 QTY 1 lConsole / Debug Serial Port l7-34V DC or 5V DC power l2 Serial Ports lAccepts 8MB DiskOnChip l2 16-bit Timers l512K DRAM & 512K Flash lWatchdog Timer lExpansion options with Peripheral Boards Development kit includes: lFlashlite 186 controller $99 lBorland C/C++ ver 4.52 Development lFREE Email Tech Support System lSerial Driver library lAC Adapter and cable

Call 530-297-6073 Email [email protected] On the web at www.jkmicro.com

JKmicrosystems

Controller, Operator Interface and I/O for Any Instrument Use the QVGA ControllerTM for machine control, embedded systems, scientific instruments, and OEM applications - wherever you need an I/O-rich computer and a smart user interface! ALL THE I/O YOU NEED • 48 Analog & Digital I/O Lines • Expansion I/O modules WWW.GiURUMELE.Hi2.RO

POWERFUL CONTROLLER PLENTY OF MEMORY • Programmable in C and Forth • Up to 768K Flash, 640K RAM • Multitasking RTOS • 64Mbyte Mass Memory

READY-MADE GRAPHICAL USER INTERFACE • Bright, High Contrast 1/4 VGA (320x240 pixel) Electroluminescent (EL) or Monochrome Display • High-resolution touchscreen • Precoded menu managing software Mosaic Industries Inc tel: 510-790-1255 fax: 510-790-0925 wwwmosaic-industriescom

86 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 87 USB to Serial • 1,2,4, and 8-port models • RS-232, RS-422/485, and RS-232/422/485 versions • Supports data rates up to 921K bps Ethernet Serial Servers • 1,2,4, and 8-port models • Ethernet 10/100Base-T (autosense) • RS-232, RS-422/485, and RS-232/422/485 versions • Easy-to-use software included

www.sealevel.com [email protected] 864.843.4343

WWW.GiURUMELE.Hi2.RO

88 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 89 WWW.GiURUMELE.Hi2.RO

90 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 91 WWW.GiURUMELE.Hi2.RO

92 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com Email: [email protected]

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 157 August 2003 93 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 Abacom Technologies 90 Embedded Micro Software 81 Micromint 88 RobotBooks.com 85 ActiveWire, Inc. 74 ESC-Boston 27 MJS Consulting 77 Saelig Company 19 AeroComm, Inc. 89 eProtos 86 Mosaic Industries, Inc. 3 Scott Edwards Electronics Inc. 42 All Electronics Corp. 17 ExpressPCB 63 Motorola 88 Sealevel Systems 90 Amazon Electronics 85 FDI-Future Designs, Inc. 58 MVS 86 Senix Corp. 93 AP Circuits 92 Front Panel Express 86 Mylydia Inc. 95 Sierra Proto Express 73 Arcom 92 Futurlec C2 NetBurner 84 Signum Systems 7 Atmel 85 Hagstrom Electronics 88 OKW Electronics, Inc. 86 Softfield Technology Inc. 85 Avocet Systems, Inc. 15 HI-TECH Software, LLC 10 On Time 93 Softools 91 Bagotronix, Inc. 80 ICOP Technology Inc. 92 Ontrak Control Systems 84 Square 1 Electronics 90 Basic Micro 89 IMAGEcraft 66 PCB123 11 Systronix 91 Bellin Dynamic Systems, Inc. 89,93 Intec Automation, Inc 10 PCBexpress 85 TAL Technologies 30 CadSoft Computer, Inc. 85 Intrepid Control Systems 87 PCB Fab Express 88 TLData Corp. 87 Carl’s Electronics 91 Intronics, Inc. C4 Parallax, Inc. C3 Tech Tools 27 CCS-Custom Computer Services 65 Jameco 84 Phytec America LLC 89 Techniprise 92 Conitec 64, 86 JK microsystems, Inc. 87 Phyton, Inc. 32,33 Technologic Systems 35 Connecticut microComputer, Inc. 84 JPA Consulting 93 Picofab Inc. 85 Technological Arts 84 Cyberpak Co. 27 JR Kerr Automation & Engineering 86 Pioneer Hill Software 89 Tern Inc. 1 Cypress MicroSystems 43 K-Team SA 86 Prairie Digital, Inc. 91 Triangle Research Int’l, Inc. 90 CWAV 43 LabJack Corp. 93 Pulsar, Inc. 69 Trilogy Design 91 DataRescue 43 Lakeview Research 91 Q-Kits 89 Vesta Technology, Inc. 90 Delcom Engineering 39 Lemos International 88 R2 Controls 93 Weeder Technologies 84 Deys Electronics, Inc 2 Link Instruments 57 R4 Systems Inc. 93 Xeltek 86 Digital Products 16 Linx Technologies 49 Rabbit Semiconductor 87 Z-World 34 Earth Computer Technologies 82 MaxStream 66 Remote Processing 88 Zanthic Technologies Inc. 47 Easy-Radio USA 90 MCC (Micro Computer Control) 5,25 Renesas Technology Corp. 55 Zilog, Inc 87 EE Tools (Electronic Engineering Tools) 69 Microchip 23 Renesas Contest 35 EMAC, Inc. 92 microEngineering Labs, Inc. 90 RLC Enterprises, Inc.

Preview of September Issue 158 Theme: Internet & Connectivity ATTENTION ADVERTISERS October Issue 159 Design a Wide-Range RS-232 Concentrator Box Deadlines Space Close: Aug 11 RS-485 Network for Embedded Systems Material Due Date: Aug 19

Microprocessor Glue Logic with Verilog HDL Theme: WWW.GiURUMELE.Hi2.ROData Acquisition LCD-Based Color Clock: Tell Time Anytime BONUS DISTRIBUTION

I Applied PCs: Speed Racer: Stand-Alone, Track-Timing Pinewood Derby Computer Sensors Expo Call Sean Donnelly to I From the Bench: Next-Generation Text to Speech: Winbond Makes Strides with the reserve your space! WTS701 860.872.3064 I Silicon Update: ESCape to SF e-mail: [email protected]

94 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com For Unparalleled Quality, Technology, Delivery and Price Insist on 2 to 24 layer PCBs from Sierra Proto Express

We offer the highest quality, the broadest range of technology (2 – 24 layers), the fastest, most reliable turns (99% on-time delivery) and a competitive price. And we prove it every day, with every PCB we ship.

With every multilayer order you receive "Evidence of Quality" which is a set of 5 reports. Microsection Analysis, such as the one featured here, is one of those reports, which provides a proof that your board meets or exceeds your specifications.

Order from us, benchmark our quality, technology, delivery and service with whoever you are currently doing business with, send us that report and receive our special polo shirt commemorating our 17th year of success. Mention promotion code: PPDB00043. Microsection i t y l e 14 Layer Board l a d a e u r q For WWW.GiURUMELE.Hi2.ROproven quality that never costs extra, put Sierra Proto Express on your team today.

M I 2 Call our expert Technical Advisors at • L 0 8 -P 0 0 - 9 • 800.763.7503 0 55 O - 110 IS m 7 co 63 s. or visit us at www.protoexpress.com -7 es 503 pr www.protoex PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director Contest Zest

Contest closing is a hectic time around Circuit Cellar. Not so much because it’s crazier than any other time, but because contests have become my personal fiefdom and a lot happens at the last minute. My official title may be Editorial Director, but I have really come to enjoy being the Contest Administrator, too. I’ve said this before, and I’ll say it again: contests are a big deal at Circuit Cellar because we do them right, and we do them for mutual benefit. What’s that mean? Well, one of the reasons you read Circuit Cellar is because we publish real-world embedded applications. When we run a design contest, we aren’t doing it as some advertising scheme, we’re doing it to build a fire under the design community. Entrants get an opportunity to walk away with some big cash (there’s $30K in prize money in the Motorola Flash Innovation 2003 Design Contest), and we get to publish and post some really great projects. The best part of personally doing the contest job has been communicating with entrants and realizing that contest participation is mutual- ly beneficial. My incentive is that it is a good way to find authors. Surprisingly, however, by talking to entrants, I am finding out that having Circuit Cellar publish their project entries has had major benefits for their careers. Dozens of past entrants and winners have written to me describing how much they enjoy the increased respect at work and in the professional community. More than a few have said they can attribute a bonus, job promotion, or outright career change to a Circuit Cellar contest. The most recent example of this is Robert Lacoste. If you’ve been reading Circuit Cellar for a while, you’ll recognize his name from many past contests. If I remember correctly, he’s won prizes in seven different contests in the last four and half years. A couple weeks ago, Robert wrote me that he was leaving his job as Director of a large company and starting his own design business (www.alciom.com). His world-wide design reputation, frequently demonstrated in the pages of Circuit Cellar, along with a network of semiconductor manufacturer contacts (all the contest sponsors) has provided the perfect incentive to capitalize on everything and go it alone. Given his past performance, I know Robert will do well. As I write this, the Motorola contest entries are arriving. I know there are a number of repeat entrants like Robert who love the challenge, but it’s amazing what the new guys think up for projects. It’s a good thing part of the judging criteria is originality. Here are some of the entries in the in-basket so far: a neat touch-screen controller for LCDs; an acoustic wave soil moisture detection system; a magic-lamp lighting effects controller, a wireless mousetrap-monitoring system; a microwave radar-guided automobile cruise control system; a blood pressure monitor; and a number of other equally interesting designs. I especially appreciate entries that teach me something new. Has anyone besides me never really thought about acoustical cellular automa- ta parallel processing? Just so you aren’t scratching your head for the two to three months it takes to post contest projects, the closest I can describe this concept is to think of the game of Life that we all played on early computers. Now, substitute processors with four eight-tone sound transducers for the individual cells in a large array. The overall sound effect, whether seemingly chaotic or orderly, is governed by the rules used to generate new cell states in the game of Life. I plan to go back and ask the cellular automata entrant to send me a recording. This I have to hear. Fortunately, the evolution in video technology has helped in understanding some of the other projects. More than a few entrants have included video clips this time around. For example, watching as the Follow-Me Greeter Grandfather Clock turns and follows the direction of the contestantWWW.GiURUMELE.Hi2.RO as he walks through the living room and greets him both coming and going definitely explains the concept better than words. Of course, there’s also the video showing a PC ventilation-failure detector where the contestant adds a little excitement by using a blowtorch to simulate an overheated enclosure. Pyrotechnics aside, the expanding concept of contest entry ingredients these days undoubtedly helps in understanding the project and adds zest to dull schematics and software listings. Of course, our contests have always been about adding a little zest to the whole notion of embedded design.

[email protected]

96 Issue 157 August 2003 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO