WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO TASK MANAGER

FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Something for Everyone Steve Ciarcia Jeannette Ciarcia MANAGING EDITOR MEDIA CONSULTANT Jennifer Huber Dan Rodrigues ur lineup this month focuses on Internet & Connectivity matters. With TECHNICAL EDITOR CUSTOMER SERVICE O C.J. Abate Debbie Lavoie varied topics and approaches to web-enabling, there’s something for every- one in this issue. Additionally, we have a few engaging articles about proj- WEST COAST EDITOR CONTROLLER Tom Cantrell Jeff Yanco ects that were entered in three recent design contests. Jeremy Baugher and Stephen Fenwick give us the full story on Voyeur, CONTRIBUTING EDITORS ART DIRECTOR Jeff Bachiochi KC Prescott which won Honorable Mention in the 2004 Flash Nets Cash Design Ingo Cyliax Contest (p. 10). Voyeur is an eZ80Acclaim!-based system for displaying Fred Eady GRAPHIC DESIGNER Mary Turek Internet content. Using a 5″ × 7″ frame and a Noritake 2 × 20 vacuum flu- George Martin Ed Nisley STAFF ENGINEER orescent display, Jeremy and Stephen created an aesthetic platform for John Gorsky viewing text from web sites. You might hang the system by your kitchen NEW PRODUCTS EDITOR John Gorsky clock to get the latest traffic report on your way out the door, or in your home PROJECT EDITORS office to see stock market and weather reports. You’ll want to read about Steve Bedford how Jeremy and Stephen converted web data for the alphanumeric display. Ken Davidson Lindsay Meek put his creativity to good use designing the Portable Web David Tweed Server to enter in the Renesas M16C Design Contest 2005 (p. 51). Lindsay’s system for hosting web sites cuts down on the money and com- ADVERTISING plexity usually involved in hosting a web site. Starting with a Renesas 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise M32C/84 , Lindsay was able to build an effective, low-cost PUBLISHER system using a dynamic domain name system (DNS) service and a Sean Donnelly Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] CompactFlash card to store the data to be presented on the web site. Ingo Cyliax is back this month with a truly interesting article titled ADVERTISING REPRESENTATIVE Shannon Barraclough “Internet-Connected Sonic Anemometer” (p. 56). Ingo’s system is designed Direct: 860.872.3064, E-mail: [email protected] with a Rabbit RCM3000 development board and a Ubicom microcontroller. ADVERTISING COORDINATOR He walks you through the process of measuring wind speed. As Ingo Valerie Luster explains, a sonic anemometer also can be used to measure the actual E-mail: [email protected] speed of sound in air. This in-depth article covers all the details. I also wanted to highlight another fantastic project we’re featuring this Cover photography by Chris Rakoczy—Rakoczy Photography month. I’m continually amazed by the ingenuity of entrants to our design www.rakoczyphoto.com contests. As you’ll see when you read about the Voyeur and Portable Web PRINTED IN THE UNITED STATES Server projects, the sky’s the limit when it comes to choosing an application. CONTACTS Richard Wotiz rounds out the contest showcase in this issue with an article SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] about his Electronic Scarecrow, which won First Honor in the 2005 Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 Freescale Wireless Design Challenge (p. 18). Whereas some entrants are Address Changes/Problems: E-mail: [email protected] inspired to develop something that’s universally helpful, others use the GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] opportunity to create something specific to their needs. Richard was among Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] the latter. Driven by a desire to rid his yard of foraging deer, he devised a New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION technologically advanced way to deter them. His problem called for a unique 860.875.2199, E-mail: [email protected] AUTHORS solution because deer acclimate quickly. You can spend thousands of dol- Authors’ e-mail addresses (when available) are included at the end of each article. lars on a new fence, but the deer will eventually figure out they can jump over it. So, Richard designed a unique deterrent—one engineered so that WWW.GiURUMELE.Hi2.ROCIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar the deer couldn’t easily get used to it. When the system detects animals in Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico $31.95, all other countries $49.95.Two-year (24 issues) sub- the yard, it sets off a variety of sounds and turns on water sprinklers. The scription rate USA and possessions $39.95, Canada/Mexico $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. Direct subscription orders Electronic Scarecrow is built around Freescale MC13192 SARD boards. and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call I hope these projects give you some ideas for your own applications. 800.269.6301. Good luck! Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or [email protected] 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. Cover: HNC700PT Remote-Motion CCD Network Camera product photograph Entire contents copyright © 2004 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. courtesy of Hawking Technologies, Inc. (www.hawkingtech.com). Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO January 2006: Internet & Connectivity FEATURES

10 Internet-Connected Display System 43 Watchdog Supervisory System Jeremy Baugher & Stephen Fenwick David Gamble & Andrew Smallridge Zilog 2004 Flash Nets Cash Design Contest Winner 51 Portable Web Server 18 Electronic Scarecrow Lindsay Meek Richard Wotiz Renesas M16C Design Contest 2005 Entry Freescale Wireless Design Challenge Winner 28 Low-Cost EKG Pulsometer 56 Internet-Connected Sonic Anemometer Serhiy Matviyenko Ingo Cyliax

35 Third-Generation Rabbit 62 Advanced System for Vehicle Back Up A Look at the Rabbit 4000 Rangefinder and Video Display System Aids Drivers Monte Dalrymple Victor Lick

Display for Internet Content (p. 10) PSoC-Based EKG M32C/84-Based Web Three-Point Sonic Pulsometer (p. 28) Server (p. 51) Anemometer (p. 56)

COLUMNS

70 SILICON UPDATE Hot Enough for You? Tom Cantrell 76 FROM THE BENCH Regulator Review Jeff Bachiochi 80 APPLIED PCs ARM Applications with MicroBolt Fred Eady Choose Your Regulator (p. 76) Introducing MicroBolt (p. 80)

DEPARTMENTSWWW.GiURUMELE.Hi2.RO

4 TASK MANAGER 94 INDEX OF ADVERTISERS Something for Everyone February Preview Jennifer Huber 96 PRIORITY INTERRUPT 8 NEW PRODUCT NEWS The Personal Touch edited by John Gorsky Steve Ciarcia 93 CROSSWORD

6 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO NEW PRODUCT NEWS Edited by John Gorsky LONG-DISTANCE CONNECTOR FOR USB DEVICES The USB standard calls for a maximum range of 5 m, but you can stretch this useful pro- tocol to over 100 m with standard UTP cabling or as much as 500 m with fiber cable. This is made possible with the new Ulinx USB extender. Ulinx USB extenders are composed of two separate units, the local extender and the remote extender. You supply up to 100 m of Cat 5 cable or 500 m of fiber- optic cable to connect the modules. Copper media models for USB Type 1.1 with ranges of 50 and 100 m are available. A 50-m version for USB Type 2.0 is also available. If fiber optic is your media of choice, there are 10- and 500-m versions available. Pricing for the Ulinx models starts at $109.95.

B&B Electronics www.bb-elec.com

LINEAR ACTUATORS ENABLE NEW BREED OF DEVICES The Firgelli miniature linear actuators will drive a new genera- tion of compact robots, motion-enabled medical devices, and con- sumer products. Smaller than a cigarette, these cylindrical actua- tors provide efficient piston-like linear motion. They are designed to save product designers the difficulties of engineering a linear stage from large and awkward motors, servos, gears, and rods. The family of Firgelli actuators delivers between 1 and 10 lbs. of linear push/pull force from a 3- or 5-VDC input. The actuators offer customizable stroke lengths from 1″ to 3″ at speeds up to 1″ per second. Other features include internal end-of-stroke limit switches, configurable force sensing and force overload shutoff, and optional closed-loop position control for simplified system design. Firgelli actuators are priced at less than $3 in volume. Firgelli also customizes its standard actuators (size, speed, force, or stroke length) to meet OEM customer needs. NEW PROTOTYPING BOARD The SchmartBoardEZ uses a new patent-pend- Firgelli Technologies ing technology to make hand-soldering surface- www.firgelli.com mount components simple. It’s simple enough for anyone to easily solder 0.4-mm and BGA devices. There are two reasons that it has been difficult in the past to hand-solder surface-mount compo- nents. First, it’s hard to correctly place the chips on the pads and keep them aligned. Secondly, it’s difficult to hand-solder such tiny areas. What makes SchmartBoardEZ so revolutionary is that the solder mask is higher than the solder pads. This enables you to easily place a chip on the pads because the pads are in grooves. The chip’s legs fit inWWW.GiURUMELE.Hi2.RO the grooves so the chip stays in place during the soldering process. To make the process even simpler, all the sol- der necessary is already on the board. All you need to do is melt the solder and push it toward the leg to be soldered. The suggested retail price for the SchmartBoardEZ is $9.99 per piece or $80 for 10 pieces.

SchmartBOARD www.schmartboard.com

8 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com NEW PRODUCT NEWS USE YOUR PC AS A NETWORK ANALYZER The new RF Vector Network Analyzer (VNA) gives designers, production engineers, and educators affordable access to many capabilities of conventional bench-top network analyzers. The VNA covers 200 kHz to 120 MHz. It’s used to test low-power amplifiers, determine characteristics of coax cables, measure and adjust filters, check antenna impedance versus frequency, measure antenna SWR, and even measure the length of transmission lines using the time domain reflectometer (TDR) fea- ture. The VNA measures the forward and reverse gain and phase response of a cir- cuit. It also measures I/O reflection (complex impedance), provides S parame- ters, and measures one- (input and ground) and two-port networks (input with ground and output with ground). The VNA also functions as a general-purpose signal generator. To use the VNA, load the software on a Windows-based PC and connect to a USB 1.1- compatible port. A Linux version is currently under development. The VNA costs $655.

TEN-TEC www.tentec.com

TAMPER-RESISTANT DUAL 8051 MULTI-CONTROLLER The SL80C051 is a tamper-resistant, dual MCS8051 instruction-compatible multi-controller that can directly interface with Freescale’s new MR2A16A 4- Mb MRAMs. Dubbed the SL80C051-2001 for the tamper-resistant version and SL80C051-2002 for the lower-cost non-tamper-resistant version, the Dual8051 multi-controllers can substantially reduce component count, minimize PCB board space, and improve overall processing performance. They do all of this while warding off attacks from software and data pirates in embedded applica- tions that require secure data collection and storage. Both devices are based on a parallel pipeline architecture. The architecture is capable of instruction execution speeds of up to 25 MIPS when used with one or more 20-ns Freescale MR2A16A MRAMs or up to 11 MIPs when used with one or more SST 32HF202 and SRAM combination memories or tradi- tional NVRAMs. Sharing a common program counter output register and 16-bit external pro- gram/data bus, both of the on-board MCS8051 instruction-set-compatible CPUs are completely autonomous. They can operate independently from one another or respond to a dedicated internal interrupt line for parallel processing and con- troller applications. Because each CPU shares a common external program/data memory of up to 2 MB using their own extended addressing windows, they can process and pass large amounts of data between each other without actually having to move the data. This saves an enormous amount of processingWWW.GiURUMELE.Hi2.RO cycles. The result is a higher multiprocessing throughput capability not found on any other 8051-type microcontroller. The SL80C051-2001 costs $60. The SL80C051-2002 costs $45. Each device is shipped with a unique security key programmed in.

Silicon Laude www.siliconlaude.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 9 FEATURE ARTICLE by Jeremy Baugher & Stephen Fenwick Internet-Connected

CONTEST WINNER Display System Jeremy and Stephen use their Voyeur system to display textual content from the Internet.The compact system, which is extremely easy to mount on a wall, features an eZ80F91 micro- controller and a Noritake 2 × 20 CU20029ECPB display.

Everyone agrees that computers are glance at their stocks’ latest turn in the becoming smaller, cheaper, less power- market. We saw people rolling over in hungry, and cuter than ever. But bed to view the day’s weather and traf- regardless of the type of CPU you buy, fic updates (and then rolling back over they all have one thing in common: a and going to sleep, of course). big, bulky monitor. When you limit Our vision was simple. We saw an yourself to only two display options Internet-connected display box designed (LCD monitor or a traditional CRT to communicate textual information in monitor), using a computer to surf the a casual, practical, and amusing way. ’Net becomes all too predictable. The eZ80Acclaim! microcontroller we If you have an Electronic Edition sub- obtained for the Zilog 2004 Flash Nets scription to Circuit Cellar, we can wager Cash Design Contest provided just the a hefty bet on three things about you right vehicle for the implementation of right now: First, your face is probably 2′ our idea. from a screen of some sort. Second, We call our device the “Voyeur” you’re sitting down. Third, you’re the because looking at it is like watching Photo 1—We mounted the finished Voyeur unit on a only one looking at the monitor in front other people surfing the ’Net from bedroom wall. of you. Sad to say, this is how nearly your living room. Photo 1 shows the everyone spends his or her time surfing finished unit mounted in a 5″ × 7″ view 10 of the most recent searches users the Internet. shadow box frame. have performed on the MetaCrawler Several months ago, we envisioned a search engine every time the page is device that would change this. With the SYSTEM OVERVIEW reloaded. This web site proved to be so right device, we thought we could open Our idea was sparked by a web site fascinating that we wanted to be able up new avenues to take people away (www.metaspy.com) that enables you to to view it all the time, whether the from their monitors and computer was on or not. free them from their desk (Try it out. It’s addictive!) chairs. In this vision, we To pull pages off the saw people in groupsWWW.GiURUMELE.Hi2.RO’Net and display them standing around a shadow- inside a shadow box box frame, fascinated as frame, we needed four the rest of the world’s things: an Internet con- Internet searches scrolled nection, a small form-fac- by: “ultrasonic liposuc- tor board with a micro- tion,” “president bush controller and Ethernet resume,” “symptoms of interface, an attractive, depression,” and easy-to-read alphanumeric “minesweeper.” We saw display to show the con- people walking by another Photo 2—Take a look inside. The Noritake CU20029ECPB VFD connects to the motherboard tent, and software to frame in their kitchen to via a 14-pin ribbon cable. The eZ80F91 Ethernet mini module plugs into the motherboard. bring it all together.

10 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com The eZ80Acclaim! microcontroller For the Voyeur to be easily cus- http://metaspy.dooroneprojects.net. was ideal for this project because of its tomizable, we chose to take the pars- The downside is that in order for the on-chip Ethernet MAC layer, multiple ing smarts out of the eZ80. We Voyeur to operate, you need access to general-purpose I/Os, and ease of use. designed a simple command language a web server. The upside is that it The on-chip EMAC allows the micro- that the Voyeur can easily interpret. makes the Voyeur flexible. Most ISPs controller to interface to 100BaseT con- We also designed a separate server (on include a small amount of web server nections with only minimal support the Internet somewhere) that’s respon- space for every subscriber. You could hardware. Conveniently, Zilog sells a sible for converting the web page to use that space to host your own 2″ × 2″ board called the eZ80F91 mini the Voyeur commands. An example of Voyeur bridge scripts. Ethernet module. The module contains these “bridge” scripts (the one used for The Voyeur has three modes of oper- the eZ80F91 microcontroller, along with the MetaSpy web site) is posted on the ation: Configuration, Display, and all the necessary supporting bypass Circuit Cellar FTP site. You can view Setup. A flowchart detailing these modes capacitors, crystals, and PHY interface to the output from this bridge script at is shown in Figure 1. At power-up, the run the microcontroller and communi- cate over a 100BaseT Ethernet network. All of the processor I/O lines are brought out the bottom of the board for interfac- CPU Reset ing to other devices. Ini’t peripherals The eZ80Acclaim! development kit contains a motherboard that accepts “Voyeur” the eZ80F91 mini Ethernet module and Copy TCP/IP setup from brings out serial, debug, power, and flash memory several I/O lines. The kit also comes Initialize TCP/IP “Check Internet with a fully integrated development stack Connection” environment, a serial debug interface Ethernet N for source-level debugging, Zilog’s real- connection time RZK , and present?

Zilog’s ZTP TCP/IP stack). Y The only component left for us to Setup jumper Y choose was a display that would be easy installed N to view, attractive, and simple to inter- “Hold button Configuration mode to restore defaults” face to the eZ80Acclaim!. Although “Loading” varieties of backlit LCDs abound, we Load config data Delay 3 s from flash felt that the reflective nature of an memory Setup mode LCD would limit the viewing angle Button Perform HTTP pressed? Y too much. Nor did it look as good as a GET using URL Delay 10 s vacuum fluorescent display (VFD). We in config data N “Current IP addr: chose a Noritake 2 × 20 VFD for its Parse commads xxxx” received over “Check Internet Store defaults to LCD-compatible interface, large char- socket Connection” flash memory: Wait for TCP IP: 192.168.1.77 connection on acter size, and availability. Photo 2 NetMask: 255.255.255.0 telnet port shows the motherboard, eZ80F91 mini Gateway: 192.168.1.1 "loadwebpage" N module, and VFD. command Parse commands “Defaults Set, received? received over Rebooting...” Y socket VOYEUR IN ACTION Store received Display mode Setup complete URL to RAM Converting a web page into a format rebooting suitable for a small alphanumeric dis- Perform HTTP GET using URL in Delay 5 s play was no simpleWWW.GiURUMELE.Hi2.RO task. Parsing out RAM text from a sea of HTML tags wasn’t Reset CPU Parse commands trivial when written in C language. received over socket Furthermore, after the text-parsing algorithm was written, it would have to be rewritten and flashed again for "loadwebpage" N command the Voyeur to display content from a received? different web page. We wanted to be able to display not just the MetaSpy Y page, but also information from vari- ous web sites (e.g., weather and traffic Figure 1—The Voyeur has three modes of operation: Configuration, Display, and Setup. For now, the Voyeur unit information). can operate in only one mode at a time.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 11 software enters Configuration mode Listing 1—This sample Python output is what the Voyeur unit processes in order to display phrases. Any infor- and loads the data stored in Setup mode mation can be converted easily to this form for the Voyeur to interpret. from flash memory. It then attempts to connect to the Configuration web site, reset setdispdelay 5 which is a kind of springboard that ddisp "food" enables the Voyeur to jump to one of ddisp "solar power refund" numerous bridge scripts that you may ddisp "pure platinum motorcycle" write. A separate Configuration page loadwebpage 10.2.63.4 bob.worldatt.com /cgi-bin/metaspy.py enables you to change the Voyeur’s behavior without having to perform the Listing 2—The Voyeur uses the most basic form of an HTTP request. The system doesn’t use the HTTP set-up procedure again. Simply change header in the response, so it can strip it off. the Configuration web site, and then Request: cycle power to the unit. After the GET /cgi-bin/metaspy.py HTTP/1.0 Voyeur successfully loads the Host: bob.worldatt.com Configuration page, it enters Display mode. In this mode, it executes every Response: command that the server it’s connected HTTP/1.1 200 OK to sends it. Date: Fri, 30 Sep 2005 02:57:00 GMT Server: Apache VOYEUR COMMAND LANGUAGE Connection: close Content-Type: text/plain Instead of having the eZ80Acclaim! expend processing time parsing complex reset web pages, we decided to let a web setdispdelay 5 server (being a more powerful and flexi- ddisp "food" ddisp "solar power refund" ble machine) do the grunt work for the ddisp "pure platinum motorcycle" Voyeur. To simplify the responsibilities loadwebpage 10.2.63.4 bob.worldatt.com /cgi-bin/metaspy.py of the embedded software and make it more flexible, a CGI-capable web server runs Python CGI scripts to parse the The ddisp command puts a phrase system (DNS), the protocol that resolves pertinent information from web pages. of text on the display. It takes all the a domain name to an IP address. This Although the parsing and decoding is text between the quotes and formats isn’t a major concern for anyone setting done off the board, a different way of it for display on the screen. This up the Voyeur or writing scripts for it. communicating display commands is includes ensuring that no words wrap Simple Python commands accomplish needed. from one line to the next. It also guar- the DNS resolution for the Voyeur. The Enter the Voyeur command lan- antees that phrases too large to fit on Python scripts are available on the guage (VCL). It’s a simple, text-based the screen at once are divided into Circuit Cellar FTP site. command set that’s intended to offer multiple screens with the proper delay A sample output listing from the the control of the Voyeur’s capabilities inserted in between. metaspy.py Python script is shown in to any web page that the Voyeur unit The loadwebpage command keeps Listing 1. The effect of having the loads. The command set is described the system running continuously. It loadwebpage command as the last in Table 1. reexecutes the script on the web server command in the VCL script is that the The reset command clears the dis- by reloading the web page. You may be script may load itself again. It does this play and sets the cursor to the home wondering why the command requires after the Voyeur finishes displaying the position. The setdispdelay config- an IP address and doesn’t simply accept items in the script. This results in ures the duration of time inserted a URL. This is because the evaluation unlimited fun as more and more ridicu- between each screen so that you have version of the Voyeur’s CMX TCP/IP lous searches show up (when you use enough time toWWW.GiURUMELE.Hi2.RO read the content. stack doesn’t support the domain name the MetaSpy bridge script, for example). The actual VCL command set is richer than what we’ve presented here, but the Command Description basics are explained. The full set con- reset Clears the display and sets the cursor to the home position tains other commands that have finer setdispdelay x Configures unit to delay x seconds between processing ddisp com- control over the display, like adjusting mands and between phrases that get split up between screens the brightness and blink rate. ddisp “phrase” Displays a phrase of variable length, splitting up the phrase at white space and delaying the configured amount between each screen HTTP BASICS loadwebpage ipaddr hostname Performs HTTP request to load next Voyeur command language page path from server specified by ipaddr, hostname, and path The Voyeur acts like a simple web browser, sending the most basic HTTP Table 1—Here are the four main VCL commands. They enable the Voyeur to perform its basic display functionality. request to get the response containing

12 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com the VCL. Sure, a full-featured request Because the demonstra- could be constructed, but all the tion CMX TCP/IP stack Voyeur really needs is a text/plain list- doesn’t support DHCP (the ing of commands. protocol that enables a The HTTP request consists of a GET device to automatically scriptname HTTP/1.0 command and obtain an IP address), set- a Host header. The response consists ting up the network param- of an HTTP status code and HTTP eters is slightly more com- headers, all of which are discarded. plicated than just plugging After the response headers is the in the Voyeur. Before per- Photo 3—Setting up is easy with a GUI front end written in Python that script’s output: the Voyeur commands. forming the setup for the communicates with the Voyeur unit over a TCP/IP connection. The response contains some informa- first time, the default unit tion that isn’t needed by the Voyeur, settings should be restored. This is Voyeur Setup Tool sends a series of so the data up to the two adjacent accomplished by installing the set-up VCL commands to the unit. (These pairs is discarded. Listing 2 jumper. At this point, the unit defaults commands are a special extension of is an example of the basic HTTP to an IP address of 192.168.1.77. You the VCL and should not typically be request that the Voyeur uses as well as may put the Voyeur unit back into used in normal Voyeur scripts for dis- a typical response. Setup mode and change the unit’s IP playing information.) When the Voyeur address, default gateway, and netmask Setup Tool is finished sending the SETTING UP VOYEUR to any value you desire. To set up the commands, it closes the connection and Setting up the Voyeur unit involves Configuration page that the Voyeur unit the unit resets, loads the Configuration configuring its network parameters as will load after power-up, simply enter a page, and begins running. well as telling it which Configuration regular web address in the URL field. page to load. We provided a simple GUI The Voyeur Setup Tool takes the HARDWARE INTERFACES (written in Python with the Tkinter set-up information and opens a short The main interfaces on the Voyeur’s module) called the Voyeur Setup Tool telnet session with the Voyeur board. motherboard are the three display to help perform the setup (see Photo 3). The Voyeur unit must be in Setup connectors, the set-up jumper, the All of the setup parameters are stored mode in order for the Voyeur Setup Ethernet jack, and the power connec- in flash memory so the unit may oper- Tool to initiate the connection with the tion (see Figure 2). The Ethernet jack ate after cycling power to it. unit. During the telnet session, the is on the eZ80F91 mini module. It is

WWW.GiURUMELE.Hi2.RO

Figure 2—The mini module plugs into eZ80F91-J1 and -J2. Any display with an LCD-compatible interface can connect to DISPLAY1 and DISPLAY2. The VFD connector pro- vides a SPI-type interface for older vacuum fluorescent displays.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 13 WWW.GiURUMELE.Hi2.RO not included in the schematic. You eZ80Acclaim! inputs are 5-V tolerant, was easy to write. It involved writing may download the eZ80F91 module’s this made interfacing between the different values to port A on the micro- schematic from Zilog’s web site. microcontroller and the Noritake dis- controller to bit-bang the standard LCD Power is supplied via a polarized play extremely easy. (The eZ80Acclaim! interface. To support the legacy Futaba Molex KK connector at the input is a 3-V part.) interface, we perform an auto-detect of labeled “powerjack” on the schematic. In order to be able to support dual dis- the display connected to DISPLAY1 by The Voyeur requires a regulated 5-VDC plays on future versions of the Voyeur, writing and then reading back two char- supply to power both the mini module we simply added another 14-pin con- acters. If the characters match, we (via a 3.3 VDC regulator) and the dis- nector that has identical connections to know that an LCD-type display is play. Any wall-wart will do, as long as the microcontroller, with the exception connected to DISPLAY1 and the lega- it is regulated and can supply at least of a separate data strobe line so different cy Futaba display isn’t connected. 1.5 A. We used a Xicon supply. The data can be sent to each display. The Otherwise, we fall back to communi- newer switching-type supplies are quite software driver for the LCD interface cating with the Futaba display. small and cost around $12. To put the Voyeur in Setup mode, place a shorting jumper on pins 1 and 2 of the header labeled PBTNS. Alternatively, you may decide to install an actual push button on the shadow box frame. An SPST push but- ton will suffice to short pins 1 and 2 just as the jumper does. The Voyeur has three display connec- tions. The hardware can operate two connections simultaneously. (This isn’t implemented in software—yet). For the Zilog 2004 Flash Nets Cash Design Contest, we used Zilog’s development board along with a smaller Futaba VFD. Since then, we’ve laid out our own cir- cuit boards with only the necessary interfaces in order to reduce size. Nevertheless, we kept the legacy Futaba interface (labeled VFD on the schematic) because we already had several of its displays on-hand. The other two display connectors (DISPLAY1 and DISPLAY2) are standard 14-pin LCD interface connectors. They can communicate properly with any type of display that supports a 4-bit, M68-type parallel interface. In addition to the 4 data bits, there are also read/ write (R/W), data strobe (E), register select (RS), and reset signals between the display and the microcontroller. We chose a 4-bitWWW.GiURUMELE.Hi2.RO interface over an 8-bit interface so that we could control the display from only one 8-bit port on the microcontroller. Most displays with standard LCD interfaces can be switched between 4- and 8-bit modes by sending them a command at power-up. Nearly all VFDs require a 5-VDC supply. Importantly, Noritake displays feature data line inputs that are com- patible with both 3- and 5-V logic. Combined with the fact that the

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 15 VOYEUR 2.0 ZTP TCP/IP stack, which doesn’t have Aside from the software, the Voyeur We already have several ideas for this restriction. Also, we’d like to add will become even more flexible when improving the Voyeur’s capabilities. the free Zilog RZK real-time kernel. we add an 802.11 wireless interface. I Fortunately, most of them are soft- This would enable the Voyeur to enter ware-only enhancements. The current Setup mode at any time (without hav- Jeremy Baugher has worked as a sen- software on the Circuit Cellar FTP ing to use a jumper). ior software engineer at Motorola in site uses the CMX TCP/IP stack that Other software enhancements will Schaumburg, Illinois for the past four came with the contest kit. This evalu- include the capability to interpret RSS years. He holds a B.S. in computer engi- ation version has the limitation that it feeds (they provide many short informa- neering from Case Western Reserve will run for only 1 h before disabling tion services, like breaking news, for University. Jeremy enjoys banging away itself. Thus, the Voyeur software must example), the ability to reflash the at Python code. You may contact him reset itself every hour. We’ll eventual- firmware over the network, and the abil- at [email protected]. ly port the software to use the free ity to drive both displays simultaneously. Stephen Fenwick has worked as a sen- ior software engineer at Motorola in Schaumburg, Illinois for the past seven years. He holds a B.S. in electri- cal engineering from the University of Michigan. He recently earned an M.S.E.E. from the Illinois Institute of Technology. He regularly watches his Voyeur system to determine when Chicago’s traffic is clear. You may con- tact Stephen at [email protected].

PROJECT FILES To download the code, go to ftp://ftp. circuitcellar.com/pub/Circuit_Cellar/ 2006/186.

RESOURCES J. Bentham, TCP/IP Lean, CMP Books, Gilroy, CA, 2002. Voyeur information and sample scripts, http://dooroneprojects.net. Zilog, Inc., “eZ80F91 Flash MCU with Ethernet MAC Product Specification,” PS0192, June 2004. ———, “eZ80F91 Mini Enet Module Product Specification,” PS0236, August 2004.

SOURCES US162SD03CB Display WWW.GiURUMELE.Hi2.ROFutaba Corp. of America www.futaba.com Xicon power supply (model 19-10520-4) Mouser Electronics, Inc. www.mouser.com CU20029ECPB VFD Noritake Co., Inc. www.noritake-elec.com eZ80F91 Microcontroller Zilog, Inc. www.zilog.com

16 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by Richard Wotiz

Electronic Scarecrow

CONTEST WINNER

Richard’s Electronic Scarecrow keeps animals from foraging for food in backyard gardens. It includes four remote stations designed around MC13192 SARD boards. When an animal is detected, the system generates loud sounds and runs water sprinklers to scare it away.

For the past 12 years, I’ve lived in a electric fence in his yard, but that didn’t Freescale’s MMA1260D and small rural section of an otherwise deter the deer either! It appears that MMA6261Q accelerometers detect urban area. A forest abuts my backyard. deer will eventually adapt to obstacles motion. When setting up your system, Although there have been many advan- they encounter on a regular basis. The you can mount an accelerometer on a tages to living in a natural setting, one only way to keep deer away is to create piece of plywood and post it on a path of the more annoying problems has deterrents they’ll never adapt to. where animals travel. You can also been the ever-increasing number of My Electronic Scarecrow system is a attach an accelerometer to one of a series deer that have come to forage in the great solution (see Photo 1). When an of flexible garden stakes connected by a area. Several times a day, for instance, I animal is detected, the system’s base wire. The wire will move when an ani- see deer munching in my yard. station activates countermeasures like mal climbs over it or slides under it. Most of the conventional methods loud sounds and garden sprinklers to Another idea is to connect a for keeping deer off my property no scare it away. The system includes four Freescale MC33794 e-field sensor to longer work because these foragers can remote stations designed around an insulated wire on the garden jump over fences and they don’t seem Freescale Semiconductor MC13192 stakes. The MC33794 will pick up a to mind the foul taste and smell of SARD boards. Each board is connected slight capacitance change as an animal repellents. One of my neighbors once to several sensors that transmit signals brushes up against the wire. You can got so frustrated that he installed an to the evaluation board on a base sta- connect the pressure sensor to a bicy- tion, which features an LCD, push but- cle tire or thin-walled flexible tubing ton controls, an X10 power line trans- placed under a sheet of plywood to act mitter interface, and a serial port for as a weight-activated switch. downloading code updates and sound Lastly, you can connect the switch files. The remote and base stations are built around MC13192 2.4-GHz trans- ceivers controlled by Freescale MC9S08GT16 (see Figure 1). I obtained the Freescale parts when I entered the 2005 Freescale Wireless Design Challenge.

WWW.GiURUMELE.Hi2.ROSENSING TROUBLE When I started this project, my goal was to build a simple yet reliable system for detecting a large animal. The best way seemed to involve using numerous types of sensors, several of which must be activated within a short amount of time in order to indicate a valid trigger. Photo 1—The base unit is on the left. The remote unit The sensors on the Freescale Wireless Photo 2—The SARD board is in the middle. The set of is configured with an e-field and a switch expander wide traces on the left edge acts as an antenna. Also board. The photovoltaic panel is ready to be mounted Design Challenge breakaway board included are the MC33794 e-field sensor, accelerome- on a garden stake. enabled me to achieve this goal. ters, pressure sensor, and switch expander boards.

18 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com expander to several IR opti- Animal detection The MMA1260D Z-axis cal beam-breaking sensors. accelerometer is a bit more Motion Plant Remote Accelerometer stake unit #1 You can place the sensors detection Base unit complicated. The accelerom- between fence posts or any eter’s I/O levels have to be Weight Flexible LCD Pressure sensor other fixed objects to estab- detection tubing shifted because 5 V powers it. Remote lish a perimeter. unit #2 An on-board regulator sup- X10 Proximity Fence Power line detection wire E-field sensor plies 5 V from the switched REMOTE UNIT interface 9-V supply. Remote Perimeter IR LED Photo 2 shows the remote Switch expander unit #3 The MPXM2010GS pres- detection and sensor unit’s hardware, which sure sensor shares the same Countermeasures includes a modified SARD input as the MMA1260D Z- Amplifier Startling Remote X10 and board and various sensor sounds unit #4 Module axis accelerometer, so only boards. The modular system speaker one of them can be connect- Sudden can include up to four SARD burst of Garden Sprinkler ed at a time. They have dif- sprinklers boards. Each board uses one water controller ferent output levels in Self of its on-board accelerometers Test mode, allowing the and can connect to as many Figure 1—Each remote unit can handle any combination of sensors. The remote units software to automatically transmit sensor activations to the base unit, which then activates the countermeasures. as three external sensors. distinguish between them. Also included are a PWM The sensor, which operates audio output for an external amplifier mize settling time. Between readings, directly from the 9-V switched power, and speaker and a logic-level output the microcontroller goes into Stop 3 produces an output signal of only for future expansion. You may down- mode and the radio goes into Doze 25 mV. This signal is amplified with a load a schematic of the complete sys- mode. I spent a lot of time evaluating TLC271B op-amp. It’s then shifted up tem from the Circuit Cellar FTP site. which clock modes would yield the from ground by approximately 500 mV The system is designed around an lowest overall power consumption. to compensate for the worst-case op- MC9S08GT16 microcontroller (see amp and sensor offsets. Figure 2). The SARD board actually SENSORS The MC33794 e-field sensor IC contains an MC9S08GT60 microcon- Each sensor (except the on-board measures small changes in capaci- troller, but all of the hardware and soft- accelerometer) has its own board and tance from up to nine electrodes. A ware is based on an MC9S08GT16 is connected directly to the SARD built-in shield driver minimizes the microcontroller. Changes aren’t required board. The MMA6261Q XY-axis effect of electrode cable capacitance. when switching to this part. All of the accelerometers are the most straight- It’s powered from the switched 9-V MC9S08GT16 microcontroller’s I/O forward. Their outputs are RC filtered supply. pins and most of its internal peripherals to eliminate the noise from their inter- The MC33993 switch expander is are used. nal switched capacitor filters. The out- configured to handle pairs of IR LEDs The SARD board includes an puts are then fed directly to the micro- and phototransistors. The expander MC13192 2.4-GHz radio transceiver with controller’s ADC. Power comes from wakes up every 64 ms for 125 µs to separate transmit and receive antennas. the switched 3-V supply. check the sensors, and it interrupts the It also has an RS-232 port, microcontroller if the status which is used only for debug- changes. It also has to be ging, and a pair of accelerome- able to wake up the radio to Switch ter sensors. Only the XY-axis expander enable its CLKO pin, which connector accelerometer is used. The BDM supplies the MC9S08GT16 connector On/off switch board has several connec- connector microcontroller’s clock. I MC13192 tors for the various external 2.4-GHz BDM do this by feeding the Sensor radio SPI ADC sensors. It also has a system connector expander’s *WAKE output transciever MC9S08GT16 Enable/Disable switch. Two MCU to the radio’s *ATTN input. WWW.GiURUMELE.Hi2.ROAudio amp address select jumpers enable PWM The MC9S08GT16 micro- connector ADC UART up to four boards to be indi- XY-axis RC RS-232 Serial controller can disable this vidually addressed. accelerometer filter Converter connector function by holding port pin A NiCd battery charged 9 V 3-V Switched PTC2 high. The LED out- Power by a photovoltaic array pow- 9-V Switched puts are set to source 16 mA PV Panel Current control ers the remote unit, so min- 12 V, 50 mA regulator of drive current on SP7:0. Voltage imizing power consumption 3 V The sense inputs SG7:0 are regulator is a primary design goal. 9.6-V set to 2 mA. Pins SG13:8 Sensors are turned on only NiCd are hard-wired to an alter- when necessary. Sensor cir- Figure 2—The MC9S08GT16 microcontroller is at the center of all the action. It coor- nating high/low pattern for cuitry is designed to mini- dinates all the sensors and transmits their statuses to the base unit over the radio link. the purposes of self-testing.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 19 batteries are charged from a photovoltaic a valid trigger event, it instructs the array made up of eight 3-V, 25-mA remote to activate its audio or logic- photovoltaic cells wired in series/par- level outputs, generates a local logic- allel for 12 V at 50 mA. The battery level output (which is currently feeds a low-power, 3-V regulator. A unused), or sends a command to an X10 transistor acts as a 9-V power switch. interface. The X10 protocol is a simple 120-kHz on-off keyed modulation, BASE UNIT which must be synchronized to the The base unit features a modified power line’s zero crossings. The external evaluation board. A separate board X10 transmitter, which provides an contains a 2 × 16 LCD and three push optoisolated zero-crossing output that’s buttons (see Photo 3). The evaluation fed to one of the microcontroller’s timer board came with an MC9S08GT60 capture channels, does this. Another microcontroller, but all of the hard- channel’s PWM output feeds the X10 Photo 3—The base unit is built around an MC13192 ware and software was based on a transmitter’s input, which controls evaluation board. I modified its power supply and MC9S08GT16 microcontroller, as the 120-kHz signal. added an X10 interface. The LCD daughterboard with the remote unit (see Figure 3). I I had some difficulty with the first mounts on top of the evaluation board. The heatshrink insulated backup battery is sandwiched in between. used almost all of the MC9S08GT16’s LCD I used because its inputs appeared I/O pins and most of the internal to require CMOS levels even though the peripherals. datasheet specified them as TTL. One AUDIO OUTPUT The evaluation board includes an manufacturer I contacted confirmed One method of scaring animals away MC13192 2.4-GHz radio transceiver the problem, but I was told that the is to startle them with loud sounds. The with an NEC Electronics uPG2012 company wasn’t concerned that its remote station can output a sound file antenna switch that enables you to datasheets didn’t match the parts. The using one of the MC9S08GT16 micro- use one antenna for both transmission company claimed that everyone else controller’s timers in PWM mode and and reception. I had to find a suitable does it. Caveat emptor! drive an external amplifier/speaker antenna to fit the board’s SMA con- Living in the woods, I frequently module. nector because most Wi-Fi antennas use experience power failures, some of The amplifier is based on an a nonstandard reverse-polarity plug which last for several days. A regulated STMicroelectronics TDA2822M dual (RP-SMA). The board also includes an 5-V wall adapter normally powers the low-voltage amplifier configured in RS-232 port for downloading flash base unit, but I wanted it to be able to Bridge Drive mode. Because the peak memory updates and a USB port, which keep time for at least a week without supply current can approach 1 A, it has is currently unused. An RJ-11 connects requiring external power. I also wanted its own high-current power switch. A to a PL-513 or TW-523 X10 transmitter, to use a lithium battery so I wouldn’t divider at the system’s input keeps the enabling the base unit to send X10 have to remember to replace it. speaker from being overdriven. An RC commands over the power line. During a power failure, the 3-V regu- filter filters out the 16-kHz PWM The base unit is normally in Receive lator sends a signal to the MC9S08GT16 carrier frequency. mode, where it waits to hear from a microcontroller. This puts the MC13192 remote. When the unit acknowledges in Doze mode with its CLKO output POWER driving the MC9S08GT16 The remote units are microcontroller’s clock mounted away from any BDM and real-time interrupt connector power sources, so they have 2 × 16 LCD (RTI) counter at 32 kHz. to be self-sufficient. The In this state, the system BDM Push button MC13192 average power consump- SPI switches consumes 35 µA, which is 2.4-GHz MC9S08GT16 Menu Select Exit tion varies depending on Radio low enough to run for Antenna MCU transciever RS-232 Serial switch which sensors areWWW.GiURUMELE.Hi2.RO installed. KBI PWM UART Converter connector approximately eight This varies from 170 µA months using a CR2032 USB for the XY-axis accelerom- USB lithium coin cell. The Pwrfail Interface connector eter up to 1,750 µA for the 5 V clock stops automatically if Voltage 3 V X10 RJ-11 e-field sensor. 5 VIN power isn’t restored after a regulator Interface connector A set of eight AAA (To PL-513 few days. In this state with NiCd batteries supplies transmitter) the radio held in reset and power with a capacity of 3-V all the microcontroller 240 mAh. This can run Battery functions stopped, the sys- the system at 3.25 mA for Figure 3—The main unit is straightforward. The MC9S08GT16 microcontroller receives tem draws 2.5 µA. This three days, or longer, if less sensor status packets from the remote units. It can activate countermeasures using X10 will last for the lithium current is needed. The power line commands. The backup battery keeps the clock running during power failures. battery’s 10-year shelf life.

20 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com The DC power jack’s switch contact is it has something to report such as a case a sensor was present but failed its also connected to a microcontroller sensor trigger event or the press of a test. The next step is to read and store input pin. If I unplug the power con- switch. It also sends ping packets with the zero offsets for all the sensors. Lastly, nector, the clock will stop sooner than the results of sensor tests performed at a final test on each sensor ensures that if the power had just failed. This elim- regular intervals. The base unit always its value is within a valid input range. inates the need for a separate power responds by sending back a reply packet. Intended to check for broken wires, switch. The remote unit handles the resending these final tests are repeated each time of missed packets. Because packets are a ping packet is sent. REMOTE UNIT SOFTWARE sent infrequently, any external RF The main loop begins by reading all The application code, which I wrote interference is usually different from the connected sensors. The accelerom- in C language with CodeWarrior 3.1 one packet to the next. Therefore, eters should be checked every 50 ms from Metrowerks (now Freescale searching for the quietest channel to avoid missing an event. The others Developer Technology Organization), didn’t make sense, so I just went with can be read every 500 ms. The switch uses the SMAC 4.0 protocol stack. a fixed channel. expander doesn’t need to be read This isn’t ZigBee- or 802.15.4-compliant The SMAC stack had all the features because it interrupts the MC9S08GT16 because I don’t need compatibility required for this simple protocol. I microcontroller whenever its status with other devices. added a few functions for system con- changes. I wanted to be able to change When I started development, I found trol, including support for Timer2 and the sensor thresholds without recom- that the software for downloading the Doze mode, the ability to read GPIO piling the code, so I put them in a boards wouldn’t run on Windows 98. pins, and control over the ATTN pin structure that’s loaded at a fixed address The demonstration programs and the interrupt. I also made a few changes to at the beginning of the code. (Refer to compiler were fine, but I couldn’t decrease the execution time of some struct THRESHOLDS in the Periph.h download new code. There weren’t any frequently used routines. file posted on the Circuit Cellar FTP alternatives (short of upgrading my site.) This made them easy to patch. PC), so I made my own. Because I didn’t MAIN ROUTINE need any of the ZigBee embedded boot- The flowchart posted on the Circuit CHECKING FOR REPLIES loader’s special features, I found a Cellar FTP site shows the remote After all the sensors have been read, generic serial bootloader and borrowed unit’s main routine. After initializa- the main routine checks if the latest a P&E Microcomputer Systems BDM tion and sensor tests, the unit remains outgoing packet has been acknowledged. Multilink download cable so I could in the main loop, which reads the sen- Normally, the ACK packet should arrive try it out. The bootloader also came sors, checks for a switch press, checks while the sensors are being read. Each with a DOS program (hc08sprg.exe) for incoming reply packets, and then request packet (except for resent that talks to it over a serial port. (You sends a request packet if necessary. duplicates) has a unique sequence may download the hc08sprg.exe file In order to minimize power con- number with a matching reply having from the Circuit Cellar FTP site.) I sumption, sensors are read only if they the same number. If these numbers used the bootloader for the rest of the are installed and working properly. don’t match, it means a reply has been development process. During initialization, the sensor_init lost. If this occurs too many times, the The entire application fits in 7 KB of routine executes a presence detection transmit power increases unless it’s flash memory, leaving 8.5 KB available algorithm for each sensor. For the already at its maximum. In this sort of to store a PCM sound file. This pro- accelerometers, the algorithm uses their case, you can only assume an unrecov- vides about one 1 s of sound at 8 kHz. built-in hardware self-test functions. erable problem, so the remote will I wanted to be able to download a new The pressure sensor’s external amplifier sleep for 1 h before retrying. sound file or update the running code has a similar self-test function even When a valid reply is received, the over the radio link. The latter required though it doesn’t actually test the sen- routine checks if it’s a block of down- some changes to the serial bootloader, sor. Because it uses the same input as load data. If it is and its data length is which sits in a 512-byte protected area the MMA1260D Z-axis accelerometer, nonzero, the data is written to the at the top of the flash memory. To free the self-test voltage level is sufficiently sound file download buffer in flash up enough spaceWWW.GiURUMELE.Hi2.RO to add the update different so the software can tell which memory. A zero length download function, I replaced the bootloader’s one is connected. The MC33794 e-field packet indicates the end of data and flash memory routines with smaller sensor’s test looks at the reference input contains a checksum. If it’s a code ones from a MC9S08GB/GT serial levels, while the switch expander test update, the buffer needs to be copied monitor. The remote download fea- reads six of the input bits that are hard- to the executable code area, overwriting ture enabled me to update both the wired to an alternating high/low pattern. the existing code. The bootloader han- base and all of the remotes through After all the tests, pull-ups are dles this and will reset the system if the base unit’s serial port. enabled on all of the MC9S08GT16 the update succeeds. The radio link operates with a sim- microcontroller’s analog input pins Finally, the code checks the packet’s ple request and reply protocol. A that didn’t have valid sensor signals. I flags. Two flags control output remote unit sends a request whenever didn’t want to set them to outputs in actions, activating either the auxiliary

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 21 output or the sound playback func- receive timeout than usual in order to BASE UNIT SOFTWARE tion. The playback routine looks for a boost the integrity of the download The base unit’s code uses approxi- wav formatted file in the sound file process. mately 70% of the MC9S08GT16 flash memory buffer area, which must microcontroller’s 16-KB flash memo- be in 8-bit 8-kHz PCM format. If the TEST MODES ry, and it includes the serial boot- file is found, it turns on the external The remote unit has a pair of test loader with the remote code update amplifier and plays the sound file. The modes that are helpful when setting feature disabled. The second page of file can be looped several times as up the system. Holding down the On the flowchart posted on the Circuit specified by the packet flags to pro- switch while the MC9S08GT16 Cellar FTP site shows the main rou- duce up to 5 s of sound. A third pack- microcontroller resets enables Local tine. After initialization, the main et flag enables Download mode, which Test mode. This turns on the LED loop enables Receive mode and waits erases the download buffer and pre- when any of the sensors are triggered. for a packet. As it waits, it calls vari- pares to receive a new data file. Holding the Off switch down as the ous activity-processing routines. MC9S08GT16 resets enables Remote After a valid packet arrives, its OUTGOING PACKETS Test mode. This calls a special routine sequence number is checked against After the replies are processed, the that constantly reads the sensors and the last packet received from the code figures out whether or not it’s sends data packets. The LED indi- same remote unit. Normally, it will time to send a packet. If the last sent cates a valid reply packet, so this be incremented by one. If it’s the packet wasn’t acknowledged, it’s sent mode is useful for radio link testing. same though, it means the packet is a again. Otherwise, it checks whether or Sensor data values are also sent out duplicate, which indicates that the not a new request packet is needed. through the serial port, which is remote unit didn’t get your last reply. A data packet is sent if the sensor useful for more detailed system If that’s the case, a flag is set and an status changes from the last time it evaluation. error counter is incremented. If was sent. The data packet contains the current sensor status Listing 1—This routine implements the trigger logic for each of the eight output channels. It checks the sensor status, repeat coun- and a sensor data value. ters, delay timers, and activation time to determine if an output should be activated. If a switch is activat- byte check_outputs (byte inputs) ed, indicating that { you want to enable or struct OUTTRIG *trigp; disable the system struct OUTPUT *outp; byte out_no, outputs, i, j; remotely, an outputs = 0; enable/disable packet is for (out_no = 0; out_no != NOUTPUTS; out_no ++) { //Check each output channel sent along with the trigp = &out_trig[out_no]; //Use ptrs for faster access outp = &Outputs[out_no]; switch status. This //If output enabled, and sensor triggered & enabled enables you to enter if (outp->dev_type != DEV_TYPE_none && (inputs & outp->sns_sel) != 0) { the protected area trigp->rpt_dly = outp->rpt_dly; //Init repeat delay time if ((inputs & trigp->sns_sel) != 0) //If sensor was active before, without triggering the trigp->sns_rpt ++; //then incr repeat count system. You can enable trigp->sns_sel |= inputs & outp->sns_sel; //Save active sensor bits the system again when for (i = trigp->sns_sel, j = 0; i != 0; i >>= 1) if (i & 1) you leave. j ++; //Count number of active sensors If it’s time to send a if (j >= outp->sns_mult //Do we have enough sensors, ping, the sensor test && (byte)(trigp->sns_rpt + 1) >= outp->sns_rpt //and enough repeats, && trigp->wait_dly == 0 //and have waited long enough, routines are executed && (*(word *)&Time.hour) >= (*(word *)&outp->on_time) //and are within the and the results are sent && (*(word *)&Time.hour) <= (*(word *)&outp->off_time)) { //activation window? along with the battery trigp->sns_sel = 0; //Clear the repeat stats trigp->sns_rpt = 0; and charger voltages. If WWW.GiURUMELE.Hi2.ROtrigp->rpt_dly = 0; enough time has passed Last_trig.time.hour = Time.hour; //Update the activation stats that the sensor offsets Last_trig.time.min = Time.minute; Last_trig.days = 0; may have drifted, if (Syscfg.enabled != 0) { //Check master system enable flag they’re reread as well. outputs |= bit_mask (out_no); //Now set the channel’s output bit A download data trigp->wait_dly = outp->wait_dly; //Update the wait delay time } request packet is sent } when Download mode } is enabled. The packet } return (outputs); //Return with bitmask of triggered is sent using maximum //channels transmit power. It’s fol- } lowed by a longer

22 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com enough errors occur, the trans- Setting Values three-phase power system, so mit power is increased if it Output device None, sound playback, X10 device, local the protocol specifies a 1 to isn’t already at maximum. If auxiliary output, remote auxiliary output be three identical 1-ms wide the packet number is out of X10 code (X10 device only) House code A–P, unit code 1–16 output pulses spaced 2.778 ms sequence, a flag is set to let Output duration 0–15 s (1/360 Hz) apart, which rep- you know there was an error. Start time 0:00–23:59 resents each phase’s zero Next, the incoming packet Stop time 0:00–24:00 crossing locations. A 0 occu- is processed and a reply is Enabled sensors Accelerometer, e-field, pressure, switches pies the same time interval sent. If it isn’t a duplicate data Multiple sensors required 1–4 without any output pulses. packet, the sensor status is Multiple activations required 1–8 The main program loop saved and a check is run for Multiple activation interval 0–7 min. calls a routine to store all of trigger events. The remote Repeat activation hold-off time 0–31 min. the bits for a command in a unit handles some of the out- Table 1—The configuration menus enable you to set the output device and acti- buffer. They’re pulled out one put responses (e.g., sound vation parameters for each virtual output channel. For an X10 device, setting the at a time at each zero cross- playback and auxiliary out- duration to 0 will result in an on command without a corresponding off command. ing. The power line status is put), so the program checks monitored by comparing the for these right away and sets the manually. The available settings are zero crossing rate to a 360-Hz timer appropriate flags in the reply packet. A listed in Table 1. overflow, which is also used to call the check for a pending download request push button switch debounce routine. is also made so the corresponding flag X10 INTERFACE The real-time clock routine counts can be set. If it’s an enable/disable The well-documented X10 power the number of zero crossings during a packet, the system master enable flag line carrier system has been in use for 24-h period whenever the 60-Hz signal will be updated. If it’s a ping packet, many years. The PL-513 transmitter, is valid. If it’s off from the expected the various status bytes will be simply which supplies a 60-Hz line zero- value, the error is used to adjust the saved for later. If a download data crossing signal to the MC9S08GT16 MC13192’s oscillator trim register to request arrives, a block of data will be microcontroller, expects a gate signal try to get an accurate time. The real- read from the serial port and sent out to enable its 120-kHz carrier output. time clock is based on the 32786.9-Hz the remote unit. The output is designed to work with a (16 MHz/488) CLKO signal divided

EVENT TRIGGERS The heart of the Electronic Scarecrow is its output triggering sys- tem, which collects the sensor trigger status from all the remote units and decides whether or not to activate a countermeasure. The system is highly configurable. Different sensors can be enabled at different times of day. The system can specify whether or not multiple activations are required with- in a certain time interval and whether or not the activations must come from different sensors or the same one. Listing 1 shows the routine that implements this trigger logic. There can be up to eight virtual out- put channels, each having different triggering parametersWWW.GiURUMELE.Hi2.RO and driving one of the various outputs. Several chan- nels can drive the same output. This can be useful for playing back sounds. During the day, you can set activa- tion to a single sensor with a 5-s sound duration. In the evening, you can set multiple activations with a shorter sound duration in order to keep the peace with your neighbors. You can also trigger each channel

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 23 down by 32,768, which is slightly sound file, which is left in the buffer a 9-V battery and 5-V regulator from faster than 1 Hz. It has to adjust its for later. The base unit reads in the the breakaway board in a small box. concept of a day to 86449.8 counts data file from the PC as it’s sent with- ((16 MHz/488/32,768) × 86,400 sec- out buffering it locally, so it has to be TESTS TO COME onds per day) to compensate for this. transferred once for each remote I haven’t had the chance to test the After doing so, the time of day should unit’s update. A batch file on the PC system as much as I’d like. The eating be as accurate as a line-powered clock. automates this process. habits of deer are so unpredictable. But I expect my neighbors will soon MENU SYSTEM CONSTRUCTION be complaining that the deer spend The Electronic Scarecrow features a Photo 2 shows the Freescale ZigBee more time foraging in their gardens user-friendly menu system, which is a demonstration boards and all of the than in mine! I table-driven state machine consisting of sensors from the sensor breakaway LCD prompts and actions that enable board supplied to ZigBee Wireless Richard Wotiz earned a B.S.E. in elec- you to control everything via three Design Challenge entrants. The SARD trical engineering and computer sci- push buttons. The menu-processing boards I used for the remote units ence from Princeton University. He routine is called from the main loop required significant modification. has run his own hardware consulting once every 1 s or whenever you press Most of the sensor boards were fairly business for the past 14 years, special- a button. The menu table contains the easy to modify because almost all of izing in consumer products and chil- text for each menu state, the routines, the IC pins were in just the right dren’s toys. You may contact him at and the next states after you press the places to install connectors where I [email protected]. Menu and Select buttons. needed them. The notable exception The Exit button always returns to was the MMA6261Q accelerometer, the top menu state. From this state, which was missing a connection on PROJECT FILES the Menu button steps through each its self-test pin. Its pins are under- To download the code, additional files, of the primary menus. Pressing the neath the package, so it was a chal- and a schematic of the system, go to Select button drops you down one lenge. ftp://ftp.circuitcellar.com/pub/Circuit_ level or increments a displayed param- I mounted the photovoltaic cells on Cellar/2006/186. eter if you’re already at the lowest a curved piece of plastic and attached level. it to the top of a heavy-duty garden RESOURCES stake (see Photo 1). The cells are rated CODE UPDATES for short-term outdoor use, so I’ll add P. Lajsner, “Developer’s Serial You can download updated code for a protective layer on top of them at Bootloader for MC68HC08 and HCS08 the base and remote units via the seri- some point. The box mounts on the MCUs,” AN2295, Freescale al port on the base unit. For base unit same stake so its built-in accelerome- Semiconductor, November 2004. updates, the PC talks directly to the ter can pick up movement. The two J. Sibigtroth, “Serial Monitor for serial bootloader. I wanted the remote RJ-11 jacks located just above the MC9S08GB/GT,” AN2140, Freescale update to use the same protocol, so I batteries are for a second accelerom- Semiconductor, June 2003. set up the base unit code to simulate eter and the pressure sensor, which the bootloader’s responses. I can use are both mounted in tiny boxes and D. Rye, “PL513/TW523 Technical the same program running on the PC can be placed in other areas of my Note,” X-10 (USA), www.x10.com/ for both base and remote updates. property. support/support_manuals.htm. Selecting the base unit’s update func- The base unit’s evaluation board was tion simply resets the MC9S08GT16 much easier to modify (see Photo 3). I microcontroller and starts the flash replaced the power supply, added cir- SOURCES memory-based bootloader. cuitry for the X10 interface, and CodeWarrior The remote unit update is consider- moved some connectors so the board Freescale Developer Technology ably more complex. The base unit would fit into the box. I mounted the Organization (formerly Metrowerks) notifies each remoteWWW.GiURUMELE.Hi2.RO unit of a pending push buttons on a small piece of perf www.metrowerks.com update one at a time by setting a flag board that I attached to the LCD. MC13192 SARD board, MC33794 e- in the reply packet the next time it I sandwiched together the LCD and field sensor IC, MC9S08GT16 micro- sends one. Then the remote unit evaluation boards before dropping controller, and MPXM2010GS pres- requests download packets. The base them into the plastic box. I made the sure sensor unit replies with a block of data that front panel legend by running an Freescale Semiconductor, Inc. the remote unit writes to its download adhesive Mylar sheet through a laser www.freescale.com buffer. After the entire file is sent, the printer. remote checks if it’s a valid code I wanted to be able to carry the base BDM Multilink update. If so, it calls the bootloader to unit outside, so I made a portable power P&E Microcomputer Systems perform the update. Otherwise, it’s a source by putting the PCB containing www.pemicro.com

24 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by Serhiy Matviyenko Low-Cost EKG Pulsometer

Healthcare professionals use expensive high-tech pulsometers to monitor their patients’ pulse rates. You can use Serhiy’s low-cost EKG pulsometer for a variety of medical, sports, and home appliance applications.You won’t miss a beat with this CY8C27443-based system.

Pulse rate measurement is an bands enables you to determine the important part of medical and athletic blood oxygen saturation level. This testing. But the pulsometers used in method yields more than a simple hospitals and sporting facilities tend to pulse rate measurement. Light modu- be expensive. In this article, I’ll show lation curve analysis can also detect you how to build an inexpensive elec- respiratory system illnesses. trocardiogram (EKG) pulsometer around My EKG pulsometer involves pulse a Cypress Semiconductor CY8C27443 rate electrical signal detection. This microcontroller (see Photo 1). method requires you to use an EKG to measure electric impulse reception. PULSE MEASUREMENTS Routinely used in hospitals as a tool There are various methods for meas- for identifying cardiac disorders, it’s uring pulse rates. For instance, you can the most accurate method for heart manually measure someone’s pulse rate rate measurement. To detect electrical Photo 1—What do you think of my EKG pulsometer? It by touching his wrist (radial artery) or signals, you must place two or more starts working when you put your hands on the elec- neck (carotid artery). You can even find a electrodes on your patient’s hands. trodes. I used pennies as the electrodes. pulse in a person’s elbow (brachial artery) Analyzing the EKG data from the elec- and groin area (femoral artery). When trodes provides a quantitative descrip- atrial contraction and the beginning of you find a pulse, count the number of tion of the heart’s electrical activity. a ventricular contraction. Finally, the beats per minute. This is a simple way Six peaks and valleys labeled with T peak marks the ending of a ventric- to take measurement, but it’s easy to successive letters of the alphabet (P, Q, ular contraction. The magnitude of make errors. For example, if you use R, S, T, and U) characterize the EKG the R peak normally ranges from 0.1 your thumb, you might mistake your signal (see Figure 1). The P peak is pro- to 1.5 mV. If the R peak is narrow and pulse for the other person’s. duced by a contraction of the atria. high, you have a strong heart. You can also measure pulse rates The R peak shows the ending of an A complete heart cycle consists of mechanically. Mechanical methods systole and diastole phases. The are based on the conversion of former refers to the contractile 1.5 blood vessel rippling into electric (pumping) phase. Diastole refers QRS RR Interval signals via a strain or pressure Complex to the resting (filling) phase. sensor. A piezoelectric sensor is 1 The average heart rate is calcu- typically used for such an appli- Systole lated by measuring the time WWW.GiURUMELE.Hi2.RODiastole cation, but the sensor position is interval (the RR interval) sensitive to the vessel location and E (mV) 0.5 T T between two consecutive R P vessel displacement. Conventional P peaks, taking the average recip- tonometers are large and imprac- rocal of this value over a fixed 0 tical for long-term use. period of time (usually 15, 30, Q Q Another option is to take S or 60 s), and then scaling to S measurements optically. Optical -0.5 QT Interval units of beats per minute (bpm). tissue measurements are based 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 The R peak is a part of the QRS on light absorption levels. Time (seconds) complex, which represents ven- Measuring the difference in light Figure 1—The EKG signal is characterized by six peaks and valleys tricular depolarization. The absorption in infrared and red labeled with successive letters of the alphabet (P, Q, R, S, T, and U). duration of the QRS complex is

www.circuitcellar.com 28 Issue 186 January 2006 CIRCUIT CELLAR® WWW.GiURUMELE.Hi2.RO normally between 0.06 and a) filtering in the CY8C27443 0.1 s. To pick the R peak, you processes the acquired EKG must take the first derivative signal. A second-order infinite from the EKG signal (see impulse response (IIR) low- Figure 2a). pass filter is for power-line 50- A few things can corrupt an and 60-Hz interference sup- EKG: electrical interference pression. After digital filtering, from nearby equipment, meas- the pure EKG signal passes urement noise (or electrode through the differentiator, contact), electromyogram noise b) where the QRS complex is (muscle contraction), move- picked out. A smart peak ment artifacts, baseline drift detector with a threshold level and respiratory artifacts, and that’s automatically adjusted instrument noise (artifacts to increase the noise resist- from the ADC process). A vari- ance detects the pulse beats. ety of signal-processing tech- Figures 2a and 2b show the niques can be employed for fil- EKG signal before and after tering the raw EKG signal prior digital filtering. Figure 2c is to feature extraction and the c) the first derivative of the diagnosis of medical disorders. EKG signal, which is used for Before calculating a heart pulse rate calculations. You rate, you must process the EKG can clearly see how the in the analog (amplification, threshold adaptive algorithm common mode voltage sup- works. Note that all the dia- pression, and filtering) and grams are measured in differ- Figure 2a—Take a look at the EKG signal before digital filtering. The power-line digital (digital filtering) ent time intervals. noise has an amplitude larger than the desired EKG signal. b—Now study the domains. In my project, a EKG signal after digital filtering. Passing the EKG signal through the cascade of For external pulse wave sig- PSoC CY8C27443 microcon- three second-order IIR low-pass filters reduces the noises. QRS complexes and nal processing and debugging, troller controls most of the T peaks are clearly revealed. c—The first derivative of the EKG signal is used for the EKG samples can be sent pulse rate calculations. The automatically adapted threshold level is shown. functions in real time. via an RS-232 port. The noisy EKG signal from the human PULSOMETER when hands are placed on the elec- hands passes through the RFI filter (R5, My EKG pulsometer is a fairly sim- trodes. The threshold circuit and com- R6, and C1–C3) to the input of the ple device (see Figure 3). The software, parator detect this moment. This embedded CY8C27443 microcontroller which calculates the pulse rate in beats reduces power consumption and pre- INSAMP, which has a CMRR of ~60 dB per minute, provides information such vents the pulsometer from responding (see Figure 4). The INSAMP’s gain is 16. as the pulse rate and error conditions. to accidental periodic noise. From the INSAMP’s output, the EKG The EKG signal passes through the From the INSAMP’s output, the signal passes through a high-pass filter RFI filter (cuts inducted RF signals) to EKG signal passes through a high-pass (C5, R9) and is fed in via the microcon- a high common-mode-rejection ratio filter and is buffered by a buffer ampli- troller’s port P0.6 to the input buffer (CMRR) instrumentation amplifier fier. Then the signal is digitized via a amplifier. The high-pass filter’s cutoff (INSAMP). The INSAMP rejects the 13-bit incremental ADC. frequency is 2 Hz. Then, the signal is common-mode voltages (a ~300-mV Processing the ADC datastream is digitized via a 13-bit incremental ADC. common-mode component from the implemented with firmware. Digital The common-mode voltage is derived potential between the electrodes and the skin, power-line interference, and other noise sources) and pre-amplifica- Electrodes Buf Notch Service WWW.GiURUMELE.Hi2.ROon left hand RFI filter INSAMP ADC LDC tion of the differential EKG signal. amp filter routines An antiphase signal fed back to the Theshold electrodes improves noise immunity. circuit Comparator Electrodes Pulse rate calculation The circuit includes a buffer amplifier on right hand Antiphase signal generation R11M and an inverting amplifier that applies Inv Buf R21M Smart-peak an inverted version of the common- amp amp Differentiator detector mode signal to the hands in order to cancel the interference (see Figure 3). Implemented software If you don’t place your hands on the Figure 3—The internal PSoC blocks are shown in blue in this flowchart of the pulsometer’s functional blocks. The electrodes, the Pulsometer enters main functional blocks of the CY8C27443 microcontroller include the INSAMP, two buffer amplifiers, an ADC, a Sleep mode. A voltage shift occurs comparator, and an inverting amplifier.

30 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com from the INSAMP’s inter- nal resistors. The inverted amplified value of this volt- age is taken from port P0.4 via resistors R7 and R8. It’s then applied to the hands to suppress the power-line interference. In addition to applying inverted common- mode voltage, the resistors (R7, R8, R3, and R4) play a part in the threshold cir- cuit. They help detect the moment hands are placed on the electrodes. Let’s take a look at how this circuit works. The voltage drop on R3 or R4 is small: ~R4 × IB, where IB is the INSAMP’s input bias current. When hands touch the elec- Figure 4—It’s amazing how few external components are needed to run this design. Without a debug serial port, you only need the trodes, the potential on PSoC microcontroller, an LCD, and a couple passive components. the R4 resistor increases higher than VCC/2. This voltage passes enables the heart rate calculation. (AAMI) standards for safe current lev- through a low-pass filter (R1, R2, and The values of resistors R1 through els. The RMS ground currents or fault C4) to port P0.5 and to the input of R8 comply with Association for the current from the electronics must be the comparator. The comparator Advancement of Medical Instrumentation less than 50 µA.

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 31 The calculated pulse rate is displayed The CY8C27443’s 2.5-V analog SYSTEM SOFTWARE on a low-cost LCD. D1 is an LED that ground (AGND) is fed out via the ana- The pulsometer’s software reads and flashes every time a beat is detected. log driver of the fourth column to port digitally filters the ADC data. It also The optional RS-232 optoisolated-level P0.2. Because the buffer amplifier calculates the pulse rate and displays translator (U2) is used for sending the already uses the ACB03 block, you it on the LCD. ADC data to the external PC. need to use the ACB03CR2 register to Figure 5 illustrates the real-time signal- enable and propagate the AGND sig- processing algorithm. After initializa- PSoC INTERNALS nal to the fourth column. This is done tion, the software repeatedly reads the Cypress Semiconductor’s family of using the TestMux bits in the RefMux ADC with a sampling rate of 240 Hz. A PSoC microcontrollers consists of module. cascade of three second-order IIR low- numerous mixed-signal arrays with The common-mode voltage is derived pass filters filters the ADC samples. In on-chip controller devices. These from the INSAMP’s NON_INV block. general, an IIR filter is represented by devices are designed to replace tradi- This voltage is inverted and amplified by an equation in which the output signal tional microcontroller-based system the low-pass filter (ASD11 and ASC21 at a given instant is obtained as a lin- components with one low-cost pro- blocks). It’s fed via the ASC12 block to ear combination of I/O signal samples grammable device. PSoC devices port P0.4 and applied to the hands. To at earlier times. These filters are include configurable blocks of analog minimize power consumption, the designed to suppress the 50- and 60-Hz and digital logic as well as program- power remains off while the pulsometer interference. Each has the following mable interconnects. This architecture is in Sleep mode. The CY8C27443’s transfer function with a cutoff fre- enables you to create customized internal structure includes the LCD user quency of 25 Hz: peripheral configurations that match module and an 8-bit serial transmitter. ()−−21 () 0.0625 1 + z + 0.125z the requirements of each application. Hz = −−[1] 1 − 0.75z 12 + 0.25z With PSoC Designer, you can config- ure, write application code, compile, Start The first-order IIR high-pass filter build, and debug your customized sys- with a cutoff frequency (FC) of 70 Hz tem. As for the CY8C27443’s internal Initialization determines the first derivative of the structure, the voltage from the external EKG signal used for pulse rate calcula- RFI filter passes through ports P0.0 tions. and P0.1 to the INSAMP’s input Are the hands −1 on the electrodes? Sleep 0.5() 1 − z (ACB00, ACB01, and ASC10 blocks). Hz() = [2] − −1 From the INSAMP’s output, the 1 0.015625z Y amplified EKG signal is fed out via To implement Equations 1 and 2 in Digital filtering port P0.3 to the external high-pass fil- C code in a fixed-point representation, ter. The purpose of the high-pass filter you must scale the filter’s coefficients Differentiation is to remove DC components. From by 65,536 and then verify if the filter the high-pass filter’s output, the EKG remained stable (i.e., all the poles lie signal is fed out via port P0.6 to the Is QRS within the unit circle of the z-plane). complex buffer amplifier’s (ACB03 block) input. detected? The quantized filter is stable if: The buffer amplifier’s output is con- Y nected to the ADC, which is placed in lim hn() = 0 [3] n→∞ the ASD13 block. The ADC resolution Are the 11 QRS is set to 13 bits. The sampling rate (F ) complexes where h(n) is the quantized filter’s S detected? is 240 Hz. impulse response. I used MATLAB to The low-power comparator is placed Y study the quantized filter’s stability. Pulse rate in the ACB02 block. Sleep mode calculation I also tried using the filter’s coefficients reduces the average power consumption by plugging in numbers (1, 2, 3, ...) for to 1 mA. The sleepWWW.GiURUMELE.Hi2.RO interval is 1 s. Every Output to LCD n in 2–n (0.5, 0.25, 0.125, ...). This second, the software reads the state of method enabled me to replace the Threshold the comparator bus via the CMO_CR0 adaptation operations of division and multiplica- register and enables a pulse rate calcu- tion by shifting right and left (see Noise lation when (CMP_CR0 & 0x20) = 0x20. detection Listings 1 and 2). The digital filters Otherwise, the software switches off work faster if you don’t use division all the analog blocks (ARF_CR &= 0xF8 Figure 5—The real-time, pulse-calculating algorithm and multiplication. and ABF_CR0 &= 0xE3), puts P0.4 into performs hardware initialization and dynamically recon- Shifting 16 bits to the right performs Strong Drive mode (corresponding bits of figures the PSoC on the fly (i.e., it switches on/off all the division by 65,536. You may down- analog blocks and changes the port functions). It also PRT0DM0, PRT0DM1 and PRT0DM2 load the amplitude-frequency charac- reads and digitally filters the ADC data, sends the ADC registers), and sets logical 1 to port P0.4. data to PC, automatically adapts the threshold, calcu- teristics of the developed digital filters The pulsometer then reenters Sleep mode. lates the pulse rate, and displays it on the LCD. from the Circuit Cellar FTP site.

32 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com The filtered and differentiated EKG value stops when it reaches a certain ence your heart rate, including stress, signal is used for QRS complex detec- low value (E0), which equals the average food, excitement, ambient temperature, tion. The QRS complex is detected noise level. E0 is determined experimen- and previous physical exertion. You can when the absolute magnitude of the dif- tally for a certain level of noise. The ask your doctor about resting and active ferentiated EKG signal is higher than the decreasing rate is directly proportional healthy heart rate ranges. threshold value. The LED also flashes at to E – E0. The decreasing threshold this point and the current RR interval is value is needed to guarantee the small POSSIBLE UPGRADES calculated: RR = g_time – g_time_old. amplitudes of QRS complex detection. You can use my low-cost EKG pul- g_time is a value of the time counter, If Eis greater than the threshold someter in medical, athletic, and which is incremented with every cycle value during the interval between t1 home appliance applications. I’ve been of ADC conversion. g_time_old is the (200 ms) and t2 (240 ms) following the thinking about upgrading the system. value of time counter at the moment of last QRS complex detection, then a noise I’d like the system to be able to gen- the previous QRS complex detection. is detected and you must increase the erate a beep via the piezoelectric After calculating 11 QRS complexes, threshold value and count the current speaker when it detects a beat. I’d also the array of 11 RR intervals passes RR interval again. The algorithm will like to use a flash memory card for log- through the median filter, which gives then wait for the next QRS complex ging pulse rates. Finally, I’d like to use the closest to the integrated duration detection, when the differentiated EKG Bluetooth technology to send the EKG value of the RR interval. Median filtering value E is greater than the threshold and measured pulse rate data to a PC. is a simple yet effective noise-removal fil- value. I tested my pulsometer against a tering process. It’s good for removing shot professional one. The tests showed the noise, which consists of strong spike-like TIPS error to be less than ±2 bpm. So, you isolated values. In a one-dimensional You can use pennies for your pulsome- don’t need a costly external high-CMRR case, a median filter involves sliding a ter’s electrodes. If you design a commer- instrumentation amplifier. Nor do you window of an odd number of elements cial pulsometer, however, you must use need a fast digital signal processor. I along the signal and replacing the center a material with a stable polarization sample by the median of the samples in voltage. The most stable electrode mate- Serhiy Matviyenko earned a diploma the window. The RR interval duration rial is chlorized silver (Ag-AgCl). Use in physical and biomedical electron- then passes via a second-order averaging large electrodes because the polariza- ics in 2003 from the National filter and is scaled to units of beats per tion voltage depends on the current University (“Lvivska Polytechnika”) minute and displayed on the LCD. density. If you improperly connect the in Ukraine. He now works there as a To reduce the detection of false beats, electrodes to skin, the heart rate reading research engineer. Serhiy holds three after every detected QRS complex, the will be incorrect. Ukrainian patents (and has two pend- algorithm performs the automatic Keep in mind that the polarization ing) for electronic systems. You may threshold level adjustment and noise voltage is extremely sensitive to move- reach him at [email protected]. detection in 240 ms. The maximum ment artifacts. For the best accuracy, absolute value is found in an interval of you and your patient must remain still. PROJECT FILES t1 = 200 ms after the detected complex. Always operate the pulsometer with To download the code, go to ftp://ftp. The threshold value is updated with batteries. Never use a mains adapter circuitcellar.com/pub/Circuit_Cellar/ 0.75 × maxE, where E is the differen- because the power line is a source of 2006/186. tiated EKG (see Figure 2a). noise. Plus, you don’t want to run the The threshold value decreases with a risk of electrocution. RESOURCES slow rate. The decreasing threshold There are numerous factors that influ- AAMI, “Safe Current Limits for Electromedical Apparatus,” ANSI/AAMI ES1-1993, 1993. Listing 1—Check out the second-order, low-pass IIR filter. F. Eady, “PSoC 101,” Circuit Cellar diff1 = yn_1<<16; 169, August 2004. y=((((x + xn_2)<<16)>>4)+((xn_1<<16)>>3)+(diff1>>1)+(diff1>>2)-WWW.GiURUMELE.Hi2.RO (((yn_2)<<16)>>2))>>16; xn_2 = xn_1; SOURCE xn_1 = x; yn_2 = yn_1; CY8C27443 Microcontroller yn_1=y; Cypress Semiconductor Corp. www.cypress.com Listing 2—Here you see the first-order, high-pass IIR filter. Disclaimer: This article is for edu- y=((((x-x_hpf1_1)<<16)>>1)+(y_hpf1_1<<10))>>16; cational purposes only. The project x_hpf1_1 = x; discussed is not an approved med- y_hpf1_1 = y; ical device.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 33 WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by Monte Dalrymple Third-Generation Rabbit A Look at the Rabbit 4000 You’ve used Rabbit 2000 and 3000 . Now it’s time to get familiar with the Rabbit 4000, the newest addition to the Rabbit line of low-EMI microprocessors. According to Monte, the new design includes several exciting features that will enable you to take your communications, embedded control, and Ethernet connectivity applications to the next level.

The gestation period for new Rabbit libraries written by Rabbit engineers, the new 32-bit accumulator. Semiconductor microprocessors seems and this experience provided many of The four pointer (P) registers were orig- to be about three years. I know this the requirements for this new design. inally requested by Rabbit to be 24 bits because I’ve designed all three genera- Probably the biggest drawback to the wide. They were intended to hold address tions of Rabbit microprocessors. Now existing CPU register architecture is the pointers. Given that we had a 32-bit data it’s time to introduce you to the third- relatively limited support for 16-bit path, it made more sense to expand these generation device: the Rabbit 4000. quantities and lack of support for 32-bit registers to 32 bits and allow them to The first two generations have been quantities. However, to maintain back- be used for data as well as addresses. covered in past issues of Circuit Cellar, wards compatibility, it was important When used for data, these registers so I won’t spend much time describing to retain all of the existing registers are general-purpose 32-bit registers. But the existing feature sets. Instead, I’ll without changing their widths. The when an instruction calls for one of concentrate on the new expanded fea- Rabbit 4000’s register architecture these registers to be used as an address, tures. I’ll also describe some of the addresses these issues (see Figure 1). the contents of the register receive spe- thinking that went into the new design. Readers familiar with the Z80 will cial treatment. This special treatment is Rabbit has accumulated a lot of user recognize most of the registers, but required because the Rabbit 4000 (like feedback from the first two generations, we’ve added a new 16-bit register (JK) the previous generations) has two types and I think it’s been put to good use. as well as four new 32-bit registers of addresses: logical and physical. One thing that has helped in this (PW, PX, PY, and PZ). All of these new Logical addresses are 16 bits wide. The regard has been the advance of fabrica- registers have alternate versions. memory management unit (MMU) auto- tion technology. We had a fixed transis- The existing HL register remains matically translates logical addresses into tor budget when designing the Rabbit the default accumulator for 16-bit cal- 24-bit physical addresses. Logical address- 2000. This led to a number of compro- culations. When combined with the JK es save code space and execution time at mises in functionality. Transistor budget register and new 32-bit instructions, the expense of having a limited range of issues affected the Rabbit 3000 in a the resulting JKHL register becomes memory available at any given time. similar fashion. Physical addresses in the Rabbit Things were different this time 4000 are 24 bits wide, but they around. The expanded transistor Alternate registers F maintain backwards compatibility budget for the Rabbit 4000 provided A with the 20-bit addresses of the WWW.GiURUMELE.Hi2.ROB C room for a plethora of new features. earlier generations. Previous Main registers D E It also enabled us to address the JK Rabbit devices provided only two compromises left over from the H L rather cumbersome instructions previous generations. IX for accessing physical memory. IY This was the initial reason for EXPANDING THE CPU adding the pointer registers. PW During the six years since the PX The special treatment of address- introduction of the Rabbit 2000, a PY es in the pointer registers enables PZ great deal of code has been written them to be used to hold either logi- for Rabbit microprocessors. Much Figure 1—The Rabbit 4000 register architecture more than doubles the cal or physical addresses. If the of the code is in the form of resources available in previous generations of Rabbit microprocessors. upper word of a pointer register is

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 35 all ones, then the lower word of the reg- However, covering all of the per- Select Mnemonic Function ister is used as a logical address. Any mutations of instructions loading 0 0 R3K_MODE Rabbit 3000 instruction set other bit combination in the upper word to or from the new pointer regis- 0 1 Mode_01 Enable 6D prefix page and the entire register is treated as a ters required a new first byte for a 1 0 Mode_10 Enable 6D and 7F prefix pages physical address. number of 2-byte instructions. 1 1 R4K_MODE Enable full Rabbit 4000 mapping This logical/physical decision is auto- And there was still the issue of Table 1—Three new operating modes enable different por- matically handled by the logic, enabling the new 1-byte opcodes. tions of the new instruction set. or disabling the MMU for the address as In the end, I used two separate appropriate. In addition, when loading a bits in the on-chip I/O space to con- encryption and decryption. One option pointer register from one of the regular trol the opcode mapping. These 2 bits was to provide a full AES encrypt/decrypt registers, a 32-bit load writes all 32 bits provided four options (see Table 1). logic block in the design. However, this of the pointer register while a 16-bit The default case is compatible with would have led to export control issues load automatically sets the upper word the existing opcode map, with the addi- that I wanted to avoid. of the pointer register to all ones. tion of most of the new instructions in Instead, I went through the AES stan- Sometimes it’s desirable to find out the available 2-byte opcode space. In this dard looking for operations that were which physical address corresponds to a mode, any existing code will run without hard to do with the existing instruction given logical address. Figuring this out is modification, but not all of the new set. One thing that AES encryption does normally somewhat time-consuming instructions are available. This was a lot of is substituting 1 byte for another, because it involves duplicating the opera- important for me because I didn’t want to using a mapping operation called “sub- tion of the MMU to generate the physical have to go through all of my test patterns stitution box” (SBOX). The inverse address. The Rabbit 4000 adds two new from the previous generations to account operation (IBOX) is used for decryption. instructions to perform this conversion for instructions with different opcodes. The Rabbit 4000’s two AES-specific automatically. Two separate instructions Mode 1 is a first step to providing the instructions (SBOX and IBOX) take the are required because the MMU can trans- full Rabbit 4000 instruction set. It uses byte in the accumulator A and replace late code differently from data. To imple- an existing instruction that’s effectively it with the appropriate SBOX or IBOX ment this feature, the CPU performs a an NOP (it’s actually Load L with itself) byte value. To speed up moving data into dummy read from the logical address, as the first opcode byte. This mode and out of the accumulator for this oper- while at the same time capturing the enables all of those instructions for ation, there are byte rotate operations resulting physical address and loading it loading to or from the pointer registers. between any of the pointer registers and back into the specified pointer register. Mode 2 enables the full Rabbit 4000 the accumulator. With these simple addi- But this conversion is only one way. instruction set, using the same tech- tions, plus the new 32-bit math instruc- A physical address can correspond to nique as Mode 1, except that all of the tions that had already been added, Rabbit more than one logical address or to a instructions that Rabbit wanted to be was able to speed up AES-128 encryption logical address that isn’t available 1-byte opcodes are actually 2 bytes. This and decryption by a factor of 10 over given the current MMU programming. mode provides full Rabbit 4000 func- the Rabbit 3000. If the pointer register already contains tionality without breaking any existing Byte substitution is an operation a physical address, it’s left unchanged. code (except for the two virtual NOPs). common to many encryption algorithms Mode 3 is the full Rabbit 4000 besides AES, but the exact substitution NEW INSTRUCTION SET implementation, where a number of the table varies. To handle this possibility, All of these new registers require new new instructions use 1-byte opcodes for I also added an instruction that uses instructions. In fact, the number of performance and code density reasons. A, added to an index register, to access opcodes increased from 250 in the exist- The 1-byte instructions that were lost a byte table in memory. The contents ing Rabbit 3000 opcode map all the way are mapped to 2-byte versions. of this byte table are loaded back into to 464 in this design. Rabbit specified I expect that most programmers will A in what is effectively a programmable that a number of these new instructions go straight from Mode 0 to Mode 3, SBOX or IBOX operation. needed to have 1-byte opcodes. This and this is what the compiler will sup- required some WWW.GiURUMELE.Hi2.ROthought because all of port. But having the two intermediate SPEEDING UP THE BUS the 1-byte opcodes were already used modes may save someone who has The maximum clock speed has in the existing opcode map. written optimized assembly code. increased with each new Rabbit and has A second requirement was that the With 214 new instructions, I don’t gotten to the point where it’s starting Rabbit 4000 had to default to the existing have the space here to cover all of to be expensive to find memory that opcode map. This was to ensure code them. Instead, I’ll talk about a couple can be used with zero wait states. One compatibility with all of the existing soft- of specialized new instructions. obvious solution to this problem was ware until new libraries could be written. to increase the width of the data bus. There are enough 2-byte opcodes SPECIALIZED INSTRUCTIONS A 16-bit bus had to be an option and available in the existing map to take About halfway through the design, not a requirement, though, because care of the majority of the new instruc- Rabbit asked what I could do to speed up the majority of Rabbit 4000 designs tions, so this was my first priority. the Advanced Encryption Standard (AES) will still use 8-bit memories for cost

36 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com reasons. This is what makes life inter- The code first builds 0x02, which is operation is coming up, it notifies the esting for me as a designer. the data value that enables 16-bit opera- prefetch not to start any new reads that The 16-bit bus uses one of the parallel tion and stores it in B. Then, the I/O might slow down the write. In a simi- ports for the extra 8 bits of data to keep address of 0x1D is built in L. I then lar fashion, when a branch instruction the package pin count low. Supporting take advantage of the fact that multiple is recognized, the prefetch is notified to byte writes on a 16-bit bus often leads I/O prefixes (the IOI) are interpreted as stop when the branch address has been to a bit of external glue logic. I wanted one to do the actual I/O write. The first completely fetched into the queue. All to avoid this, so a separate port pin write is to an I/O register, but the sec- of this leads to a measurable perform- can be programmed to provide the ond write is going to go to memory. But ance gain with a 16-bit bus. necessary byte-lane control signal for this is fine because memory writes are The final performance option is sup- a glueless memory interface. disabled after reset. The two NOPs port for 16-byte Page mode. Page mode Rabbit wanted the option for 16-bit allow time for the actual switch, and memories are capable of supplying data memories on two of the device’s three away we go with a 16-bit bus! in the same page much faster than for chip selects, including the chip select Just providing a 16-bit bus doesn’t ordinary random accesses. However, Page used as the default after reset. Because improve performance unless the mode memory requires that both the the default is an 8-bit bus, this means processor can actually use all 16 bits chip select and the output enable remain that the first few bytes of code in a at once. Although major changes have active with only the address changing to 16-bit memory connected to this chip been made to the register architecture take advantage of the faster access time. select must be capable of switching and instruction set, the CPU itself The Rabbit 4000 supports this Page mode the processor to 16-bit mode. still takes in instructions 1 byte at a operation on either an 8-bit bus or a An additional complication was that time. So along with the 16-bit bus 16-bit bus. It includes separate wait the code must execute identically comes a 3-byte prefetch queue. state values for initial and subsequent whether it’s in 16-bit mode or 8-bit The prefetch mechanism is coupled memory reads. Separate control bits are mode (after a reset). This limited me to with the instruction execution, available for each chip select. using only pairs of 1-byte instructions. although wait states when prefetching This restriction comes about because in don’t slow down execution. Instead, DEBUGGING SUPPORT 8-bit mode the CPU will actually be the prefetch runs semi-autonomously, The last major additions to the CPU fetching the same instruction twice attempting to always keep at least are the breakpoints. Seven are provid- on an 8-bit bus until the switch to 1 byte in the prefetch queue. But when ed in the Rabbit 4000. 16-bit mode occurs (see Listing 1). the execution unit knows that a write Each breakpoint can be triggered on a physical address match for reads, Listing 1—The code executes identically from either a 16-bit bus or an 8-bit bus connected to a 16-bit memory writes, or execution in either System device. It enables the 16-bit bus. or User mode. Any bits of the address can be masked off and excluded from ORG 0000h the match. You can even force a XOR A ; a <= 00000000 XOR A breakpoint to be pending, which LD H, A ; h <= 00000000 makes it act like a single-step trap. LD H, A SCF NEW FEATURES SCF RLA ; a <= 00000001 A feature that transistor budgets RLA ; a <= 00000010 wouldn’t allow in previous genera- LD B, A ; b <= 00000010 tions was the ability to read and write LD B, A the peripheral control registers. These SCF SCF registers were mostly write-only, ADC A, B ; a <= 00000101 which made keeping track of the reg- ADC A, B ; a <= 00000111 ister contents cumbersome for the ADD A, A ; a <= 00001110 software because it meant keeping a ADD A, AWWW.GiURUMELE.Hi2.RO ; a <= 00011100 SCF shadow register in memory. SCF The first solution Rabbit proposed for ADC A, H ; a <= 00011101 this problem was a dedicated, complex ADC A, H instruction that automatically updated LD L, A ; l <= 00011101 LD L, A both the control register and the shadow IOI ; two IOIs same as one register. Although this instruction still IOI exists in the Rabbit 4000, we ultimately LD (HL), B ; MACR <= 00000010 decided to make nearly all of the periph- LD (HL), B ; dummy memory write (no /WE) NOP ; required delay to start eral control registers read/write. NOP ; up the 16-bit bus The other major compromises that we removed were in the serial ports. All

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 37 six serial ports now fully support parity 2000). To compensate for this reduction, pendent of the handshake signal. generation and checking. Odd, even, each port pin has up to four alternate The last change involves the input mark, and space parity are all supported. output functions and two or more alter- capture peripheral. We added the option In addition, each serial port now has its nate input functions. The end result is to count external events instead of own dedicated 15-bit divider to generate very flexible. It enables nearly any com- merely latching the state of a counter baud rates. Of course, for backwards bination of peripheral connections. when the external event occurs. compatibility, the serial ports use the One unique feature of the Rabbit 3000 existing timer connections as the default. is the optional I/O bus, which keeps NEW PERIPHERALS Engineering is all about compromise, external I/O devices from loading down In addition to the changes to existing and even though we didn’t have to the memory bus. Rabbit has used this peripherals, we’ve added four new compromise because of the transistor option to connect to Wi-Fi cards, flash ones. Two of them are pretty simple, budget, a packaging requirement led to memory disks, and so on. However, one but the last two actually rival the a different kind of trade-off. These days, thing that many of these devices require CPU in complexity. high-pin-count packages that are a rea- is either slow access or long recovery Calling the first new peripheral a sonable size are all ball grid array (BGA). times after a command is issued. These peripheral is a little misleading because But BGA packages require different tool- requirements had to be handled in soft- it’s really just a small piece of RAM. ing for a board manufacturer, and most ware because there was no mechanism Besides being located in the internal I/O Rabbit customers don’t want to deal for externally generated wait states. space, this 32-byte RAM has two other with this requirement. So, the Rabbit To deal with these issues, we added unique features. First, this memory is 4000 had to be designed for the same an optional I/O handshake signal that powered from the same power plane as package as the Rabbit 3000. This wouldn’t holds off the completion of the I/O the real-time clock and is normally sup- have been a problem if we could use the transaction until the handshake is plied by a battery. This memory is useful same power and ground connections and removed. To prevent this handshake for holding data that isn’t appropriate if we weren’t adding new peripherals from halting the CPU forever, there’s to write to flash memory, such as an that required dedicated pins. also a timer that’s triggered at the encryption key. Second, because the data The end result was the loss of two start of an I/O transaction. If this pro- in this memory may be sensitive, parallel ports relative to the Rabbit 3000 grammable time limit is exceeded, the whenever any attempt is made to enter (or the same port count as the Rabbit I/O transaction is terminated inde- Program or Debug mode, the memory is

WWW.GiURUMELE.Hi2.RO

38 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com automatically cleared. Connecting one of mitter and a 32-byte FIFO in the Figure 2 (p. 40) shows the structure the programming pins to a tamper-detect receiver. Coupled with the powerful of a buffer descriptor. Each descriptor mechanism on an enclosure will provide new DMA controller, the network is either 12 or 16 bytes in length. All security for any data held in this RAM. port only needs one interrupt per DMA addresses are physical addresses. The second new peripheral is timer received or transmitted frame. Four byes are reserved for the source C, which provides functionality that The new DMA controller contains address and destination address, even was not available in the existing timer eight independent channels for effi- though only 3 bytes are used. This resources. Although timer A provides ciently moving data between any com- makes it easier for the CPU to build the a number of 8-bit timers and timer B is bination of memory, internal I/O, or descriptor using 32-bit operations. 10 bits, timer C is up to 16 bits with a external I/O. Rather than requiring Two bits in the control byte identify programmable count limit. programming by the CPU, these DMA the source address as an incrementing Along with the programmable count channels use buffer descriptors in memory address, a decrementing limit are four match registers, two each memory to control DMA operation. memory address, a fixed external I/O to set and reset a status bit or generate an interrupt. These features enable vari- able frequency pulse-width or pulse-posi- tion modulation signals to be easily gen- erated for use with things like servos. More and more embedded systems require network connectivity, so the Rabbit 4000 includes a full-featured 10BaseT controller. This network port provides all of the features necessary to communicate efficiently over a network. The network port, which operates either half-duplex or full-duplex, contains a complete auto-negotiation function to automatically select between these two modes. Of course, this auto-nego- tiation can be disabled to force a par- ticular mode. The network port doesn’t require an external physical interface (PHY), but instead needs only a few inexpensive external components to connect to the cable. This was one of the primary design goals for the device. In addition to the usual error counters, network timers, and so on, we included some hardware to make handling the higher-level protocols easier. For exam- ple, TCP/IP makes use of a checksum covering the entire message. The net- work port automatically calculates this checksum to reduce software overhead. There are several reasons why we went with justWWW.GiURUMELE.Hi2.RO a 10-Mbps network port rather than a 10/100 port. Besides several implementation issues, which include requiring an external PHY and on-chip buffers, Rabbit’s experience in providing network-enabled controllers indicated that 10BaseT was sufficient for this generation. The bus bandwidth required for 10 Mbps is low enough that the design doesn’t need on-chip buffers. Instead, there is a 16-byte FIFO in the trans-

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 39 address, or a fixed internal I/O address. can control the data transfers. This Lowest memory address: Frame status (optional) Another 2 bits perform the same func- works well with those peripherals that Channel control tion for the destination address. have a fixed address for data (e.g., the Buffer length [7:0] To increase performance, the DMA serial or network ports), but would be Buffer length [15:8] doesn’t fetch the unused bytes in the a problem with the PWM channels or Source address [7:0] descriptor. If either address is tagged as timer C because of the multiple I/O Source address [15:8] I/O only, the 2 least-significant bytes addresses required to program them. Source address [23:16] are fetched. This is because I/O addresses To address this issue, both of these Not used are always 16 bits in the Rabbit 4000. peripherals have a new block transfer The Link Address field is optional Destination address [7:0] address. Writing repeatedly to this and enabled by a bit in the control byte. Destination address [15:8] address automatically steps through all of If no link address is present, the next Destination address [23:16] the necessary PWM or Timer C control descriptor is contiguous with this one. Not used registers to allow for DMA control of If the link address is present, it points Link address [7:0] these peripherals. to the starting address of the next Link address [15:8] Receive messages from either the serial descriptor. This creates a linked list of Link address [23:16] port or network port are unlikely to fin- buffer descriptors. Highest memory address: Not used ish on a buffer boundary, so the DMA The Buffer Length field is self- automatically closes a buffer after trans- Figure 2—The DMA uses buffer descriptors in memory explanatory. It allows for buffers of up to control its operation. One command from the CPU ferring the last byte of a message. The to 64 KB in length. tells the DMA to begin operation. DMA also automatically writes a status One of the remaining bits in the con- byte that’s read from the serial or net- trol byte tags the descriptor as the final automatic that an interrupt on buffer work port that contains the frame status. descriptor. The DMA stops after this completion isn’t necessary. This status byte is written to the status buffer is complete and must be restarted Any internal peripheral can be used byte in the first buffer descriptor. At the by CPU command. with the DMA, and the DMA recog- same time, the DMA stores the number Another bit enables an interrupt at nizes certain internal I/O addresses and of completed buffers, plus the byte count the completion of this buffer. In most automatically connects to the relevant of the current buffer, in internal registers. cases, the operation of the DMA is so request signals so that the peripheral All of this information enables the CPU

WWW.GiURUMELE.Hi2.RO

40 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com to quickly determine the status and necessary to handle this protocol. Monte Dalrymple has been designing length of a received message. The final DMA feature that I’ll men- integrated circuits for 27 years. He is Transmit messages to either the serial tion is the timed transfer option. The the designer of all three generations of or network port also require some special DMA contains an internal timer that Rabbit microprocessors. You may reach handling. This is because the last byte generates a periodic transfer request. him at [email protected]. of a message must be identified so This request can be used to write to a that CRC can be appended. parallel port to generate periodic signals RESOURCES The last bit in the control byte of the without any CPU overhead. It can also AES Encryption standard, http://csrc. buffer descriptor tags this descriptor as be used to repetitively read or write an nist.gov/publications/fips/fips197/ the last one for the current message. The external ADC or DAC. fips-197.pdf. DMA then writes the last byte of this buffer to a special serial or network port WORTH THE WAIT T. Cantrell, “Watch Me Pull a Rabbit address. This is what tags the byte as the The Rabbit 4000 has been a long time Out of My Hat,” Circuit Cellar 147, last byte in a transmit message. in the making, but it has been well October 2002. One DMA feature that isn’t controlled worth the wait. We’ve enhanced the M. Dalrymple, “Rolling Your Own through the buffer descriptors is the pat- CPU and peripherals over previous gen- ,” Parts 1 and 2, Circuit tern match capability. This feature erations, and added powerful new Cellar 111–112, October–November, enables the DMA to terminate a buffer peripheral functions. The enhancements 1999. after the transfer of a particular byte have come directly from both customer value. This byte value is programmable feedback and Rabbit’s experience in writ- F. Eady, “Rabbit Season,” Parts 1–5, and can also have any number of bits ing software. I can’t wait to get my Circuit Cellar 122–126, September masked off from the comparison. hands on one instead of watching it 2000–January 2001. This feature is particularly useful work in the simulator all day. I with point-to-point protocol (PPP) links. SOURCE PPP operates over ordinary serial links Author’s note: Thanks to everyone at and uses a special byte as a message Rabbit Semiconductor, especially Rabbit 4000 delimiter. Placing messages in separate Norm Rogers, Pedram Abolghasem, Rabbit Semiconductor buffers greatly simplifies the software Lynn Wood, and Steve Hardy. www.rabbitsemiconductor.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 41 WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by David Gamble & Andrew Smallridge Watchdog Supervisory System

It’s now possible to increase the availability of a remote data system without hooking into the system’s internals. David and Andrew’s PIC18F452 microcontroller-based watchdog supervisor system does the trick.

As part of an ongoing environmental sensor input unit performs data acquisi- system to automatically recover from research project in remote Western tion and conditioning. It communicates system crashes. However, developing a Australia, two self-contained EdiSol eddy to the laptop via the Gill Power and replacement data processing application covariance systems are used to measure Communications controller. The sys- and changing from a laptop to a rugged the surface fluxes of heat, carbon dioxide, tem’s power and communications con- computing platform would have been too and water vapor. The systems are config- troller is a protocol translator that con- expensive, risky, and time-consuming. ured identically, each comprising a three- verts between RS-422 (the sensor input We couldn’t modify the EdiSol applica- axis sonic anemometer subsystem, an unit) and RS-232 (the laptop) ports. Data tion source code. What were we to do? infrared gas analyzer subsystem, a streams continuously from the sensor Fortunately, we came up with an Windows XP-based laptop, and EdiSol input unit to the laptop, where the EdiSol affordable, straightforward solution. We data processing and logging software. application processes and logs the data. designed a watchdog supervisory system Basically, an EdiSol eddy covariance Unfortunately, the EdiSol systems to run in parallel with the EdiSol system, system preprocesses and logs large vol- proved unreliable in the field for multi- increasing the system availability (i.e., up umes of data on a hard disk for subse- ple reasons. They frequently crashed time) and providing visiblity to the opera- quent downstream processing. A DC/DC after a few hours or days of operation. tor (see Figure 1). The watchdog supervi- converter provides a clean 15-V power Each system cost tens of thousands of sory system monitors the EdiSol system supply to the EdiSol system from a dollars, so it was imperative that we find and automatically restarts it after a fail- battery-backed solar power supply. The a solution. We considered redesigning the ure. To minimize development costs, we used a subsystem originally developed

EdiSol eddy convariance system for a Bowen ratio data acquisition sys- USBRB-232 Watchdog supervisor system tem (A. Smallridge, “Intelligent Sensor Laptop Adapter PC Supervisor (PCS) Head,” Circuit Cellar 171, October 2004). Heartbeat Communication process EdiSol supervisor (CPS) SUPERVISORY SYSTEM Gill R50 Laptop on/off Laptop on/off output sonic anemometer Power in Our watchdog supervisory system RS-232 Sensor power control comprises four essential components. A PC supervisor (PCS) application runs Gill power and communications controller on the laptop. A CDMA wireless RS-232 CDMA Wireless modem provides short message service Power in modem MM-5100 RS-422 and power (SMS) alarms and remote dial-up access. A communications processor supervi- Gill sensor input unit sory (CPS) system serves as an external WWW.GiURUMELE.Hi2.RORS-422 and power Gas analyzer signal in watchdog timer and interfaces to the Licor gas analyzer control unit CDMA modem. Finally, a sensor power Gas analyzer signal in Power in control relay module power cycles the Sensor power control relay system’s sensors. 24- to 15-V DC/DC converter ▲ The supervisory system implements LI-7500 Power out Gas analyzer multiple levels of supervision. At the

To 24-V solar power system highest level, the PCS application automatically starts, configures, and begins monitoring the EdiSol application. Figure 1—The EdiSol system incorporates our watchdog supervisory system. The CPS system works in conjunc- tion with the PCS application on the laptop to deliver the external watchdog timer service for the EdiSol application. In the event of an anomaly, the PC The sensor power control power cycles the system’s sensors to recover from asynchronous communication failures. supervisory system restarts the appli-

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 43 cation and, when appropriate, reboots (e.g., laptop reboot). The CPS system, WATCHDOG CIRCUIT the operating system and power cycles which maintains an event log that you The CPS system and the associated the sensors via the CPS system. can access remotely, incorporates a boot- sensor power control relay board are The PCS application, which runs in loader that facilitates the downloading of shown in Figure 2. The heart of the sys- parallel with the EdiSol application on new software via the modem. tem is a PIC18F452 microcontroller run- the laptop, is the first line of defense. At the highest level, the CPS system ning at 40 MHz derived from a 10-MHz With the exception of power cycling has several responsibilities. For instance, crystal and the internal 4× PLL multipli- the sensors, it’s intended to run inde- it power cycles the laptop after an anom- er. The PIC18F452 features an internal pendently of the CPS system to keep aly. In addition to power cycling the sen- hardware UART for communicating the EdiSol system operational in the sor subsystem after a command from the with the PCS application on the laptop event of application-related failures. PCS application, it logs CPS status infor- over an RS-232 interface at 115 kbps. The PCS application partially solves mation. The CPS system also monitors Control messages and keep-alives are the problem of not being able to modify the PCS application’s active status, transmitted over this interface between the EdiSol application to support a super- exchanges status information with the the PCS and the CPS system. A second visory function. The PCS application PCS application, and generates alarms. UART, implemented in software, inter- monitors the EdiSol application’s external Finally, in addition to providing the user faces the CPS system to the MM5100 behavior to ensure it conforms to its nor- interface for remote interrogation and CDMA wireless modem. This serial port mal operational profile. After detecting an control of the supervisory system, the includes hardware handshaking for anomaly, or as the result of control mes- CPS system stores SMS calling numbers modem carrier detection and enabling sages from the external CPS system, the and call number priorities. the CPS system to release the circuit. PCS application attempts to shut down The third line of defense is the Configuration changes to the CPS sys- and restart the EdiSol data-logging appli- watchdog timer implemented in the tem and access to the CPS and PCS cation. If necessary, it then reboots the Microchip Technology PIC18F452 log files are possible via this interface. operating system. Having the ability to microcontroller used in the communi- A USB type B port is implemented shut down the application and operating cations processor. In the event that using a Future Technology Devices system is a key feature that minimizes the CPS software fails to periodically International USB controller. You have the possibility of file system corruption. reset the watchdog timer, the watchdog the option of using the USB port to At start-up, Windows automatically timer resets the CPS microcontroller. locally monitor the operation of the launches the PCS application. The appli- The CPS system then generates an SMS CPS system via a HyperTeminal session cation then launches the EdiSol applica- status message at power-up. from your laptop running the EdiSol tion and initiates data logging. The PCS The fourth and last line of defense is application. Configuration changes are application maintains a status log file Maxom Electronics Australia’s MM- also possible via the USB interface. that can be interrogated remotely. 5100 CDMA wireless modem, which We modified the laptop and brought The CPS system provides the second is used to send SMS messages and sup- the power on and off contacts to a con- level of supervision. The CPS hardware port remote dial-up access to the nector. The connector, which connects includes the four communications inter- supervisory system. The CPS system to the laptop’s power control relay on faces that are required for the supervision. interfaces between the PCS applica- the CPS board, enables the CPS software An RS-232 DCE port, which connects to tion and the CDMA modem. Using to control the laptop’s power cycling. the laptop’s USB port via a USB-to-RS-232 the dial-up interface, you can remotely The PIC18F452 on the CPS system con- adapter, is used for exchanging status download status logs from the CPS trols power to the acoustic anemometer information with the PCS application. An system and PCS application. You can system and the gas analyzer system via RS-232 DTE port is used for connection configure the CPS system and control the sensor power control relay board. to the CDMA wireless modem. A USB the supervisory system to gracefully or type B port is used for local system moni- forcefully restart the EdiSol applica- DEVELOPMENT PROCESS toring. Voltage-free changeover contacts tion and the laptop’s operating system. To minimize the development time, are used for power-cycling the laptop. You can also power cycle the laptop we split the development tasks. David The CPS systemWWW.GiURUMELE.Hi2.RO functions as an and sensors as required. was responsible for developing the external watchdog timer for the EdiSol The CPS user interface is accessed PCS application. Andrew wrote the system. It interfaces to the PCS appli- via the CDMA modem or via the USB functional specification and handled cation via a messaging interface over an console port. User interface com- the CPS software development and RS-232 serial port. When the PCS appli- mands enable you to send CPS and hardware integration. cation fails to send periodic system status PCS log files, restart the EdiSol appli- As ambiguities in the specification messages to the CPS system, the latter cation, and reboot the laptop’s operat- were identified, they were removed and restarts the laptop by initiating a power ing system. The commands also the specification was updated. After the cycle via an on-board relay on the CPS enable you to reset the CPS system, initial functional specification was writ- system board. When appropriate, the CPS clear the CPS and PCS logs, and con- ten, we developed useful tools to enable system also initiates an SMS alarm mes- figure the SMS numbers and calling PCs to be used to emulate the CPS and sage indicating a significant anomaly priorities. PCS systems. The PCS application and

44 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

Figure 2—The CPS system is built around a PIC18F452 microcontroller, which has a RISC CPU core featuring 10 MIPS, 32 KB of programmable flash memory, and 1,536 bytes of RAM. The internal peripherals for the CPS function include the watchdog timer, timers, and UART.

CPS emulators were connected back-to- We originally estimated that we We used the communications proces- back via RS-232 interfaces and the could reuse 50% of the original com- sor PCB as the target platform for the behavior of the system was modeled. munication processor code base for supervisor because it was a proven plat- When we were happy with the emula- developing the supervisory function. form with sufficient interfaces for the tors, we used the CPS emulator to devel- This turned out to be wishful think- CPS application. The only real short- op the PCS application and the PCS ing. We ended up retaining about 15% coming was that it lacked a real-time emulator to develop the CPS software. of the original code. clock. This was addressed by having the

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 45 PCS send date and time information cation. Microsoft XP Pro includes two function, which meant we didn’t have with every message. The CPS system command line applications for checking to use tasklist to check if the EdiSol extracted the date and time information the status (tasklist) and killing the application was up and running. The best and used it as the basis for logging and application (taskkill). Our initial approach is to just search for what is reporting date and time information. attempts to use tasklist were unsuc- required and weed out the results. There The CPS software uses a combination cessful. Testing showed that the EdiSol is an old saying: “You get what you pay of state machine and timer-based logic. application didn’t always function prop- for.” But the sheer number of hits for any The state machine logic and associated erly. It did, however, respond well to particular query usually means you can state machine timer control temporal probes with the tasklist function. distill the essence of the solution with- events. For example, when power cycling Alternative methods were required. out relying too heavily on any one. Of the laptop, the state machine and associ- After some thought, we decided that course, there is no substitute for testing. ated timer determine when the power the easiest way to do this would be to After assembling the components, we button can be released. In such a sce- simply check for desired outcomes. We glued them into some semblance of an nario, a state machine timer timeout is wanted the EdiSol application to run application. The requirement to peri- required to move on to the next step. (tasklist would tell us this) and log. odically poll the CPS system meant After the timer expires, the CPS system Fortunately, the EdiSol application logs building the program around a central transitions the state machine into a lap- significant volumes of data, so it’s rela- timer was the best option. Rather than top booting state. It then loads the state tively easy to check if it’s logging. use a state machine approach, we used machine timer with the maximum There were a few other chores to be a number of timers and a separate allowable boot delay. done. The serial communications were thread for the serial handler. If the state machine timer expires, an handled nicely by the Synaser library, At start-up, a new thread was launched error event has occurred. This means the but we still needed to run external and an instance of the serial port handler laptop, operating system, EdiSol applica- applications and reboot Windows. was created. The thread continuously tion, or PCS application has failed to Rather than reinvent the wheel, we did polled the serial buffer for received char- start. Under normal conditions, an EdiSol some research on the ’Net to see how acters and called a parse command proce- Active message is received to transition other people have handled these tasks. dure to deal with incoming commands. the state machine to the EdiSol Active A wealth of material was available. The parse command procedure checked if state. The logic for the state machine is The EdiSol system required a sequence the command was valid and then execut- located in the ServiceStateMachine() of keystrokes to enable logging. We need- ed the required sequence of actions. The and SrvPCSMessage() functions in the ed to be able to send keystrokes to a tar- receipt of commands and their execution CPS source file (supervisor.c) located on get window, so we returned to the ’Net happened almost completely independ- Circuit Cellar FTP site. and found Jon Stenqvist’s SendKeys com- ently of the monitoring tasks performed ponent for Delphi (www.torry.net). This by the mainline code. The two threads PCS APPLICATION was the first component we tried and it overlapped in the transmission of mes- With a specification for the PCS appli- worked well. As an added bonus, it had a sages to the CPS system and the logging cation and carte blanche for determining GetHandleFromWindowTitle() function. (Everything the PCS application its implementation, the does is logged.) Delphi’s world was our oyster. But synchronize function we faced the same drivers PC Supervisor (PCS) ensured that these here as with the CPS. We threads didn’t interfere Main line wanted a robust solution Main timer Serial thread with each other. Ararat Synaser without having to make a Check EdiSol status Meanwhile, the main- serial library career out of delivering it. Restart? Kill EdiSol line code set up a timer Maintain counters Tx Restart timer We first chose the devel- Report status to drive the PCS applica- enable opment language. This was tion’s main supervisory fairly easy because Andrew function. After a tick of Restart timer had used Delphi for the PC the timer (1-s default), WWW.GiURUMELE.Hi2.ROLauch EdiSol Command parser end of some of his previous Status two checks were per- Disable restart timer •Restart projects. He had also used •Reboot formed. Was the EdiSol •Status Ararat Synapse’s Synaser application logging? Did Send log timer •Ping •Erase log serial library, so it made •Send log the EdiSol application Send line sense to use it here as well. • • • window exist? Update line count The PCS application’s Send log timer enable If everything is fine, a main task is checking if confirmation message is the EdiSol application is sent to the CPS system. Figure 3—PCS logic made simple. Three timers and an asynchronous communications running correctly. If it Obviously, if the applica- thread govern the PCS application. The Main timer periodically checks the EdiSol applica- isn’t, the PCS application tion. The Restart timer control restarts the EdiSol application. The Send Log timer governs tion window isn’t up, it restarts the EdiSol appli- the log file’s rate lines, which are serialized to the modem via the CPS. isn’t logging. But having

46 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com the two checks was necessary to distin- We used another two timers in the was sent. Figure 3 is a graphical repre- guish different fault conditions. In fact, PCS code just because it made things sentation of the timer logic for the PCS. we assumed that if the EdiSol applica- easy. Sure, we could have used a single Naturally, there were a number of tion wasn’t logging, then it was having timer and a state machine approach, but other nuances in the code, but it was problems communicating with the we had practically all the resources of essentially as we have described. The sensors and they needed to be reset. In a laptop at hand. The second timer mainline code monitors the applica- response to either error condition, the ensured that a healthy delay occurred tion. The serial handler thread looks EdiSol application was shut down and between the time the EdiSol application after command execution. restarted to ensure a clean start. shut down and the time it restarted. Another useful feature of the PCS To prevent false alarms, we used two This allowed the sensors to restart. code is the ini file. Delphi has built-in levels of counters to keep track of the After killing the program, restarting it support for ini files, so there’s no excuse number of faults. The first level count- involved enabling the restart timer. On for not using them. Editing the ini file, ed actual faults, one counter each for a cue, the timer expired and the applica- a feature that proved useful for testing missing application window and logging tion came up. Sending keystrokes to and debugging, can alter almost every failure. Only when the fault count start logging was accomplished in the constant in the PCS program. We could exceeded a preset limit was a restart main timer tick routine after the appli- have changed these remotely through cycle initiated. The second level counted cation window was detected. We used the CPS. Perhaps next time. the number of times we attempted to the third timer to send the log file to get the application up and running. the CPS system. The log file was trans- SYSTEM INTEGRATION TESTING The idea was to trap errors not directly mitted line by line on each timer tick. The complete system was integrated associated with the EdiSol application This meant that sending the log file after the CPS and PCS applications that might be solved by rebooting the was as simple as enabling the third were developed and working correctly laptop. After attempting to restart the timer. We also abandoned sending the with their complementary emulator. application several times, the CPS sys- log file by turning off the timer and Problems quickly surfaced when the tem was notified and the laptop reboot- resetting the line count. When the log pedal hit the metal! Sometimes the ed. This second level counter was reset file was transmitted, no other monitor- EdiSol application failed to start log- after sufficient time (presettable) of cor- ing took place. As a result, the main ging correctly. When this happened, rect operation had elapsed. timer tick was disabled until the file the PCS application repeatedly and

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 47 unsuccessfully attempted to restart with the default data rate set at any After the communications problems the system via the EdiSol application value other than 115,200 bps, automatic were addressed, the system worked before restarting Windows. After several negotiation took place. properly. The first indication of this cycles, the CPS system then power It was clear that the automatic data occurred five days into the soak testing. cycled the laptop. This process repeated rate scanning frequently locked up the At 5:22 a.m., the CPS system initiated endlessly. Although we were respond- sensor’s serial communications sub- an SMS alarm to report a system fail- ing as we had planned, we couldn’t system. The only way to recover was ure. The laptop’s hard drive had failed. bring the EdiSol application online. to power cycle the sensor assembly. Although the system couldn’t recover, Subsequent debugging indicated that The likely culprit was the serial com- it provided timely information, which the problem was due to the locking up munications locking up because of decreased the time it took to repair the of the sensor’s serial interface. When framing errors. This was aggravated by system and increased its availability. we raised this issue with the EdiSol the automatic data rate negotiation. system’s regular operator, he said “Oh When the EdiSol application was con- ROBUST SYSTEM yes, I forgot to mention that!” figured for 115,200-bps operation (it was “Good, fast, or cheap. Pick any The EdiSol application communicat- 38,400 bps), the problem went away. two.” This little saying has been used ed with the anemometer sensor input This lends weight to the framing error for years to remind us that we can unit (sensor conditioning and acquisi- hypothesis. Unfortunately, the higher control only two things at any one tion subsystem) via an RS-232/422 pro- data rate then led to the introduction of time. But by being realistic about your tocol translator. The EdiSol application cyclic redundancy check (CRC) errors objectives for a project, you can come attempted to automatically negotiate between the EdiSol application and the in under budget for all three. the data rate from 115,200 bps down to anemometer sensor input unit. Restoring For our project, we focused on our 2,400 bps each time it connected to the the default data rate to 38,400 bps and objectives, reused resources (both hard- sensors. When the connection was suc- adding a relay driver board and software ware and software), and figured out a cessful, the sensor’s data rate was then to the PCS application and CPS system plan that would ensure the best use of set to the value in the EdiSol configura- addressed the serial communications the available personnel. Sounds great, tion file. It’s unclear why it did this problem. This enables the CPS system doesn’t it? Actually, we worked over- instead of using the value in the config- to power cycle the sensors either directly time because the problem evolved into uration file for the first attempt. Thus, or as a result of a PCS message. something more difficult. Even so, by

WWW.GiURUMELE.Hi2.RO

48 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com writing a simple specification, we knew It isn’t particularly elegant, but our RESOURCE where we were heading. Of course, it robust supervisory system delivers Synapse asynchronous library for needed some tweaking as we learned what we need. We could have built a Delphi and FreePascal, Ararat Synapse, more about the problem, but there was far more elegant solution (and would www.ararat.cz/synapse. light at the end of the tunnel. have enjoyed doing so), but we didn’t With rapid prototyping tools such as need one at the time. There are many the emulators, we confirmed that the reasons for choosing a particular specification was achievable. The emula- development path. Making an existing SOURCES tors also served as a crude test bed on system work better is as good a reason Delphi 2005 which we individually worked on com- as any. I Borland Software Corp. ponent pieces. By reusing the hardware, www.borland.com we saved a considerable amount of time. David Gamble is an electronics enthu- PCH C compilers An extra I/O port would have made siast who has worked with Andrew on Custom Computer Services, Inc. the CPS software development process a number of projects during the past 25 www.ccsinfo.com easier, but adding the port would’ve years. You may contact him at d.gam- meant new boards, more testing, and a [email protected]. MM-5100 CDMA longer delay. The CPS software was by Maxon Electronics Australia far the most difficult thing to develop, Andrew Smallridge holds a diploma www.maxon.com.au however, some of the pain was relieved in electronic engineering and a post- MPLAB IDE and PIC18F452 micro- by adding to the family of tools. For graduate diploma in computer science. controller example, during the development You may contact him at asmallri@ Microchip Technology, Inc. phase, using the bootloader module westnet.com.au. www.microchip.com to load code to the CPS system’s PIC18F452 microcontroller meant that EdiSol eddy covariance system running new firmware was just a few PROJECT FILES University of Edinburgh School of mouse clicks away. Even the PCS soft- To download the code, go to ftp://ftp. Geosciences ware required us to use our existing circuitcellar.com/pub/Circuit_Cellar/ www.geos.ed.ac.uk/abs/research/micr knowledge and a little external glue. 2006/186. omet/edisol/

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 49 WWW.GiURUMELE.Hi2.RO FEATURE ARTICLE by Lindsay Meek Portable Web Server

CONTEST ENTRY

Host your web site the embedded way. No server PC required. Lindsay shows you how to build an M32C/84-based portable web server.

Here’s a slightly different way of to point to a registered IP address. These The data served by the web site is hosting a web site. I recently used a services have a couple of advantages. You stored on a low-cost CompactFlash Renesas Technology M32C/84 micro- don’t have to formally register and main- card. The CompactFlash card supports processor as an embedded Internet tain a domain name. In addition, you large web sites that can be easily server connected permanently via a can dynamically change the resolved IP updated with the built-in FTP server dial-up modem. When the system con- address by sending a simple automated or offline using an external PC that nects to the Internet, it announces its command to its central server. has a CompactFlash reader. The allocated IP address to a dynamic Implementing a dynamic DNS Renesas Technology M32C/84 micro- domain name system (DNS) service. approach eliminates the need to use processor I used for this project had a This enables a fixed domain name to frame redirection and ISP web space. It minimum number of additional ICs. It point directly to HTTP and FTP servers. also enables the web site to be truly allowed for a fast memory-mapped The result is a low-power web-hosting portable because the IP address can interface to the CompactFlash card option for simple web sites. change to whatever the assigned IP using its Expansion mode. address happens to be set to. SIMPLE SITES The embedded web site approach is M32C/84 & CompactFlash The usual process for setting up a also a better solution than using a As you can see in Figure 1, the server’s simple low-cost web site involves get- desktop or server PC. Less power is main hardware components are the ting an account with a local Internet needed for operation. Plus, the relative M32C/84 daughterboard, a CompactFlash service provider (ISP) and setting up a simplicity of the hardware and soft- card interface, an RS-232-compatible series of web pages on its server. The ware enhances reliability and keeps modem interface, and a control power URL often ends up being something costs down. supply. As the heart of the system, like www.ispname.com/~accountname. the M32C/84 communicates directly In addition to being clunky, this URL with the CompactFlash card and makes it difficult for people trying to modem using its memory expansion CompactFlash find your web site. It also contains the memory card bus and UART interfaces (see Figure 2 ISP’s domain name, which can be a (p. 52)). pain if you decide to change ISPs. The CompactFlash card interface Expansion bus A common solution to this problem interface logic connects to CompactFlash memory is to use a stealth redirection service, cards, which gives the module access DC 3.3-V M32C/84 Power which enables a registered domain Regulator Daughterboard to up to 8 GB of solid-state flash supply URL such as www.seriouswebsite.comWWW.GiURUMELE.Hi2.ROmemory. Flash memory uses less to point to your local ISP’s URL by RS-232 Line driver power and is more reliable and rugged inserting it within a stealth frame gen- than conventional hard drives. The erated by the redirection service. This downside is that there are a finite Modem solves one problem but creates anoth- number of times you can write to er. Search engines like Google ignore them. But this is a non-issue for a web frames and drop such web sites from Internet site that doesn’t need to be changed their indexes. service too often. provider A more recent approach involves The CompactFlash card interface is using a dynamic domain name system a miniaturized version of the 16-bit Figure 1—The dark area represents the web site mod- (DNS) service, which enables a URL ule. The Internet is connected via an external serial PCMCIA connector commonly found such as http://seriouswebsite.dyndns.org modem. on PDAs and laptops. A descendant of

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 51 the PC’s ISA bus, the interface con- Device Amperage In addition, the *BHE and A0 lines are sists of a 16-bit data path with an 11- CF Memory card 30 mA used to enable the 8-bit byte lanes for bit address space split into three main M32C/84 MCU 22 mA 8- or 16-bit access. memory spaces: the I/O memory space LCD Module 1 mA The VHDL statements in Listing 1 and the common memory/attribute LEDs (4) 14 mA probably best describe the signal map- spaces. The common memory space is RS-232 Converter 2 mA pings. Note that the CE0, CE1, IORD, further decoded as attribute memory if 9572XL-7 16 mA IOWR, OE, and WE signals are the *REG line is asserted. Total 85 mA CompactFlash bus signals. The *WAIT Attribute memory contains the wait-state input to the M32C/84 is Table 1—The current consumption estimates for the plug-and-play, configuration-specific circuit’s main components are much less than the aver- connected directly to the CF RDY signal. data for the card. It is used during the age stand-alone PC running a web server. PLDs are useful for rapidly prototyp- initialization process to determine the ing high-speed interfaces. I used a card’s capabilities and to select an the various PCMCIA address spaces. Xilinx 9572XL PLD for the bus’s signal appropriate configuration. This memory maps the CompactFlash mapping because I had a couple of The CompactFlash interface can card in the memory area of E00000 spares lying around. If you produce a also operate in a legacy IDE mode by hex, allowing rapid communication PCB, you could simplify this by using grounding the *CSEL line. This makes between the card and the CPU using discrete logic gates, which would the CompactFlash card act like an memory access instructions or the reduce the number of programmable IDE-compatible hard drive. However, I M32C SOUT/SIN block-copy-style devices. decided not to do this because the full assembler instructions. The memory Finally, a dedicated PIO line from CompactFlash interface allows con- expansion timing was adjusted in the the M32C/84 provides a CF_RESET nection to other types of cards (e.g., software to provide the minimum line to the CompactFlash card. I found Sandisk’s combined flash memory/Wi- 600-ns cycle time required for the this to be necessary for the software to Fi card). attribute memory accesses. reset the card to a known state during I interfaced the CompactFlash card The A10 line connects directly to the initialization and configuration to the M32C/84 expansion memory the CF/REG address line. A11 decodes processes. bus in non-multiplexed mode 3. This the I/O and common memory. A10 is was accomplished via a single chip also present on the CompactFlash con- RS-232 INTERFACE select line (*CS0) combined with M32C nector, but CompactFlash cards need The RS-232 interface connects an address lines A10 and A11 to decode only the first eight or so address lines. external modem to the web site mod-

WWW.GiURUMELE.Hi2.RO

Figure 2—J1, J2, J4, and J5 connect to the M32C/84 evaluation board. Note that the evaluation daughterboard isn’t shown here.

52 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com ule’s UART. The interface circuitry Listing 1—The VHDL glue logic statements connect the CompactFlash memory interface to the M32C/84 microcontroller’s expansion bus. Address line A11 controls the multiplexing between I/O and common memory. consists of a fairly generic charge-pump voltage converter, providing Rx, Tx, -- RTS, and CD lines. The RTS line pro- -- generate chip selects for 8/16 bit operation vides hardware flow control to stop the -- chip_selects: process(cs0, bhe, a0) modem from overflowing the input begin buffer during high-speed transmission ce0 <= '1'; bursts. The M32C/84’s UART0 ce1 <= '1'; peripheral is used to communicate if cs0='0' and a0='0' then ce0 <= '0'; with the modem. end if; if cs0='0' and bhe='0' then CONTROL POWER SUPPLY ce1 <= '0'; The power supply for the web site end if; end process chip_selects; module consists of a 3.3-V regulated DC supply, which is provided via a simple -- linear regulator. The CompactFlash -- generate read and write strobes cards support either 5 or 3.3 V during -- read_strobes: process(rd, a11) their configuration phase, but most begin of the newer cards are designed to oe <= '1'; run at 3.3 V. iord <= '1'; Estimates for the power budget for if rd='0' and a11='0' then oe <= '0'; the module are shown in Table 1. The end if; total amount of power required with a if rd='0' and a11='1' then 5-V supply is 425 mW (i.e., 5 V × 85 mA). iord <= '0'; The regulator power dissipation is end if; end process read_strobes; 144 mW (i.e., (5 V – 3.3 V) × 85 mA). The rise in the regulator’s temperature write_strobes: process(wr, a11) is around 9°C (TO-220 without a begin heatsink). This indicates that the linear we <= '1'; iowr <= '1'; regulator can easily manage the heat if wr='0' and a11='0' then with a 5-V supply. It also means the we <= '0'; web site module should draw less end if; than 0.5 W during operation. if wr='0' and a11='1' then iowr <= '0'; I had some difficulty with the evalu- end if; ation board I received for the Renesas end process write_strobes; M16C Design Contest 2005 because it was intended to run at 5 V not 3.3 V. Listing 2—The main control flow for the web server’s software is straightforward. Luckily, the fixes were minor. I rewired the LCD contrast potentiometer and INITIALISE PLL & MCU CONFIGURATION logic supply input so they were supplied INITIALISE EXPANSION BUS INTERFACE directly from the 5-V supply. The INITIALISE LCD DISPLAY INTERFACE INITIALISE TICK TIMER M32C/84’s PLL oscillator frequency INITIALISE LEDS & SWITCH INTERFACE also needed to slow down from 32 to DISPLAY SIGN ON MESSAGE 24 MHz to remain within Renesas’s INITIALISE UART specifications. RESET & CONFIGURE COMPACT FLASH CARD FOR I/O MODE OPERATION LOAD CONFIGURATION SETTINGS FROM FLASH CARD DIAL ISP IFWWW.GiURUMELE.Hi2.RO ENABLED SOFTWARE NEGOTIATE PPP CONNECTION The web site module’s main software INITIALISE TCP/IP PROTOCOL STACK elements are broadly divided into the INSTALISE HTTP SERVER ON PORT 80 INITIALISE FTP SERVER ON PORT 21 TCP/IP/PPP protocol stacks and INITIALISE DYNAMIC DNS CLIENT CompactFlash file system. To accelerate FOR EVER the development cycle, I built the SERVE FILE REQUESTS ON HTTP PORT basic architecture with open-source SERVE FILE REQUESTS ON FTP PORT PERIODICALLY REFRESH DYNAMIC DNS SERVER IP ADDRESS software subsystems. I wired it together IF DIAL ENABLED AND CARRIER NOT DETECTED with additional glue code to provide RESET CPU the desired functionality. END IF The main control flow of the web LOOP module is summarized in Listing 2. www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 53 You may download the rest of the PPP client to reject most of the more Finally, a FAT16 file system driver is code from the Circuit Cellar FTP site. advanced PPP features that the ISP on top of the IDE drive interface. The attempts to negotiate during link ini- driver interprets the directories and PROTOCOL STACKS tialization. This simplifies the PPP files stored in the disk structure. Most The web site module’s protocol client implementation by requiring CompactFlash cards larger than 32 MB stacks consist of the usual industry- only the minimum number of link are formatted using the FAT16 file sys- standard TCP/IP sockets, PPP, FTP, and features required for establishing a tem, usually via a PC-based card reader. HTTP servers. The stacks are based PPP link. The FAT16 driver provides a POSIX- heavily on the TinyTCP package’s soft- The PPP client also intercepts style file system interface with famil- ware framework. Internet control message protocol iar functions such as open(), close(), At the application level, the frame- (ICMP) echo requests (pings) and sends read(), and write(). The driver is work consists of a minimalist callback a response back to the originating glued to TinyTCP’s file handler hooks, structure, where the TCP/IP stack party. The PPP client also generates a providing the disk interface for the runs as a single foreground thread. periodic keep-alive ping request to a HTTP and FTP servers. This thread continuously calls a user- nominated IP address, which is used nominated polling callback function to keep overzealous ISPs from drop- DYNAMIC DNS CLIENT when it is idling and waiting for ping the call during periods of inac- One of my portable web server’s incoming data. tivity. The ping/pong sequence is best features is its ability to appear as The server ports listening for HTTP shown in Photo 1. a static web site on the Internet, even and FTP requests are also initialized though the IP address is dynamically with callback functions. Any data CARD DRIVER reassigned each time the PPP client packets received on these ports are The CompactFlash memory card connects to the ISP. This is achieved passed up to the handler for further stores web site pages and files. It has a using a dynamic DNS service (e.g., processing. structure and an interface similar to a www.dynu.com), which provides a The user-nominated polling callback standard IDE hard disk in that it has a simple and free automated interface function runs the background activities master boot record, boot block, and for resolving DNS queries and points such as client-based TCP/IP socket FAT file system. them to the web server. processes, file transmission, and The low-level interface to the The mechanism for informing the modem connection status monitoring. CompactFlash card consists of memory- dynamic DNS service of the assigned If the modem drops out, as indicated mapped I/O. The M32C/84’s expanded IP address consists of an HTTP GET by the loss of the carrier detect signal, memory mode is used to communi- request to its main server. The request the web site module resets itself and cate with the CompactFlash card contains the domain name, the attempts to reconnect to the ISP. using direct memory accesses. Basic assigned IP address, and a security Currently, the HTTP and FTP servers register and block read operations are password. The dynamic DNS client are able to send only a single page or performed on the CompactFlash card’s within the web site module has a peri- file at a time, because only a single I/O, common, and attribute memory odic timer that opens a socket to the active file descriptor is used. This can spaces. main server and sends the GET request be extended in the future to a higher- The next layer up is concerned every few minutes. capacity server by maintaining a larger with resetting and configuring the list of active file descriptors. CompactFlash card into the correct ADDITIONAL WORK At the link layer interface level, the operating mode. This process involves My design has some limitations that TinyTCP distribution consists of an examining the attribute memory to I’ll probably address in a future revision. example serial line IP-based (SLIP) verify that the card type is actually a The first limitation is the relatively serial interface driver as well as an memory card. The location of the all- inefficient implementation of packet Ethernet card driver. The PPP interface important PCMCIA configuration reg- buffering, which results in a larger was adapted into a PPP client because ister is also determined. After the than necessary RAM requirement for a PPP is well supportedWWW.GiURUMELE.Hi2.RO by ISPs on their PCMCIA configuration register is relatively small number of socket han- dial-up as well as ADSL links. located, the card can be activated by dlers. A better approach would be to The PPP protocol is somewhat simi- writing an enumerating value to this recycle the buffers from a centrally lar to SLIP in that it inserts escape register, allowing the disk control reg- managed pool. This is similar to the code sequences into the serial stream isters to be mapped to the I/O space. socket memory concept used for the to indicate packet boundaries. But it The layer above the card configura- networking system on Linux. The also checksums the packet data for tion is the IDE drive interface, which improved RAM usage efficiency would errors and has flexible link control fea- communicates using the IDE con- increase the number of simultaneous tures. The flexibility of the link con- troller registers. It provides basic disk- socket connections. Therefore, I’d see trol negotiation works in favor of the related functions like identifying the an increase in the maximum number lightweight embedded implementa- device, reading the data sector, and of users before receiving a “server tions of PPP. It’s possible to get the writing the data sector. busy” message.

54 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com PROJECT FILES To download the code and additional files, go to ftp://ftp.circuitcellar.com /pub/Circuit_Cellar/2006/186.

RESOURCES D. Anderson, PCMCIA System Architecture: 16-bit PC Cards, Addison-Wesley, Boston, MA, 1995. Dynamic DNS Service Information, www.dynu.com/basic.asp. F. Eady, “Embedded Wi-Fi with TRENDnet,” Circuit Cellar 174, January 2005. FAT16 File system specifications, www.maverick-os.dk/FileSystem Photo 1—The M32C/84 evaluation board sits on top of the web site motherboard. The ICMP keep-alive ping Formats/FAT16_FileSystem.html. response displays a “PONG” message. In no way does Index of /Apple2IDE, http://s.guillard. this refer to the quality of the modifications required to fix the RS-232 wiring. free.fr/Apple2IDE/. Internet RFC/STD/FYI/BCP Archives, Substituting the carrier detect (CD) www.faqs.org/rfcs/. input with a clear-to-send (CTS) signal Mircochip Technology, “Using from the modem would also enable PICmicro MCUs to Connect to the module to make better use of the Internet via PPP,” AN724, DS00724C, buffers contained in the modem. It 1999, www.microchip.com/down would reduce the size of the local loads/en/AppNotes/00724c.pdf. transmit stream buffer. Removing the carrier detect signal would require the Registration for CompactFlash software to be changed so that it mon- Specification download, itors the modem connection using www.compactflash.org/specdl1.htm. something else, such as a keep-alive SanDisk Corp., “SanDisk CompactFlash ping. Memory Card,” V. 10.8, 20-10-00038, Additionally, the FAT file system 2005. interface on the module doesn’t sup- port long file names. This results in Stealth Redirection Service, the need to truncate the web site page www.mydomain.com/domains_ file names to the shortened (and urlfwd.php. ancient) 8.3 convention. Incorporating TinyTCP information, www.unusual these missing features, perhaps research.com/tinytcp/tinytcp.htm. together with Wi-Fi capability, would make for an even more useful, cool gadget. I WWW.GiURUMELE.Hi2.ROSOURCES M32C/84 Microcontroller Lindsay Meek is currently employed in Renesas Technology Corp. Advanced Energy System’s embedded www.renesas.com systems division. He holds a bache- CompactFlash memory card lor’s degree in engineering as well as a SanDisk Corp. master’s of philosophy. Lindsay is www.sandisk.com interested in emerging technologies and enjoys participating in international XC9572XL PLD design contests. You may contact him Xilinx, Inc. at [email protected]. www.xilinx.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 55 FEATURE ARTICLE by Ingo Cyliax Internet-Connected Sonic Anemometer

Ingo’s Internet-based sonic anemometer gauges wind velocities by measuring the speed of sound in air. Read on to learn how the system works. Ingo has included all the infor- mation you need to get started on an anemometer of your own.

I recently became interested in A hot-wire anemometer measures F1 > F2, F3, F4 anemometers when I took a new job in F1 the heat carried away by a moving air × × the weather instrument industry. One of T = F1 r sin(90) + mass (see Figure 3). The higher the × × T F2 r sin(0) + the most common instruments used in F3 × r × sin(–90) + wind speed, the more heat carried r F × r × sin(180) weather stations to measure wind veloci- F2 4 away (i.e., it cools the wire). F3 ty is the anemometer. Cup anemometers Pitot tubes and hot-wire anemometers feature several half-spherical, hollow cups F3 are advantageous because they don’t have attached to radial spokes (see Figure 1). moving parts that need to be sealed from It’s intuitive to see that the coefficient of the elements. Anemometers are often Figure 1—The rotational speed of a traditional cup drag for a spherical cup differs depending anemometer is determined by the difference in drag force installed in remote weather stations on where the air is pushing. Basically, and indicates wind speed. A separate vane is used to where they’re hard to maintain, so hav- the drag is high for the hollow side in indicate the wind’s direction. ing one with no moving parts is a perk. comparison to the closed side. Using a Doppler lidar is an interesting This difference in drag generates overcome friction and drag. They have way to measure the effects of wind torque that spins the entire assembly. A momentum, so they don’t respond well speed. A laser beam is sent out and par- tachometer then measures the resulting to wind gusts and tend to average out ticles in the air (aerosols or water) scat- rotational speed, which has a linear rela- the speeds. ter it. Some of the scattered beam is tionship to the wind speed. Typically, There are other instruments for reflected to a sensor that measures the the tachometer is either implemented as measuring wind speed. Pitot tubes are shift in the laser’s wavelength when the a small generator that generates a volt- used in applications where the wind aerosols are moving. You can measure age into a load or a Hall effect or optical comes from a specific direction (see their radial speed to the laser by meas- sensor that generates pulses relative to Figure 2). For instance, when measuring uring the laser’s Doppler shift (or an RF the rotational velocity. a plane’s airspeed, the wind always carrier modulated on the laser). Another common method is to use a comes from the front of the plane with A fringe-type laser anemometer proj- small wind turbine. The wind drives a only small angles of deviation. A pitot ects a field of interference fringes and propeller or turbine wheel. The resulting tube works by measuring the dynamic detects how aersols are illuminated by rotational speed is measured to give an pressure of the wind as it enters a small the fringe pattern as it moves through indication of the wind speed. Using cup hole pointed toward the wind. The tube the field. complex devices require power- and turbine anemometers can be disad- compares the dynamic pressure to the ful lasers to get any range. They require vantageous because they require a sig- ambient air pressure. The dynamic high-frequency, fast electronics to make nificant amount of minimum wind to pressure is easy to calculate: them work with any resolution or accu- racy. They are usually limited to scientif- × ()× 2 WWW.GiURUMELE.Hi2.ROPDYN = PSTAT + 0.5 rho V ic applications. For example, in systems Open in front where rho is the air’s density. As you that measure wind speed and aerosols can see, you have to subtract the static pressure in order to compute the speed: I Open on sides PSTAT PDYN P − P V = DYN STAT V Difference 05. R Liquid-filled in pressure Wind glass tube A disadvantage is that a pitot tube Wire anemometer is accurate only if the Figure 2—A pitot tube anemometer is common on air- planes and in applications where the wind comes from wind blows directly into the pressure Figure 3—A hot-wire anemometer measures the wind the same direction. port. by how much it cools the resistively heated wire.

56 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO tens of kilometers in the atmosphere, or measure wind speeds in wind tunnels. V A sonic anemometer measures the SOUND speed of sound in air. In this article, I’ll V = explain how you can measure wind TOT VWIND + VSOUND speed with one. At this point, you might be thinking, “So what!” The per- Tx Rx ceived speed of sound in air is actually Figure 4—In a sonic anemometer, the wind speed the speed of sound in static air plus adds to or subtracts from the speed of sound in air or minus the speed of the wind (see depending on the sound’s direction. Figure 4). In other words, the wind speed is the difference between the tions of the sound. The delay between measured speed of sound and the actual the transmitted burst and the received speed of sound in air. burst is called time of flight (TOF), which can be converted to distance if SPEED OF SOUND IN AIR you know the speed of sound. The speed of sound in air depends C Range = T × AIR mostly on the temperature. It depends TOF 2 slightly on humidity and the air’s actual mixture of gases. Luckily, you Although ultrasonic transducers are have to worry only about the tempera- bidirectional devices (i.e., they func- ture. Furthermore, if you’re only inter- tion as transmit and receive transduc- ested in the wind speed, you can just ers), they usually use a separate trans- factor out these effects. mitter and receiver transducer. The The standard speed of sound is usually transmit transducer has a tendency to determined by one of the following: ring for some time after the excitation × waveform stops. This limits the short CAIR = 331.5 + 0.6 TC or range of such a system. Transducers can be optimized for C = 20 × T AIR K transmitting or receiving. If you substi- These are approximations, and they don’t tute one for the other, you’ll get reduced account for humidity. A more precise performance. Circuitry for rangers using instrument would use more elaborate separate transducers is available in models for the speed of sound in air. many robotics publications and How do you go about measuring the datasheets for transducers. speed of sound? The most reliable meth- Measuring the actual speed of sound ods involve ultrasound range measuring. is easy if you have a calibrated dis- Ultrasonic transducers, especially for tance. In sonic anemometers, the the 40-kHz band, are readily available. transducers are mounted in a fixture I’ve seen them used in numerous that fixes a direct distance between robotics projects. transducers. If you measure the direct In an ultrasonic ranger, a short burst time of flight between the transducers, of ultrasound (8 to 16 cycles) is trans- you can compute the perceived speed. mitted via a transducer. Another Distance transducer then picks up the reflec- C = PERCEIVED TOF WWW.GiURUMELE.Hi2.ROThis speed is the speed of sound in the air plus the speed the wind exerts.

CCPERCEIVED = AIR + CWIND

If you determine the air temperature with a thermometer, you can compute the wind speed simply by applying one of the earlier expressions: −×() CCWIND = PERCEIVED 331.5 + T 0.6

Photo 1—I built my three-point anemometer with PVC Now, here comes the clever part. If you pipe. The distance between the adjacent sensors is 0.36 m. measure the speed in both directions

58 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com along the same path, you don’t need to ing pitch as they approach and recede know the temperature. from a stationary listener. Of course this is true, but in the sonic anemome- C 12 = C + C PERCEIVED AIRWIND ter setup, both the listener and the train C 21 = C − C PERCEIVED AIR WIND whistle appear to be moving at the By combining a the equations, you get: same speed. So, it’s more like listening CC12 + 21 to the train whistle while you’re on a C = PERCEIVED PERCEIVED AIR 2 car in the back of the train (i.e., the C 12 − C 21 pitch doesn’t change) even though the C = PERCEIVED PERCEIVED WIND 2 train may be moving at great speed. You can also derive the current tem- The Doppler signal in a sonic perature: anemometer measures the change in C − 331.5 wind speed, which can give an indica- T = AIR 06. tion of the wind speed’s stability at the Of course, the system needs to transmit moment it’s measured. You can use this and receive in both directions along the to measure turbulence and fluctuations path. This requires the transceiving in wind speed. Of course, this involves transducers or a set of transmit/receive being able to measure the changes in transducers. the received signal’s frequency. You can Ringing in the transmit transducer isn’t use a fast Fourier transform (FFT) to a big problem because the turnaround look at the purity of the spectrum. You time is slow. The system waits for the may also need a transducer with a wide burst to travel the distance to the other frequency range. Many ultrasonic trans- side before it switches direction. But the ducers are tuned for a specific frequency ring has a tendency to stretch the pulse and attenuate if the received sound fre- by adding more cycles to it. This seems to quency is out of the pass-band. Check work. Well, not quite. It only determines the transducer’s datasheet. the wind speed along the path. When the wind blows from an angle, you can see IMPLEMENTATION only a portion of the wind speed. When I built a three-transducer, three-path the wind is orthogonal to the path, you sonic anemometer. Each transducer can can’t see any wind speed at all. see the other two transducers by arrang- To fix this, you can configure the ing them in a triangle (60° angles). Three anemometer to measure in different paths is a good compromise between min- paths. The cross (orthogonal) is a typical imizing the number of transducer chan- configuration. Use the same technique nels and maximizing the number of paths to measure the wind speed along each of for measuring the wind speed. The afore- the two paths (x and y). To compute the mentioned two-path, four-transducer absolute wind speed, simply add the anemometer needs one of the transducers. squares of each component and take the The transducer I selected is optimized square root (magnitude equation): for transceiving. It has a beam angle wide enough to see the others with a CC = 2 + C 2 WIND WINDX WINDY 3-dB signal reduction. For transmitting

You can also derive the wind direction: an AC signal, up to 20 VPP is applied to the terminals. When the transducer  C  Direction = Atan WINDY  is connected to a high-impedance  C  WWW.GiURUMELE.Hi2.ROWINDX input, it behaves like a microphone Other configurations are also possible. and generates a voltage in the load. I used a triangle (60°). The transducer’s design dictates the You might have noticed that you resonant frequency (40 kHz) and beam aren’t measuring the Doppler shift of angle. I could have used a different fre- the sound burst. A common miscon- quency transducer (125 or 250 kHz), ception about using a sonic anemome- but there is less absorption loss in the ter is that you can measure the wind air at a lower frequency. Furthermore, speed by measuring the Doppler fre- lower frequencies make the processing quency shift of the ultrasonic signal. requirements less demanding. Recall the high school physics experi- The transducers are mounted in a ment relating to train whistles chang- PVC pipe structure (see Photo 1). PVC

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 59 5 V processor can read the com- the sensor and front-end electronics parator’s output directly. The with an SBC (see Figure 6). If RS-485 output can be routed to a drivers and receivers are used, it’s *SND/RCV RA.0 RB.1 RX separate output pin. The possible to route the signals for long RB.0 RB.2 input pins can be shared distances. 5 V with the output pins. I used a Rabbit Semiconductor 1 MΩ 1 MΩ 10 kΩ In order for the received sig- RCM3000 development board for the nals to be in the comparator’s front-end electronic interface. The voltage range, a simple resis- processor has a high-speed pulse capture Ω SX20/28 10 k tor network must bias the that enables me to take precise meas- inputs to a point approximately urements of the time of flight. In addi-

halfway between VCC and tion, it has an Ethernet interface and an Figure 5—The transmit/receive circuit is based on a Scenix SX20/28 GND when the pins are in a optional Wi-Fi connection kit. The pro- processor. The transducer is attached to the pins that serve as both tristate condition. It turns out totype board has a regulator that accepts an analog comparator for receiving and digital I/O, which drive the that the 10- to 20-mV offset 9 to 12 VDC, which enables me to con- transducer in a push-pull configuration. I used two-conductor micro- voltage is perfect for this nect it to a sealed lead acid battery in phone cable to reduce crosstalk. application. Under normal case I want to run the system discon- conditions, the received signal nected from the main. tube is great for building these structures has up to approximately 100 mV for the For portability, economical solar because it’s easy to work with and a selected range and driver voltage. That’s panels and a charger are available for variety of fittings are available. The enough to give a reliable zero-crossing 12-V systems. With a Wi-Fi connection, transducer fits in the tip of each arm and detection, but isn’t too sensitive to pick I can use my laptop to connect to the is held in place with a little RTV. I origi- up noise transients. instrument and communicate with it nally used twisted-pair cable to connect The front end has two interface sig- using a ’Net interface or FTP to to the transducers, but that was a mis- nals for control. When the *SND/RCV upload wind data. take. I’ve since switched the wiring to pin is pulled low, the front end enters In addition to the aforementioned two conductors with shield microphone Transmit mode. A 16-cycle, 40-kHz features, the software library comes wire. The two conductors are isolated square wave burst is then sent to the with fairly fast floating-point routines. from the ground-shielding wire. The transducer. When the *SND/RCV pin The TCP/IP stack and web server is shield is terminated on the electronics is pulled up, it switches to Receive also included. end. This reduces crosstalk between the mode and sends the comparator’s out- The SBC continuously goes through transmit and receive wires and it elimi- put back via the Rx line. an acquisition cycle to measure the nates ground-loop oscillations. The SX28/20 microcontroller is avail- TOF delays between each transducer. The front-end electronics were the able in a 20-pin SSOP package, so you For each ping, you can collect two most difficult to come up with. I had to can integrate the entire front end in a paths by using the two pulse capture switch the transmission circuitry, which package that can be soldered directly registers. So, with a round-robin cycle is relatively low impedance with the to the transducer and fit inside the of three pings, you can collect six path high-impedance inputs to the receiver. PVC tube that holds it. This approach times. There are forward and backward After trying a different scheme, I finally eliminates the need for high-imped- times for each of the three physical settled on a solution featuring a Scenix ance wires in the anemometer. Four paths (T12, T21, T13, T31, T23, and T32). SX28/20 microcontroller (see Figure 5). wires (5V, *SND/RCV, RX, and GND) The path lengths for the three segments

The SX28/20 microcontroller has attrac- can be routed via twisted-pair wire to are measured (D12, D23, and D31) and tive features like symmetric adjusted for processing delays. CMOS outputs, which can The pulse capture happens source and sink up to 30 mA Wi-Fi to be in the hardware, so there each. I used the CMOS outputs 5 V aren’t any real time con- 12 V *SND/RCV1 as push-pull drivers and a supply Transmit/ straints on the system other WWW.GiURUMELE.Hi2.ROGND RX1 XCVR voltage of 5 V to drive the trans- receive than the transition from send- ducer with a 10-V voltage differ- ing the transmission pulse and *SND/RCV2 Transmit/ ential with plenty of current. SBC RX2 XCVR the arming of the capture time RS232 T receive I can switch off or tristate the X register. But this is a short RS232 RX outputs to put them into a high *SND/RCV3 time that can be handled by RX3 Transmit/ XCVR impedance state. A built-in receive simply turning off the inter- analog comparator has a low GND rupts for a few instructions. It offset voltage (10 to 20 mV) doesn’t affect the performance and short delay (25 ns) that Figure 6—The system is divided into three subsystems. The SBC handles all or add delays in processing of the communications. The transmit/receive circuit interfaces and modulates make it suitable for a sensitive the transducers. The transducers are in the tips of the actual sonic anemome- when dealing with the TCP/IP zero-crossing detector. The ter assembly. protocol stack and web server.

60 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com To measure wind speed with resolu- tion of 1 meter per second, I need a timing resolution of 1 part in 300. The WY W12 path is 0.36 m in my instrument, which results in a 1.2-ms TOF delay. A 1/300 resolution implies a timing resolution on the order of 6 µs, which the hardware capture in the RCM3000 W13 has no problems with. WX The system uses a different geometry than a traditional cross anemometer W using orthogonal paths. The math is a 23 bit more involved, but you can add all of the vector components and use trigonometry. Figure 7—Computing the vectors in a three-point Assume that the transducer is anemometer is a bit more involved, but it’s still man- anchored at the origin and two and ageable. three are anchored at 0° and 60° angles (see Figure 7). You must first compute adding an extra transducer to the ver- each wind vector: tical plane, I can add three more paths D D to the instrument and measure a 12 − 21 T T three-dimensional wind profile. W = 12 21 12 2 Well, this project has been a lot of D D fun. For my next project, I’ll try to 23 − 32 T T miniaturize the front electronics and W = 23 32 23 2 attach them to the transducers. I’ll D D 13 − 31 also weatherize the system so I can T133 T31 use it outside for extended periods of W13 = 2 time. A friend of mine is interested in Following this, add all of the vector placing a stand-alone unit with a GSM components: modem near his favorite surfing spots in order to obtain wind conditions. WW = × sin() 60 + W Y 12 23 Surf’s up! I ×− sin() 60 × () WWX = 12 cos 60 + W23 ×−() cos 60 + W13 Ingo Cyliax is the senior research engi- Lastly, compute the absolute wind and neer at All Weather, Inc., a Sacramento- angle. based company specializing in weather 2 2 instruments and systems. He has experi- Wind = WY + WX ence in many areas, including hardware  W  Angle = Atan Y  and software design, and has worked at  W  X Z-World/Rabbit Semiconductor, Purdue University, Indiana University, and ADDITIONAL IDEAS ETH-Zurich. When Ingo is away from As I mentioned earlier, you can the bench, he enjoys hiking, camping, or extract the Doppler information to simply sipping coffee at his favorite compute variationsWWW.GiURUMELE.Hi2.RO in the wind speed. sidewalk cafe. You may contact him For most applications, however, it’s [email protected]. enough to take samples and compute a running average and variance to get an idea about the wind’s stability. SOURCES Because the TOF distance is short and RCM3000 development board the sensitivity to echoes and reverber- Rabbit Semiconductor ation is low, a firing time of 10 ms is www.rabbitsemiconductor.com easy to achieve. This results in a cycle time of 33 Hz. SX28/20 Microcontroller My anemometer computes only a Ubicom, Inc. (formerly Scenix) two-dimensional wind profile. But by www.ubicom.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 61 FEATURE ARTICLE by Victor Lick Advanced System for Vehicle Back Up Rangefinder and Video Display System Aids Drivers

Victor built a PIC18F2320-based, distance-measuring video system so his friend could safe- ly back his truck up to his RV trailer. After a Parallax PING))) ultrasonic ranger measures the distance between the truck and the trailer, the system displays the data on a small monitor.

A couple of years ago, I was helping version of the design, which I call the that it represents changes based on what my friend Don back his truck up to his Backer Upper. The system features a you’re backing up to. RV trailer. It wasn’t hard to do, but it did back-up camera system and a Parallax If you’re backing up to nothing in par- take more than one attempt. His 5-ton PING))) ultrasonic rangefinder. The dis- ticular, the set point line will represent trailer is 35′ long, so precision was need- tance measured by the rangefinder is a distance of 8″ from the rangefinder. ed. Throwing his shoulder into it, Don overlaid as a horizontal line on the com- But if you’re backing up to an RV trailer, couldn’t nudge it even the tiniest amount. posite video stream generated by the the set point line will represent a dis- Always looking for a project to tinker camera (see Photo 1). The video also tance of 16″ from the rangefinder. with, I suggested that we install a device displays text data about the situation Simply back up until the range line (the to measure distances and monitor align- behind the vehicle. The set point is the small horizontal line) reaches the set ment. Soon thereafter I started working broken horizontal line near the bottom. point line. At that point, you’ll be in the on a multifunctional monitoring system. It’s always in the same position on the correct position. The vertical line sits in In this article, I’ll describe the third screen, but the distance from the truck the middle of the screen. Because the

WWW.GiURUMELE.Hi2.RO

Figure 1—The circuit incorporates two PIC microcontrollers (PIC18F2320 and PIC12F683), glue logic, a basic linear voltage regulator, a temperature sensor, a canned oscilla- tor, and a rangefinder module. There’s nothing critical about the circuit’s layout, but ample decoupling is necessary.

62 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com camera and rangefinder are mounted on ancillary circuits include an Intersil an object and sends clock pulses to the the truck’s centerline, it helps you align EL1881 video sync separator, a 20-MHz PIC18F2320. The number of sent pulses, the truck with the trailer’s hitch. oscillator, and a D flip-flop for control- which is proportional to distance, is then ling the PIC18F2320’s clock. counted by the PIC18F2320 and dis- SYSTEM OVERVIEW No article involving a microprocessor played as a video overlay on top of the I built the Backer Upper system around is complete without some discussion of camera’s signal. Video synchronization a Microchip Technology PIC18F2320 the code required to make everything for the overlay is the most important microcontroller. The PIC18F2320 is used work. I wrote the Backer Upper master aspect of the design. for command and control, triggering the PIC18F2320’s code in MicroEngineering The Backer Upper has four switches: rangefinder, converting distances to the Labs’s PICBASIC Pro 2.44 with some SEL, SET, DISP, and DIST. SEL selects display format, and producing the video in-line assembly for the time-sensitive the set point. DISP turns the video overlay (see Figures 1 and 2). The parts. I wrote the PIC12F683 code com- overlay on and off. SET is used in con- pletely in assembly language because junction with SEL and DISP. Holding my version of PICBASIC didn’t support SET and then pressing SEL sets the set the PIC12F683. point for a given situation. Holding SET The system basically operates as follows. First, the sync separator breaks TRCK 12.6″ up the composite video signal. Following this, the Video in Monitor PING))) module signals are used to syn- chronize the PIC18F2320’s Video out SEL SET DISP DIST Backer Upper Bright operation by turning on Video in Photo 1—The Backer Upper has detected a bicycle and off its oscillator at 12 VDC 22.3″ away.The video has various components. The Camera certain times by setting Video out source appears in the upper left. The distance is in the and resetting the flip-flop. middle of the screen. A thin vertical line is used for Figure 2—The connections are straightforward. A four-conductor phone alignment. The broken line at the bottom indicates the The rangefinder then cord connects the main unit and the coprocessor. I used standard RCA set point and the shorter moving range line. measures the distance to jacks for video in and out.

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 63 and then pressing DISP sets the unit But without synchronization with back to its factory defaults. DIST the video stream, the PIC’s video turns on and off the distance display, is just a mess of noise scattered which shows the absolute distance across the monitor. To ensure crisp to an object. For distances less than video overlays, the injected signal 24″, inches and tenths of an inch are must be genlocked to the video. displayed. For distances greater than That’s where the flip-flops come in. 24″, feet and tenths of a foot are dis- At the beginning of each horizon- played. Dashes are displayed for dis- tal scan line, the EL1881 takes its tances greater than 10′. CSYNC line low for a few microsec- The Backer Upper has four set onds (see Photo 2). Through the D Photo 2—I used my BitScope DSO to take a screen shot of the points. One set point is for backing scan line that the range line is on. The timing of the various signals flip-flops, this pulse gates the oscilla- up a truck. The second is for back- controlling the master PIC18F2320 is shown clearly in relationship tor output to the PIC18F2320 and ing up to a boat trailer. The third is to the composite video. then processing begins for that par- for backing up to an RV trailer. The ticular scan line. The oscillator fre- fourth is for the back of the RV trailer. The BOAT and TRLR settings are quency, which is much higher than the (I haven’t installed a camera and designed for specific situations, but I horizontal scan frequency, enables a good rangefinder behind the trailer yet.) The can use the TRCK and BACK settings deal of work to be done before the end of set points—labeled as TRCK, BOAT, to safely back up to anything. I can set the scan line, which lasts 63.56 µs. After TRLR, and BACK—are shown in the the set points by using a person, a the video has been produced for a given upper left corner of the screen. garage door, or anything that can reflect scan line, the flip-flop is clocked by one Calibrating the set points is easy. After sound. The TRCK setting is particularly of the PIC12F2320’s I/O pins. This causes you position the truck and press and hold useful. No more tapping into cars when the clock to stop and, in turn, causes the SET switch, simply press the SEL parallel parking. the PIC18F2320 to stop processing. switch to store the distance from the The microcontroller isn’t in Sleep rangefinder in EEPROM. The process is GET THE PICTURE mode. It’s just sitting there waiting for the same for all four settings. Note that A free-running PIC can easily inject the clock to start again. Controlling the unit remembers the last selection. video into the composite video stream. the PIC18F2320 in this way—start at

WWW.GiURUMELE.Hi2.RO

64 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com the beginning of a horizontal the echo is heard. When the echo scan line and stop before the is heard, the output is taken low. end of the scan line—allows for The output pulse’s width, which crisp, jitter-free video overlay. varies from 115 µs to 18.5 ms, is Although shutting off the proportional to the round trip dis- clock produces excellent stability tance traveled by the sound burst. for the video overlay, it has the For an average speed of sound of disadvantage of not allowing the Photo 3—Shortly after the vertical sync pulse, the rangefinder goes into 1,130′ per second, the roundtrip action. The tiny blip on the left side of the I/O signal is the 5-µs trigger PIC18F2320 to measure the distance the rangefinder can pulse. The wider pulse is the rangefinder’s output based on distance. The ″ ′ rangefinder’s output. To accom- eight cycles of the 40-kHz sound are clearly visible. The bottom trace is the measure is 1.6 to 20.9 . That’s plish this, I added a range output of the PIC12F683 PWM block as gated by the rangefinder’s output. quite a range. coprocessor that produces a Use the following formula to clock used by the PIC18F2320 to The LM335A indicates the ambient convert time to distance: determine distance. air temperature by producing 10 mV/°K. 12pS This voltage is read by the PIC12F683’s D = 2 SOUND UNDERSTANDING ADC and used to adjust the PWM fre- The range coprocessor portion of the quency based on temperature. The where D is the distance in inches, p is the circuit consists of a PIC12F683 micro- adjustment compensates for the changes rangefinder’s pulse width, and S is the controller, an LM335A temperature in the speed of sound caused by changes speed of sound in feet per second. You can sensor, and the rangefinder. The in air temperature. also use it to calculate the needed PWM PIC12F683—which is clocked at 20 MHz The rangefinder is a user-friendly block frequency. If the rangefinder’s pulse and configured with the MCLR used device that uses 5 V and only one of the width is set to 1 s and S is 1,130′ per as an I/O pin—triggers the rangefinder PIC12F683’s I/O lines. A 5-µs pulse trig- second, then a distance of 6,780″ is cal- when told to do so by the PIC18F2320. gers the device into action (see Photo 3). culated. I wanted 0.1″ resolution, so I It also controls the frequency of the That pulse triggers the ultrasonic trans- multiplied the distance by 10 and got pulse width modulation (PWM) block, ducer to send a 200-µs burst of 40-kHz 67,800 tenths of an inch per second. which is gated to the PIC18F2320 sound into the air. At the same time, the Using techniques from a basic fre- based on distance. rangefinder’s output is sent high until quency counter (i.e., gating a known

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 65 WWW.GiURUMELE.Hi2.RO Temperature Speed of LM335A ADC Desired PR2 PWM Temperature No temperature MASTER PIC sound register compensation compensation As you can see in Figure 3, 32°F 1,085.5 FPS 2.732 V 559 65,148 Hz 76 64,935 Hz 0.05″ –0.61″ stored set points and the last 50°F 1,105.5 FPS 2.832 V 579 66,331 Hz 74 66,666 Hz –0.08″ –0.33″ selection are retrieved from 60°F 1,116.3 FPS 2.887 V 591 66,978 Hz 74 66,666 Hz 0.07″ –0.18″ EEPROM after initialization. 72°F 1,129.1 FPS 2.954 V 604 67,747 Hz 73 67,567 Hz 0″ 0″ Following this, the text for 80°F 1,137.6 FPS 2.998 V 614 68,255 Hz 72 68,493 Hz 0.06″ 0.12″ the selection is loaded into 100°F 1,158.5 FPS 3.109 V 636 69,508 Hz 71 69,444 Hz 0.01″ 0.42″ video RAM for display. From Table 1—I developed a look-up table for the PR2 setting. The Temperature Compensation and No Temperature Compensation there, the code branches to columns show the error at 16″ with and without temperature compensation. vloop, where some work is done, and then on to end- frequency for a variable time to indicate 1,158.5′ per second, respectively. If loop, where the flip-flop is reset and an unknown frequency or count), you there had been no temperature com- the PIC18F2320 stops processing. The can make a basic frequency counter that pensation and the unit had been cali- next CSYNC pulse sets the flip-flop is calibrated to show distance instead of brated at 72°, the errors at 16″ would and causes the PIC18F2320 to run. frequency. If an oscillator running at have been 0.6″ at 32° and 0.4″ at 100°. The next instruction is a goto to the 67.8 kHz is gated by the rangefinder Such errors are too large. They’re main loop. (Refer to the vbucc.bas file output, the number of clock pulses sent eliminated by the PIC12F683 and posted on the Circuit Cellar FTP site.) to the PIC18F2320 represents the range LM335A by measuring the ambient The main loop first resets the flip-flop to the target in 0.1″ increments. temperature and adjusting the control pin. It then begins to process the For example, consider a distance of PIC12F683’s PWM output. video, trigger the range coprocessor, and 16″. The rangefinder will have a pulse When the system is on, the ’12F683’s act on switch closures. The loop decre- width of 2.36 ms. Multiplying that by ADC reads the voltage on the LM335A, ments the line count, which starts at the oscillator frequency of 67,800 yields calculates the difference between the 255, and checks if the current line count a count of 160, or 160 tenths of an inch. ADC reading and the count at –40° is on the screen (no lines before line 21 This count represents the scan line (477), and looks up a number to use in are displayed in the NTSC format). If it where the range line will be placed in the PR2 register to set the PWM fre- is and the display is enabled, the text rep- the video stream and also used for the quency. From that point on, the PWM resenting the backing situation (TRCK, distance display. Note that 67.8 kHz is block outputs a frequency that’s pro- BOAT, TRLR, and BACK) and the dis- about right for 72°, but it isn’t right for portional to temperature. tance are displayed by the SendText any other temperature. The speed subroutine. Before SendText of sound changes a lot with tem- can do its work, the data must perature, and these changes must Init be prepared by two other sub- be accounted for. routines in vloop: DistText and GetDots. This is one area Read UP TO SPEED EEPROM where assembly code is needed. The speed of sound in a gas vloop Reset varies with the temperature: Display Y ASSEMBLY REQUIRED *VSYNC Y line DistText distance? Low? count Four arrays are for text display: γ S = 3.28 RT N N text[], dots[], textbuff[],

Clock and vidram[]. text[] contains endloop GetDots where S is the speed of sound in FF numbers that represent the letters feet per second, γ is the specific of the text for a given selection. Main Reset Time to Y heat ratio (1.4 for air), R is the uni- loop FF dots[] contains the dot pattern versal gas constant (286 m2/s2/°K), PING? for each character to be displayed. and T is the temperature in Y textbuff[] contains the char- N Display Read kelvin (273.15 + °C). I used this on? current acters that will be displayed. WWW.GiURUMELE.Hi2.ROdistance equation in an Excel spread- Y vidram[] is the video RAM that sheet to calculate the speed of Trigger holds the dots to be displayed. Display N PING sound in air for temperatures text? The text for display is made ranging from –40° to 120° (see Y up of 11 characters with an 8 × 7 Table 1). Process matrix. The first four characters switches For the Backer Upper, a prac- Sendtext make up the text. The next two tical temperature range is 32° to are spaces. The remaining char- 100° for hook-up activities. Draw acters make up the distance. (Don and I once hooked up at lines The contents of textbuff[] 37°, so 32° isn’t so farfetched). Figure 3—Here you see a simplified depiction of a complex combination are numbers that represent the S is 1,085.8′ per second and of PICBASIC and assembly code. position in the dots[] array.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 67 When a selection is made, the text determines where the byte of data must constantly sends its PWM output to for the selection is copied from the be placed in the vidram[] array. The the PIC18F2320. If the PIC18F2320 text[] array into the first 4 bytes of byte is stored in that location. All this isn’t clocking, how can it measure the textbuff[]. For example, if TRCK is is done using the PIC18F2320’s Indirect coprocessor’s PWM signal? selected, the text[] elements for Addressing mode, which uses pointers It turns out that the PIC18F2320’s TRCK (25, 24, 27, and 19) will be to address memory rather than defined Timer1 (TMR1) continues to count copied into textbuff[]. (Refer to the memory locations. This is done for each while it isn’t being clocked if it’s con- text led.bas file posted on the Circuit dot row in every character. After the figured as an asynchronous counter. Cellar FTP site.) video RAM has been populated with all During vertical synchronization, the The DistText subroutine determines the dots needed to display characters, TMR1 registers are read and corrected distance. Recall that the distance is the program moves on to display the for the set point and stored in a variable determined by gating the coprocessor text at the top of the screen. used to determine the scan line on PWM block, where each count equals The SendText subroutine is called which the range line should be placed. 0.1″. The PIC18F2320 converts this seven times when the display is enabled The rangefinder is triggered after this. count to the format for display. There and the scan line count reaches the Because the *VSYNC pin goes active are three thresholds used to determine twenty-fifth line. It steps through the 60 times per second, it would cause rapid the distance display format. Dashes video RAM, retrieves the byte of dots fluctuations in the distance indication if are displayed if the distance is greater stored there using indirect addressing, the rangefinder distance varies slightly than 10′. Between 10′ and 2′, the dis- and writes that byte to port C. between samples. The *CSYNC pulses tance is displayed in feet. Below 2′, the Bit 7 is used for the video overlay data. are counted while the *VSYNC pin is distance is displayed in inches. A high is white on the monitor. The dots active. The coprocessor is triggered The pulses sent to the PIC18F2320 are clocked out with the PIC18F2320’s when six pulses occur. This amounts to are tested for the aforementioned con- rotate left no carry (RLNCF) command to 10 pings per second. Following this, the ditions. If the distance is between 2′ and rotate the bits out, which happens at a switches are scanned for closure and 10′, the count is divided by 12, which rate of 1 bit per 200 ns. After one row of action is taken accordingly. The end- yields an 8-bit value that represents dots is clocked out (there are 88 on each loop loop is the last thing that happens. tenths of feet. If the distance is less row), the PIC18F2320 steps down to the The PIC18F2320 clocks the flip-flop, its than 2′, the division is skipped and the next row and continues. This is done for clock stops, and it stands ready to go DistText subroutine continues to the every remaining row of text. back to vloop when the flip-flop is set at next part of its operation. At that point, From here the code displays the ver- the next *CSYNC pulse. a variable contains an 8-bit value that tical and horizontal lines. The vertical The user interface involves switches, represents either distance in feet or line is fixed, the set point line is fixed, so debouncing is necessary. Debouncing distance in inches, each in one-tenth and the range line moves and is set is normally achieved by introducing a increments. The 8-bit value now goes based on the distance to the target. The short delay after the PIC detects switch through a conversion (binary to binary code is a combination of PICBASIC and closure. This works pretty well. coded decimal) that generates three assembly. The latter is for fine-tuning However, I found that when the timing numbers that represent the codes for the line position that PICBASIC won’t was tight, there was flicker in the video the text display subroutine. allow. Lines are drawn by turning on after a switch was pressed. The minor When the distance has been deter- the video line for specific times after a flicker was short-lived, but I wanted the mined, the numerical codes for each preset delay from the beginning of a video to remain solid after pressing a key. digit are put in positions 6, 7, and 9 of scan line, and then turning them off To debounce the switches, I used the textbuff[]. Position 8 always has after another preset delay. same technique that I used to control the decimal point code (12). Position 10 After a given scan line for the indicator the rangefinder and counted the number has the code for either an inch or foot lines is displayed, the code branches to of vertical sync pulses. When a switch is mark (13 or 14). When it’s time to vloop to check for the *VSYNC pin pressed, a flag (KeyFlag) is set and all display the text, the information in (another EL1881 output that indicates other key presses are ignored until textbuff[] isWWW.GiURUMELE.Hi2.RO used to populate the the vertical sync of the composite 10 vertical sync pulses are counted. video RAM. The video RAM is loaded video signal), trigger the coprocessor, After the tenth sync pulse, the flag with the binary representation for the and act on a switch closure. If the clears and more key presses are dots needed to display a given row of *VSYNC pin is active, the line count is allowed. This technique is tied to the all 11 characters. The GetDots sub- reset, the current range coprocessor vertical sync pulses, so it effectively routine does this. count is retrieved, and a check is made debounces switch closure without In the GetDots subroutine, the to see if the rangefinder should be trig- causing the video to jump. PIC18F2320 gets the character code from gered. It’s all done that order. textbuff[], performs a calculation to One of the disadvantages of stopping COPROCESSOR determine the location of the character’s the PIC18F2320’s clock is that it can’t After the coprocessor initializes dots in the dots[] array, and retrieves directly read the rangefinder’s pulse variables and configures the ADC, the that byte of data. Another calculation width. The rangefinder coprocessor ADC reads the temperature from the

68 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com LM335A (see Figure 4). Following this, was doing research for this project, I came across a circuit he had built years 477 is subtracted from the ADC value, Init Trigger PING which gives an 8-bit offset from a base ago. His Video Clock Superimposer is temperature of –40°. This offset is Delay equal to approximately based on a phase-locked loop to genlock 300 ms to let the master N the video and a PIC for timekeeping and used to look up the value for the PR2 PIC stabilize PING output high? register, which sets the PWM block’s video overlay functions. I used a differ- Y frequency. You may download the Read temperature ent approach (I had terrible luck with via ADC code from the Circuit Cellar FTP site Start PWM the PLL, which is a superior way of gen- block (butempcomp1.asm). locking video), but I thank him for his Calculate offset ideas and encouragement. How the speed of sound and ulti- from –40° PING N mately the PWM frequency vary with output low? temperature is nearly linear between Look up PR2 Victor Lick first started working with setting and setup Y –40° and 120°, but it isn’t linear PWM block electronics in 1976 when he main- Stop PWM enough. At 50°, for example, the error block tained the reactor control electronics between the actual curve and the lin- on a nuclear submarine. The first ear approximation is 0.5%. That isn’t N Trigger from Y project he ever built was a digital gas master PIC high? much, but it contributes to the error gauge for his car in 1978. Most of his already present because of the integer current projects involve PIC micro- control of the PWM frequency. Figure 4—The range coprocessor code is a simple controllers. You may contact Victor at In the interest of accuracy, I used a loop that spends most of its time waiting. The code is [email protected]. look-up table based on the actual curve to written in PIC assembly code. convert the ADC count to the PR2 value. The PWM block was set up using the will eventually be a vehicle informa- PROJECT FILES value from the look-up table. The PWM tion center (VIC). Yes, it’s called a To download the code and additional block is set up using the value from the “VIC.” I plan to incorporate tempera- files, go to ftp://ftp.circuitcellar.com look-up table. Timer2 is cleared, and the ture sensors on the trailer hubs (I don’t /pub/Circuit_Cellar/2006/186. PIC12F683 entered a new main loop. want them overheating on a 6% The main loop spends most of its grade), wireless tire pressure indica- time waiting for the trigger from the tors, exterior lighting alerts, and any- RESOURCES PIC18F2320. When the PIC18F2320 thing else that may prove useful. All Intersil Corp., “EL1881,” FN7018.1, asserts a high, the PIC12F683 triggers of this will feed into the video system October 20, 2004. the rangefinder by sending a 5-µs for display. Of course, I’ll install a sec- E. Pasahow, Electronics Pocket pulse. Because the rangefinder uses the ond camera (probably wireless) on the Reference, McGraw-Hill, New York, same line for its trigger and output, the back of the trailer along with a NY 1999. PIC12F683 reconfigures the rangefinder PING))) rangefinder. trigger pin as an input and waits for the Displaying on-board diagnostic (OBD) Parallax, Inc., “PING Ultrasonic rangefinder to send a high. The high data would also be useful. Data like Range Finder (#28015),” June 2005. indicates the beginning of the timing engine speed and fuel economy could pulse. When the high is received, TMR2 be displayed on the monitor. Color starts and the PWM block outputs the would be nice too, but that’s some- SOURCES desired frequency. While the PWM thing for another time because it’s EL1881 video sync separator block is running, the PIC18F2320 such a complicated process. I’ll also Intersil Corp. counts its pulses using its TMR1. make the temperature compensation www.intersil.com At this point, the PIC12F683 is waiting continuous by using a VCO instead of PIC12F683 and PIC18F2320 for the rangefinder to end its timing cycle, the PIC12F683’s PWM block. Microcontrollers which is indicated by a low on its output. I may also let the coprocessor perform Microchip Technology, Inc. When the low occurs, the PIC12F683 the distance conversion and transmit WWW.GiURUMELE.Hi2.ROwww.microchip.com stops TMR2 and clears it for another run. the length of the vertical line and the The PWM block stops running and no distance serially. This will reduce pro- PICBASIC Pro 2.44 additional pulses are sent to the cessing overhead on the PIC18F2320 MicroEngineering Labs, Inc. PIC18F2320. The number of sent pulses and make the rangefinder data trans- www.melabs.com represents the distance to the target in mission more suitable to multiplexing LM335A Temperature sensor tenths of an inch or tenths of a foot. with other sensors, which will National Semiconductor Corp. undoubtedly have their own format. I www.national.com UPGRADES may tackle that in the next version. I The Backer Upper works well in its PING))) Ultrasonic rangefinder current configuration. The video over- Author’s note: I’d like to thank Dave Parallax, Inc. lay system will be the core of what Thomas (dt.prohosting.com). When I www.parallax.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 69 SILICON UPDATE by Tom Cantrell

Hot Enough for You? Once again, Tom was our eyes and ears at the annual Hot Chips conference in Silicon Valley. This month he reports on the proceedings and covers such hot topics as power density crises and parallelism.

The weather in Silicon Valley was Power Virus software, the latest PC uber- trying to avoid meltdown while cram- milder than usual, but the chips were chips all include thermal shutdown ming ever more and ever faster transis- hotter than ever at this year’s Hot safety features. I do keep a fire extin- tors into an ever-smaller space. Chips conference. When the conference guisher handy. The other crisis is an energy crisis first started long ago (this was the sev- Reflecting widespread angst over the (power × time) that affects any chip enteenth get-together), “Hot” was used subject in the chip design community, that’s hooked to a battery, said battery in the marketing sense of the word (i.e., both a half-day tutorial and a keynote being invariably too short-lived and the latest and the greatest). But over the address were devoted to the power cri- prone to running out of gas at the years as the number of transistors has sis. As you’ll see, it’s a subject that most inopportune moment. I’m sure marched onward and upward, the label will and indeed must affect all levels Steve Ciarcia’s October 2005 editorial has indirectly taken on a literal mean- of system design from transistors all titled “11-lb. Bricks” on the subject ing (i.e., chips that glow in the dark). the way up through racks and stacks. struck a chord with many designers, The meaning of “Hot” may have Both the tutorial by a team from IBM such as those at Apple now swallow- morphed a bit, but thankfully the recipe and the keynote address by a speaker ing the bitter fruit of having to offer for the conference itself hasn’t. It’s a from Intel were basically on the same free battery replacements for iPods. welcome opportunity to forget your wavelength.[1, 2] These folks know of From a real-world perspective, the mundane day-to-day design challenges what they speak, so take heed. problem (not the only one though) at the and contemplate the future. I relish Start by recognizing that the power high end is that power density issues sharing the good company of like-mind- “crisis” is really two separate but limit performance while low-end and ed experts and enthusiasts, not to men- related crises. First is the power density mid-range systems struggle with battery tion the amenities that can’t be beat crisis (i.e., the aforementioned melting cost, size, and longevity. For both crises, (the Stanford University location and motherboards) that’s becoming a limiter the root cause is the same, namely that catered meals). Put it all together and for big chips. It’s simply the dilemma of the easy way out has already been taken that’s why Hot Chips will stay on my and new solutions are required. calendar until all those 100-W-plus Historically, the power problem was chips freeze over. While I’m on the sub- held at bay by the march of Moore’s law. ject, let’s get started with an update on Typically, designers were primarily con- the power problems threatening tomor- Relative cerned with maximizing performance. row’s too-hot chips. power They took whatever power cards they were dealt as a result. Shrinking the WATTS UP WWW.GiURUMELE.Hi2.ROtransistors and reducing the operating Your motherboard melts when you try to voltage largely offset the increase in den- send a fax sity, meaning the power problem fixed 90-nm

Where’d you get your CPU, in a box of 130 nm itself. However, that’s no longer the case.

Cracker Jacks? process only Process plus Power supply and threshold voltages can efficiency, and efficiency, Process, design Process, Next-generation —Weird Al Yankovic, “It’s All About the design efficiency product if 130 nm be reduced only so far. And with each frequency increase Pentiums,” Running with Scissors, Volcano, 1999. new generation of chips, current con- Figure 1—As this figure from Intel shows, simply mov- sumption (dynamic and leakage) is on ing to a new process and cutting voltage no longer We’re not quite to the point of melting a seemingly inexorable upward trend. automatically fixes the power problem. Future parts motherboards. But that’s only because must be specifically designed with power as a basic It’s a reality of the human condition facing the threat of hot-spot-inducing consideration from the start, not an afterthought. that things don’t get fixed until there’s

70 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com a crisis. The bad news is that the power sive single-core, test- problem doesn’t fix itself anymore. The and-manufacturing good news is that now the wizards rec- know-how already in ognize this fact and are, albeit reluc- place. That’s because tantly, taking steps to fix it themselves. screening (i.e., speed Changing what gets built starts with grade) and testing the changing the building tools. The ball is dual-core part is con- in EDA (i.e., chip design) software’s ceptually little differ- court to upgrade with more sophisticated ent than testing two power estimation and thermal simula- single-core parts. tion features. But the buck doesn’t Not that there stop there. As well, system architects weren’t some gotchas and application designers have to do to overcome. For their part by considering the power example, the current implications of their decisions (see PC thermal manage- Figure 1). ment regime only For example, it’s thought-provoking provides for a single Photo 1—Floor a hot rod when the light turns green and you’ll probably just to consider how much energy is wasted thermometer (i.e., burn rubber. The same goes for hot-rod ICs. Here, booting a dual-core Pentium at full speed causes a marginal PC power supply hiccup (see the sag below (alternatively, excess heat generated) single diode and spec (black trace)). by the myriad speculative aspects of ADC). But depending bleeding-edge CPU architectures. Does on the workload and fetching and executing far into the the relative utilization of each core, a the main memory. This causes con- future down both paths of a condition- dual-core design has possible thermal gestion on the shared bus. al branch make sense knowing full interactions that aren’t as easy to pin Look to the next-generation Paxville well that half the work is for naught? down as a single-core hot spot. as a clean-sheet, dual-core design. It also turns out that powering up Besides being a truly monolithic die, CORE WARS two cores, especially retrofitted into a the L2 cache for each core is boosted While your computer’s crashin’, mine’s box designed for a single core, causes a to 2 MB and the bus consolidated on- multitaskin’ current surge that’s more than some chip, making for a faster and less con- It does all my work without me even askin’ commodity “silver box” power supplies gested main memory bus. —Yankovic can handle (see Photo 1). This required Furthermore, expect thermal man- a BIOS change to tell the CPUs to boot agement to get much more sophisticat- Get with it, Weird Al. Your computer up at low voltage/speed and then accel- ed using techniques outlined in Intel’s may be multitasking, but mine is erate with a light foot on the gas pedal. “Foxton” presentation.[4] It’s a scheme multithreading. And judging by the The good news is that the single- that uses a dedicated on-chip microcon- lineup of multi-core chips at the con- core design was already multiproces- troller to optimally monitor and man- ference, it won’t be long before we’re sor-capable, so the dual-core version is age power, temperature, and frequency. all multiprocessing. just a monolithic equivalent of a two- Foxton further recognizes the distinc- Having reached the limit of single- processor motherboard. The bad news tion between electrical power and ther- core design, and some would argue that is that the two loads on the bus slow mal power specifications. The former Itanium even goes a pipeline stage too things down. Furthermore, the mere dictates the peak the power supply far, Intel described its dual-core strate- 1 MB of L2 cache on the single core must be capable of delivering. The lat- gy.[3] To its credit, Intel candidly admit- means too much traffic needs to get to ter deals with dissipating the heat asso- ted the design of its cur- ciated with the average rent dual-core Pentium 4 power consumed. DVD (SATA) CPU I/0 8xx series was a bit of a Chip HDD port (SATA) Intel is on the march Core0 Core1 Core2 time-to-market-drivenWWW.GiURUMELE.Hi2.ROFront controllers (two USB) with two cores, but fire drill. It looks like a L1D L1I L1D L1I L1D L1I Wireless controllers they’d better watch out single chip, but it’s actu- MU ports (two USB) or they’ll fall behind the 1 MB L2 der ally just two existing Rear panel USB gamers judging by presen- Ethernet single-core P4 die GPU tations from Microsoft Memory Bus interface unit/ IR I/O interface Deco XMA [5, 6] stitched together on a Audio out and IBM. The multichip module. The 512-MB MC1 Flash memory Microsoft Xbox 360 ups DRAM

3D Core SMC two-chips-in-one System control the ante with three

MC0 10-MB Video Analog approach enabled them Video out 3.2-GHz PowerPC cores EDRAM chip to drop into the existing out on a single chip (see socket footprint and take Figure 2—No better proof that the Core War is coming than the Microsoft Xbox 360. It relies on a Figure 2). The cores share advantage of the exten- CPU chip that contains three PowerPC processors. a 1-MB L2 cache that’s

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 71 tightly coupled to the 500-MHz, 4-bil- parallelism inher- lion-pixels-per-second graphics-pro- ent in the work- cessing unit (GPU). Note that 512 MB load. of DRAM and a kitchen sink (every- Rather, the thing but) I/O chip round out this Achilles heels for all supercomputer in drag. parallel processing Meanwhile, the Cell processor schemes are data designed by a partnership of Sony, dependencies and Toshiba, and IBM wins the core wars I/O that characterize by taking a slightly different tack (see the mundane appli- Photo 2). It combines one big-iron cations the average PowerPC CPU with eight (count ’em, user spends most eight) synergistic processor elements. time with. After all, The SPEs themselves are register-rich you can’t spell- Photo 2—The Cell microprocessor in Sony’s next-generation Playstation adopts (128 × 128 bits) RISC hammers that check a word before multicore with a vengeance in the form of eight mini-me Synergistic Processor Units. pound vector nails (i.e., even simple it’s typed in. And scalar operations are treated as vectors speaking of booting up, do you think anything more daunting than a speed of length 1). It’s all pretty complicated. multiple cores somehow make the bump and shopping bag. But a four- I just think of it as a 200 Gflop Cray disk spin faster? wheel-drive vehicle typically costs (i.e., vector processor) on a chip. The Ideally, the compiler would take more, weighs more, gets worse fact it’s in a toy just says you’ve come care of the heavy lifting (i.e., convert- mileage, is more complicated and a real long way, baby. ing the programmers sequential expensive to fix, and is slower than a thought process into an optimally par- two-wheel drive equivalent. The lesson PARALLELISM EVERYWHERE allel program). Techniques such as is that value in a consumer’s mind is You’re usin’ a 286? Don’t make me laugh software pipelining and moving code as much about heart (i.e., emotion) as Your Windows boots up in what, a day around to enlarge basic blocks and head (i.e., reason). and a half? avoid dependencies are designed to do The question isn’t whether a two-, —Yankovic just that. However, it turns out that three-, or N-core processor makes there are some really hard problems, sense or if you really need it. The only The good news is that multiple, such as aliasing (foretelling at compile question is whether or not you desire simpler cores theoretically offer the time where a pointer will point at it and have the ability to pay. Core opportunity to deliver more MIPS for runtime), that limit the ability of the wars? Bring ’em on! less watts and dollars than an exces- compiler to take care of everything sively baroque and bloaty single core. “automagically.” INCREDIBLE SHRINKING VIDEO But the keyword is “theoretically.” If Kirk concludes that the only solu- Got a flat-screen monitor 40 inches wide you think dropping two, three, or four tion is for programmers to think paral- I believe that yours says Etch-a-Sketch on cores on a chip will get the job done lel with an assist from industry and the side two, three, or four times faster, respec- academia in the form of better tools —Yankovic tively, prepare to be disappointed. and training. Otherwise, he fears that Rubbing our collective noses in the the avalanche of emerging multicore Did I just imagine a whiff of Kirk bad news was David Kirk of NVIDIA processors won’t deliver value that gloating over the fact his company’s with his presentation, “Do We Have lives up to user expectations. graphics chips easily exploit the par- More Parallelism Than We Can I tend to agree that asking program- allelism inherent in that application? Handle?”[7] mers to do more, and do it more clev- Not really mean-spirited gloating, The quest to identify, extract, and erly, is called for. Yes, it’s a last resort, but more like the “glad it’s not me” exploit parallelism isn’t new, easy, or but the automagic schemes seem pret- feeling you get driving past a car over. Yes, greatWWW.GiURUMELE.Hi2.RO progress has been ty tapped out. Coincidentally, I see my wreck. made, at least for so-called “trivially e-mail in-basket has an announcement It’s true that screen-centric applica- parallelizable” applications where for an ACM symposium on the tions on everything from a cell phone the work is amenable to partitioning. “Principles and Practice of Parallel to a home theater are well served by Tasks such as graphics processing Programming” (www.ppopp.org). the march of silicon. But it’s no cake- (e.g., MPEG) and physical modeling But unlike Kirk, I’m not so sure that walk because the lust for prettier pic- and simulation (e.g., weather predic- users won’t succumb to the lure of the tures seems insatiable. tion) are well served by single- latest and greatest hype for multicore For example, take the upcoming instruction, multiple-data (SIMD) processors. Next time you’re down at H.264 video compression standard. I designs (vector processors). Along your local shopping mall, check out like to think of it as “MPEG the with their vectorizing compilers, how many folks drive four-wheel- Sequel.” From 50,000′, H.264’s goal they do a good job of exploiting the drive behemoths that never deal with is pretty simple: deliver ever-higher

72 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com definition video without gate-level pipeline triggers A(AND) demanding more band- Y(AND) CK(AND) (see Figure 3). Yes, 4°K is a B(AND) A(AND) 1 width. Easier said than CK(AND) bit of a trick here on earth, done. B(AND) 1 but maybe such chips will 1 A(OR) Y(AND) The heavy lifting Y(OR) find a home in the inter- B(OR) required for tasks like CK(OR) stellar space market, where CK(OR) motion estimation and the A(OR) 1 the average temperature new context-based adaptive B(OR) 0 (2.735°K) is just right. binary arithmetic coding Y(OR) 1 (CABAC) compression LIGHT MAKES RIGHT scheme suck MIPS like Your database is a disaster Figure 3—Superconducting Josephson Junction circuits mean that even a cold chip there’s no tomorrow. H.264 You’re waxin’ your modem, can be hot. At 4°K, a wire turns into a pipeline for pulse-driven logic. is said to be at least 4× as tryin’ to make it go faster computationally intensive —Yankovic as MPEG-2. Fortunately, thanks to the buy a car that can go 1,000 mph. parallelism inherent in pixel process- Developed by a team of Japanese Suffered through any slow I-Way ing, the solution is amenable to the researchers, this 40-GHz technology downloads lately? Join the crowd. brute-force solution of throwing more isn’t some super-pipelined pipe Waxing your modem is one option, cores at the problem. dream.[9] In fact, the first devices have but a better idea comes from Luxtera The Telarity-1 H.264 real-time, already been successfully fabricated in the form of technology (CMOS high-definition video encoder well and tested. photonics) that combines the net- applies lessons first taught in the days But there’s no need to rush off to working speed of optical with the of Cray.[8] It combines five identical the PC recycle center just yet. So far, manufacturability, low-cost, and relia- processor cores on a single chip, each these rocket chips are small-scale, bility of CMOS.[10] core comprised of four independent such as a 4-bit microcontroller, 4 × 4 While the huddled masses get by vector pipelines for a total sustained crossbar switch, or the subject of this with 10/100 Ethernet, the larger chip performance of 55.5 GOPS per year’s presentation—a four-channel, enterprise and infrastructure installa- second. Even so, it takes four chips to round-robin arbiter/scheduler. Oh tions are quickly headed to 1 Gbps, get the job done. yeah, there’s one other little gotcha. 10 Gbps, and beyond. Bandwidth is For now, an H.264 real-time Relying on superconducting Josephson like love and money: you can never encoder is very expensive and pretty Junction circuits, the parts require have enough. much something only a TV station or some rather active cooling indeed, as According to Luxtera, our good old cable company can afford. But thanks in down to around 4°K! copper (twisted pair) is fine for 1 G, to the easily exploited parallelism of As the name implies, superconduc- but 10 G will be pushing it. Beyond the application, the migration path tors enable lossless (i.e., no resistance) that, optical is the way to go (see (more cores per chip) is easy to see. I pulse transmission. To exploit that Figure 4). figure it’s only a matter of time before phenomenon, the researchers use a Of course, optical networking is H.264 makes it’s way into consumer novel pulse-driven logic in which the here now, but it typically requires gear such as digital camcorders. wire itself becomes a pipeline and laser transceivers built with esoteric gates store the results (also pulses) of processes lashed together with con- DUDE, THAT’S COLD their logic operations until released by ventional IC (i.e., CMOS) controllers. You think your Commodore 64 Furthermore, designs that is really neato modulate the laser direct- What kinda chip you got in ly have reliability con- Enterprise > there, a Dorito? distance: 0.1–10 km 10G _ 40G cerns. Imagine switching —Yankovic Optical an incandescent light bulb on and off relentlessly. WWW.GiURUMELE.Hi2.RORack-to-rack 3.125G 10G 40G So you think you’re distance: 1–100 m Light bulbs have been super-duper PC is really known to burn for years neato, toddling along at a and even decades if left Board-to-board 3.125G 6.25G 10G 20G mere 1 GHz or two? distance: 50–100 cm alone, but it’s no surprise Well, how about a chip that when they do fail it’s Electrical Transition that hits 40 GHz when Chip-to-chip usually during power-up. you floor it? Mileage rat- distance: 5–50 cm 3.125G 6.25G 10G 15–20G Luxtera has come up ings, insurance costs, 2004 2006 2008 2010 2012 with a way to fabricate and the average citizen’s the optics and controllers Figure 4—According to Luxtera, 10 Gbps is the tipping point at which optical networks driving skills aside, replace copper, ultimately migrating from the enterprise level into boxes and even onto on the same die using imagine being able to boards (chip to chip). (Source: Intel and silicon vendors) semi-conventional fab

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 73 WWW.GiURUMELE.Hi2.RO processing. The lasers are still sepa- gates, and the analog-to-digital com- For now, multi-core is both the rate, but they’re flip-chip bonded to parison worsens with each new gener- answer and the question (i.e., how to the CMOS controller die, making for a ation of fab process (see Figure 5). effectively exploit parallelism). The virtual single-chip solution. In addi- That raises the question, Is there a Core War chips are coming in any tion, silicon modulators handle the way to trade-off some ever-cheaper, case, which is the first step in figuring switching so the lasers themselves are ever-lower power digital gates to come out how to use them. No doubt there left powered up, which is helpful for to the aid of analog? Just as DSP fil- will be some answers, and new ques- reliability. Another benefit of CMOS ters now replace the op-amps of yore, tions, at next year’s conference. I photonics is that silicon optical filters the answer is yes. are electrically tunable to allow pack- The idea is to drop back to a sloppy Tom Cantrell has been working on ing multiple logical channels (i.e., ADC that is cheaper and lower power chip, board, and systems design and wavelength division multiplexing) on and use some digital processing to marketing for several years. You may a single optical fiber. One key ingredi- make up the difference. For instance, reach him by e-mail at tom.cantrell@ ent in Luxtera’s secret sauce is the you can replace the precision linear circuitcellar.com. exact way they mate the relatively gain amplifier at the core of an ADC large fiber to the tiny transistors, a chip with a simple open-loop, nonlin- trick they’re keeping under wraps for ear amplifier and use a mini-me DSP REFERENCES the time being. to dynamically compensate in real- [1] K. Nowka, P. Bose, and S. Nassif, time. “Low Power, High Performance ANALOG, THE FINAL FRONTIER The authors have performed tests Microprocessor Design,” IBM, Hot In a 32-bit world, you’re a 2-bit user using a modified commercial ADC Chips 17, 2005. You’ve got your own newsgroup, alt.total- (i.e., precision amplifier replaced with [2] W. Holt, “Facing the Hot Chip loser a sloppy one) combined with an off-chip Challenge (Again),” Intel Corp., —Yankovic digital assist processor. Even for this Hot Chips 17, 2005. admittedly non-best-case prototype, [3] J. Douglas, “Intel 8xx Series and More bits are all well and good, but they found the two-thirds reduction in Paxville Xeon-MP Microprocessors,” sometimes all it takes is a few of them amplifier power (from more than 50 mW Intel Corp., Hot Chips 17, 2005. to tip the balance. I was impressed by to 20 mW) more than offset extra [4] S. Naffziger, “Foxton Technology,” a presentation that demonstrated how power (10 mW) required for the digital Intel Corp., Hot Chips 17, 2005. some ones and zeros can make a dif- assist. They envision that the tech- [5] J. Andrews and N. Baker, “Xbox 360 ference in the form of digitally assist- nique can be extended for even more System Architecture,” Microsoft ed analog circuits.[11] advantage, perhaps as much as a 100× Corp., Hot Chips 17, 2005. The premise starts with the observa- reduction in the energy per conver- [6] M. Gschwind et al., “A Novel tion that Moore’s law has worked a lot sion. Better yet, unlike traditional SIMD Architecture for the Cell better for digital than for analog cir- analog circuits, the advantage of rely- Heterogeneous Chip-Multiprocessor,” cuits. With the emphasis on power ing on a digital assistant will grow as IBM, Hot Chips 17, 2005. reduction, an interesting way to look silicon marches on. [7] D. Kirk, “Multiple Cores, Multiple at the issue is to consider the energy- Pipes, Multiple Threads: Do We equivalent number of gates for an ana- SO MANY CHIPS, SO LITTLE TIME Have More Parallelism Than We log-to-digital conversion. It turns out As usual, I came away from Hot Can Handle?,” Hot Chips 17, 2005. that an ADC consumes enough power Chips with a better understanding of [8] R. Dickson, “Telarity-1: A Real to toggle hundreds of thousands of the challenges ahead, but I was Time H.264 High Definition Video inspired by the enthusi- Architecture,” Hot Chips 17, 2005. asm and expertise being [9] Y. Kameda et al., “40-GHz brought to bear. Yes, for Operation of a Single-Flux- 500,000 the long term, the ostensi- Quantum (SFQ) Switch Scheduler,” ADC 400,000 ble end of Moore’s law Hot Chips 17, 2005. Resolution: WWW.GiURUMELE.Hi2.RO 6 bits 300,000 (the wall) looms. But [10] C. Gunn, “CMOS Photonics 8 bits that’s kind of like worry- Technology Enabling Optical 10 bits 200,000 12 bits ing about the sun burning Interconnects,” Hot Chips 17, 14 bits 100,000 out. Today’s challenge 2005. 16 bits isn’t putting more transis- [11] B. Murmann, “Digitally Assisted 0

0.8 0.6 0.4 0.2 0.0 of gates number Energy equivalent tors on a chip (caveat: Analog Circuits,” Hot Chips 17, Feature size (micron) designing, verifying, and 2005. cooling them is), but Figure 5—Analog circuits haven’t enjoyed the free ride Moore’s law has rather about crafting given to digital. That fact leads to the strategy of digital assist (i.e., using RESOURCE some of the ever-cheaper ones and zeros to cut the cost and power of architectures that best analog). use them. Hot Chips 17, www.hotchips.org

CIRCUIT CELLAR® www.circuitcellar.com Issue 186 January 2006 75 FROM THE BENCH by Jeff Bachiochi

Regulator Review New regulator modules are in line to replace trusty old 1-A linear regulators. Are you ready to bring these newbies to your bench? Read on for Jeff’s comprehensive review.

Do I need multilevel bristles? Of course, this all depends on the appli- the best conductor for heat transfer. The Opposing cantilevers? An efficient cation. Will there be any savings with recipient of this heat may be the PCB angled handle with a rubber-cushioned the reduced power requirement? Can the via soldered connections or some kind handgrip? Is it effective to have motor- design benefit from producing less heat? of heatsink attached to the substrate. ized seesaw action, a circular spin, or Does the present configuration offer any The purpose here is to provide a ther- alternating rows of scrubbers? headroom for future additional loads? mal path for the heat to get out of the The fact is that toothbrush improve- device as fast as possible. When creating ments aren’t responsible for the largest KILLER HEAT a thermal path between substrate and single improvement in dental care. It’s As you know, heat is a killer of elec- heatsink, thermal grease (a crack-filler) fluoride! Even toothpaste suffers from tronics. In fact, above average temper- should be used to improve the thermal product development overkill, but atures can even shorten the life span of bridge between the two materials. that’s the American way. things like plastics. They can dry out Because you don’t generally attach More is better in the competition for and become brittle from continued an infinite heatsink to a semiconductor market share. A better mousetrap, the exposure to heat. Electronic circuits device, conduction only spreads out the padded toilet seat, the cell phone with a can become mechanically stressed by heat produced by the device. The second camera: they’re all the same. We strive repeated temperature cycling. So, you method of heat dissipation, convection, to make every product better. And so best either get rid of the heat or keep it takes over at this point. Convection is it is too in the component market. The from being generated in the first place. based on the use of a fluid passing over ruggedly simple linear regulator has Heat is dissipated from semiconductors a surface and carrying away the heat. competition from those digital guys. in a combination of three ways: conduc- Although there are some using water- No, they’re not new. But manufacturers tion, convection, and radiation. The cooled semiconductors, air is an easier are beginning to offer switching mod- majority of heat is transferred via conduc- (yet less efficient) way to carry off heat. ules as direct replacements for the tion through the surrounding material. Convection currents of less than trusty 1-A linear regulator. Let’s take a This may be metal, plastic, water, or air. 60 linear feet per minute (LFM) are con- look at how these contenders stack up Each material has a rate of thermal con- sidered free air convection. Otherwise, against the champ (see Photo 1, p. 79). ductivity (i.e., how well it transfers heat). the airflow is created by artificial means, Aluminum has a thermal conductiv- as with a fan (forced air convection). PHYSICALLY CHALLENGED ity rating of 205 W/m°K, while air is Heat transfer via convection is directly Texas Instruments’s PT5100 series 0.026 W/m°K. That means heat flows related to velocity as well as the differen- 1-A positive step-down integrated through aluminum approximately tial in the temperature between the air switching regulator (ISR) offers a pin- 8,000 times better than it does through and surface. Forced air in a closed system compatible, three-terminalWWW.GiURUMELE.Hi2.RO regulator in air. No wonder stirring hot soup with relies on convection to transfer the heat a module package that looks like a TO- a metal spoon isn’t much different from the air to the system, and it’s gener- 220 device with heatsink. This enables than sticking your hand in the pot. The ally inadequate. Therefore, a free flow of it to directly drop into a PCB laid out cross section of the spoon has a great external air allows the greatest differen- for a linear regulator with a heatsink. deal to do with how well the heat is tial and ensures that the dump of heat is The PT51xx offers improved power transferred up the handle. On the other external to the system. supply efficiency, reduced heat dissipa- hand, wood is close to air in thermal The last mode of heat transfer is from tion, and current-limiting and thermal conductivity and will enable you to stir radiation. This form of heat transfer shutdown protection. The single-part the hot soup with little transfer of heat requires no medium for transfer to take cost for a PT51xx runs about $12. This to the handle. So it’s easy to see that the place. (The sun transfers heat through the doesn’t seem like competition for the $2 metal legs (or an exposed metal sub- vacuum of space.) A campfire is a good linear regulator/heatsink combination. strate) of a semiconductor device make radiator of electromagnetic waves, espe-

76 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com cially in the infrared spectrum. On winter radiate approximately 2 W of power The PT5101 5-VDC integrated camping trips, members of my Boy Scout with no heatsink under ideal conditions. switching regulator uses switching troop frequently turn their bodies to But who would design for ideal condi- techniques to improve the efficiency expose a different side to the campfire. tions at maximum temperature ratings? of the conversion and regulation, thus This helps spread the transfer of warmth To get rid of 4 W, a stamped heatsink reducing the wasted power. Using the through their bodies via radiation. This will suffice, assuming the ambient air is two aforementioned examples, let’s demonstrates how powerful radiation can approximately 30°C over 25°C (thermal see how the PT5101 stacks up. Using be because the clothing worn must be resistance better than 11°C). At 8 W, a VI = 9 V and requiring 1 A of 5-V reg- so well insulated as to prevent heat loss the thermal resistance of the heatsink ulated output current, the PT5101 from conduction and convection. must be better than 5.5°C/W. In this needs to dissipate 0.8 W. The total

case, an extruded heatsink can provide power required at VI = 9 V is 5.8 W PT5101 COMPARISON this. (Many factors are required for (0.8 W + 5 W). That’s an efficiency of The maximum input voltage for a choosing the proper heatsink, but that’s approximately 86%. typical 7805 linear regulator is 35 VDC, beyond the scope of this article.) Based on a VI = 16 V, the PT5101 with a required minimum differential Are you forced into using a VI higher needs to dissipate approximately 1.1 W.

VI-to-VO drop of at least 4 VDC. With than 9 V for your 5-V regulator? You may This makes the total VI power equal to the minimum VI = 9 V, the regulator be using a 12-V regulator as well and approximately 6.1 W. The efficiency can supply 1 A at the output. The 4-V supplying both the 12- and 5-V regulators drops to only about 82%, or roughly drop across the regulator produces 4 W with the same VI. For a 12-V regulator, VI 10× better than the linear regulator in of wasted power (4 V × 1 A). That’s 9 W must be approximately 16 V. This means terms of wasted power. Reduced power

(VI × 1 A) to get 5 W (VO × 1 A) regulated, that the 5-V regulator (VI = 16 V) will be requirements mean being able to use a or approximately 55% efficiency (VO/VI). dropping 11 V. With the same 1 A of smaller transformer. This directly Maximum current is approximately required current, the power wasted by relates to a real estate savings and a 2 A if you can keep the junction tem- the regulator is now 11 W! That’s 16 W lower parts cost. On the dissipation side perature at 25°C. (That’s 8 W of heat to (VI × 1 A) to get 5 W (VO × 1 A) regulated with a thermal resistance of 50°C/W, it get rid of.) With a thermal resistance rat- and doesn’t count what the 12-V supply can safely dissipate even the 1.1 W with ing of 65°C/W and a maximum junction might require. The efficiency here goes an ambient temperature of anything temperature of 150°C, the device can way down to approximately 30%. less than 95°C (200°F)!

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 77 TRADE-OFFS? lator’s VO varies 0.3 mV for each 1°C, equipment. If I needed to use a 5-V linear

It would make sense for a manufacturer which over zero to 60°C is 18 mV, the regulator with such a high VI, I would to design a replacement circuit to meet or switching regulator is rated in percentage split the 5-V load and use two 5-V regula- exceed the specifications of the device it’s change in the output volt. It’s 0.5%, or tors to reduce the operating junction replacing. After all, without any benefits, about 25 mV, in this case (see Table 1). temperature. Meanwhile, the PT5101’s there’s no incentive to use a new part. It’s device temperature increased slightly, yet obvious that this integrated switching LOAD TESTING well below a temperature considered regulator is meant to compete directly Under identical load testing of the lin- hot. As you study Photo 1, note that the with the linear regulator and win based ear regulator and the integrated switching frame of the PT5101 module is plastic on reduced power supply requirements regulator, I found them to be similar and not metal. It doesn’t serve as a (sig- and heat production. Depending on your in most respects. The high-frequency nificant) heatsink to the circuit, but more needs, one of these might far outweigh switching spikes of the PT5101 were as a frame to hold the tiny module’s PCB. the other. But you get the benefit of both. measured at less than 100 mV at full 1-A As you can see in Table 1, most of the output. I don’t see this as a problem for THE NEED specifications are similar. The linear regu- most systems. The efficiency of the Is power supply heat a problem for lator lists ripple rejection as about 80 dB, switcher over the linear regulator was your design? Are you using an enclosure which is 1/10,000 of the value at the apparent right from the mini- input. The VO ripple (up to 20 MHz) of mum VI. Using the specifica- Specification 7805 Linear regulator PT5101 ISR the switching regulator is listed as 2% of tion’s minimum differential VOTOL ±5% ±2% the output voltage, which for 5-V output voltage of 4 V, the linear reg- V RIP(PP) 80 dB 100 mV is roughly 100 mV. Photo 2 is an oscillo- ulator was hot to the touch O Reg ±20 mV ±10 mV scope shot of some high frequency noise even with a stamped finned LINE Reg ±25 mV ±10 mV I measured at 1 A of output current. (The heatsink, while the switcher LOAD

PT5151 uses a 500- to 800-kHz internal was barely warm (see Photo 1). RegTEMP –0.3 mV/°C ±25 mV switching frequency for regulation.) After raising VI from 9 to Current limit 2.2 A 2.6 A Another specification, which is listed a 16 V, the linear regulator Operating temperature –40° to 85°C –40° to 85°C bit differently by each, is the temperature became hotter than I’d like to Table 1—Compare the main specifications for a TO-220 linear regula- coefficient RegTEMP. While the linear regu- have running in any of my tor (7805) and an integrated switching regulator (PT5101).

WWW.GiURUMELE.Hi2.RO

78 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com with little or no ventilation? Has this larger transformer that would be neces- Jeff Bachiochi (pronounced BAH-key- excess heat required the use of a fan? sary? Replacing the current linear regula- AH-key) has been writing for Circuit Your design can benefit directly with no tor with an ISR can improve the efficien- Cellar since 1988. His background retooling by replacing those linear regula- cy of your power supply. This will enable includes product design and manufac- tors with integrated switching regulators. your present transformer to continue to turing. He may be reached at Texas Instruments offers 3.3-, 5-, 5.6-, be used. The efficiency improvement [email protected]. 6.5-, 8-, 9-, 10-, 12-, and 15-V ISRs as also comes with the added benefit of not direct replacements to linear devices. increasing the production of wasted SOURCE Is your product in need of extra current heat. It’s a win-win situation. PT5100 Integrated switching regulators capacity but you don’t have room for the For portable designs, heat waste Texas Instruments, Inc. means reduced operating life for your www.ti.com batteries. The replacement of the linear regulator with an ISR may double (or even triple) your battery life. To an end user, there is nothing more frustrating than having to frequently replace batteries. It looks like there really are ways to improve some products. Motorizing my toothbrush isn’t one of them. While out camping in the woods, many backpackers use their fingers as toothbrush- Photo 1—Take a look at the relative sizes of a linear es. I see Oral-B now offers voltage regulator mounted on a stamped finned heatsink Brush-Up teeth wipes, which are (left) and an ISR module (right). The ISR is a replace- Photo 2—This oscilloscope shot demonstrates the PT5101’s ability ment for the linear regulator. It offers improved conver- small brushes that fit on your to squash the internal switching noise at the regulator’s output sion efficiency and effectively lowers heat production. finger. When will it end? I (operating with the maximum rated 1-A output current).

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 79 APPLIED PCs by Fred Eady

ARM Applications with MicroBolt

If you have an industrial application in the works, take a look at Micromint’s MicroBolt—a Philips LPC2106 microcontroller-based embedded controller. You can program the small module in C or assembly language. Fred shows you how to get started.

Debuggers, compilers, and program- microcontrollers don’t require you to Normally, the LPC2106 bootloader mers all have one thing in common. procure a hardware debugger and a is used in conjunction with the ISP When you buy one, you most certain- physical device programmer. The fact subsystem and UART0 to initially ly will have to buy the other two. So, that only a compiler must be pur- program the LPC2106. Programming most designers choose a microcon- chased reduces the cost of doing busi- flash program memory locations using troller that they’ll probably use more ness with microcontrollers that can be IAP is performed under user program than once. Then they throw money at programmed and debugged without control. In either ISP or IAP mode, the the tools required to support that par- the aid of a specialized external elec- LPC2106 on-chip bootloader supplies ticular microcontroller and its family. tronic device. One such device is the the programming interface to the For instance, you can find many an Philips Semiconductor LPC2106 LPC2106’s on-chip flash program armed camp of PIC and AVR user microcontroller, which is at the heart memory. forums on the Internet. I’ve found that of my topic this month, the If you’re old enough, you’ll recall most of the hard-core AVR users don’t Micromint MicroBolt embedded con- that some of the first commercial PCs own any PIC tools. In an equally vehe- troller (see Photo 1). used discreet dynamic RAM ICs, ment fashion, the PIC troopers have which were usually arranged in 64-KB no desire to carry AVR munitions. MICROBOLT ANATOMY rows of eight or nine ICs, with the Unfortunately, some of us who deal The terms “Philips”, “ARM,” and ninth IC holding the row’s parity bit. with microcontroller design at the “LPC2106” are everyday language for The equivalent of one of those eight-IC, professional level can’t take a totally some of you out there in Circuit 64-KB rows of dynamic RAM is political or personal stance on which Cellar readerland. If the aforemen- squeezed into the LPC2106 as 64 KB of microcontroller and tools we use. If a tioned terms are a regular part of your static RAM. The rest of the stuff that project calls for a particular nuance daily vocabulary, there isn’t too much you’d normally associate with just that’s done much better by a certain I can tell you about the LPC2106 that about any general-purpose microcon- microcontroller, then that microcon- you don’t already know. However, if troller can also be found within the troller is the one we should use. you’re new to ARM computing, you’ll bowels of the LPC2106. Fortunately, many of today’s newer be interested to know that the The LPC2106 microcontroller build LPC2106 is an inexpensive microcon- includes a couple of UARTs, some troller based on the ARM7TDMI-S timers, a PWM unit, a real-time clock, WWW.GiURUMELE.Hi2.ROprocessor. a watchdog timer, and a vectored The LPC2106’s ability to be pro- interrupt controller. As a Philips grammed without the aid of an exter- device, the LPC2106 provides separate nal device programmer is provided by I²C and SPI subsystems, which allows its built-in in-application program- the I²C protocol to be used regardless ming (IAP) functionality. The of the additional system requirements LPC2106’s 128 KB of on-chip flash for SPI-based and UART-based com- program memory also can be loaded munications. Photo 1—The MicroBolt controller is a really clean with your favorite algorithms sans a To ensure that all of the standard design. The JTAG interface is on the far left of this shot. hardware programmer via the micro- microcontroller bases are covered, the A 14-pin male header is included with the MicroBolt module to enable it to be connected to a JTAG develop- controller’s in-system programming LPC2106 rounds out its hardware ment tool. (ISP) subsystem. complement with some general-pur-

80 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO pose I/O pins, an on-chip crystal oscil- hardware is constructed, you can C compiler. After you learn to use an lator, and power management functions. eventually find your way home by ref- ImageCraft C compiler, you can move The LPC2106 also drives off the show- erencing the LPC2106’s user’s manual seamlessly to any other variant with room floor with an industry-standard while probing around on the absolutely zero learning curve. The JTAG interface. MicroBolt PCB. ImageCraft ARM ICCV7 IDE runs My LPC2106-based MicroBolt under all of Bill Gates’s products from embedded controller is shown in MICROBOLT SOFTWARE Windows 95 all the way through Photo 1. As you can see, the LPC2106 Micromint assumes that not every- Windows XP Professional. That’s a is housed in a 7 mm × 7 mm 48-pin one doing microcontroller work has feat in itself. TQFP package. The MicroBolt gives ARM tools. If you are new to ARM, or ICCV7 is easy to navigate. It you full and easy access to the if you already have an ARM applica- includes a built-in serial terminal that LPC2106’s functionality with its tion and don’t want to spend big you use for application output moni- 24 pins, which just happen to pin out bucks on a prototype, the MicroBolt toring and debugging. There’s also an to match, pin-for-pin, the physical hardware I’ve described is aimed at application builder that helps you and logical layout of the BASIC you. code the initialization code for the on- Stamp 2. The same idea behind the MicroBolt chip LPC2106 peripherals. All of the But unlike the Stamp, the MicroBolt hardware holds true for the software. ANSI C types are supported by ICCV7 provides a 14-pin JTAG interface, We all know that there are a bunch of for ARM. A free LPC2106 library is which enables you to use advanced really good ARM development envi- included with the MicroBolt hard- programming and debugging methods ronments out there. We also know ware/software package. that may be available only via your that some of them are extremely Pride Embedded supplies the JTAG development device and the expensive. But just because a develop- LPC2106 library. As a matter of fact, LPC2106 JTAG interface. That’s ment tool is pricey doesn’t mean it is you already know the author of the good. If you already have JTAG tools automatically easy to learn and easy LPC2106 ARM library, Bruce Pride, that can target the LPC2106, you can to use. Buying a microcontroller who’s been published several times in use them with the MicroBolt because development tool isn’t like buying a Circuit Cellar. the MicroBolt’s JTAG interface is car. The BASIC Stamp-like simplicity In addition to demonstration pro- pinned out to the 14-pin industry- of the MicroBolt hardware is comple- grams, the LPC2106 library is com- standard interface. And if you’re mented by an equally simple yet posed of multiple C and header files looking to supercharge an existing powerful software development envi- that dispel some of the mystery Stamp-based application, the ronment. behind the initialization of the MicroBolt is a bolt-in Stamp replace- I’ve written quite a bit of produc- LPC2106’s PLL and I/O subsystems. ment module. tion code for EDTP products with You’ll also find library routines that There isn’t a published schematic ImageCraft C compilers. It appears address every LPC2106 on-chip for the MicroBolt. However, the that my mind and the minds of the peripheral as well as a library entry voltage regulator in Photo 1 and a engineers at Micromint are rolling featuring an array of accurate delay second voltage regulator on the back around in the same gutter. I’ve person- routines. of the MicroBolt PCB provide the ally found ImageCraft C compilers to I mentioned earlier that the core (1.8 V) and I/O (3.3 V) power be a good investment because they’re MicroBolt can be programmed with- supply voltages required by the relatively inexpensive, bug-free, and out the aid of external programming LPC2106. fully featured. hardware. To make it so, the The MicroBolt is intended to oper- The MicroBolt package comes with MicroBolt hardware/software package ate on your bench or in an industrial a fully functional demonstration copy includes a copy of Philips’s LPC2000 environment. To that end, you can of ImageCraft’s ICCV7 for the ARM C Flash Utility, which is a software power it with a standard 3.3-V supply compiler. The copy becomes a pump- package that runs on a PC and inter- on pin 21 or from a bulk power supply kin after 45 days and limits the faces to the LPC2106 via UART0. with an outputWWW.GiURUMELE.Hi2.RO voltage between 5 and amount of code that can be compiled. Operations such as upload to flash, 12 V fed to pin 24. The power supply For those of you unfamiliar with compare flash, reset, blank check, pins are mutually exclusive. The cur- ImageCraft C compilers, each variant erase flash (sectors or device), and read rent budget for the power source is identical as far as the look and feel device ID are supported by the needs only to include 40 mA for the of the GUI goes. LPC2000 Flash Utility. MicroBolt. I’d used ImageCraft C compilers tar- The read device ID function returns The idea behind the MicroBolt’s geted at Motorola and AVR devices both the part ID and the bootloader packaging is to keep you from worry- before loading up my copy of the ID. LPC2106 reset and bootloader ing about the MicroBolt hardware. For ICCV7 ARM compiler. The only selection tasks can be assigned to the that reason, I didn’t ring out the thing that’s different to the user is DTR and RTS lines of the PC’s COM MicroBolt PCB. I’m positive that if the code that’s particular to the port that’s in communication with you need to know how the MicroBolt microcontroller being targeted by the the LPC2000 Flash Utility. As you

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 83 or what it’s doing via a simple printf statement. Think of this little debugging applica- tion as nine rolling break- points you can set with a sim- ple printf statement.

MICROBOLT BOARD So far, I’m fairly certain that I haven’t presented you Photo 2—I punched the Read Device ID button to fill in the Part ID and Boot Loader ID windows. There isn’t much to say about this with anything you can’t han- window.You simply compile your code with the ImageCraft ICCV7 dle. The MicroBolt is a rela- for ARM, fire up this utility, and push your code into the LPC2106. tively simple piece of hard- ware. The development soft- can see in Photo 2, using the DTR ware that supports the MicroBolt is and RTS lines are a must for the easy to learn and apply. MicroBolt. The Philips 8051 program- I’ll bet you’re wondering about the ming utility is similar to the LPC2000 whereabouts of that MicroBolt PC- ARM utility as it also uses spare RS- compatible serial port I’ve been talk- 232 lines to set programming modes. ing about. Well, looking again at A nifty little MicroBolt debugger Photo 1, it’s pretty obvious that there Photo 3—I forced the MicroBolt debug LED to a steady on state through COM1. The other eight debug application is also included in the isn’t a TTL-to-RS-232 converter IC on windows were filled by printf statements in the MicroBolt hardware/software package. the topside of the MicroBolt PCB. And MicroBolt debugger demonstration program. The debugger application enables you I can tell you that there isn’t one on to control the MicroBolt’s debug LED, the flip side of the MicroBolt module board via the MicroBolt’s SPI interface. which is located just above the SMT either. A Microchip 24xxxx series EEPROM resistor in Photo 1. In addition, nine If you look closely at Photo 4, you’ll can be inserted in the U7 socket. debug windows are available within see a MAX3244 TTL-to-RS-232 con- Because the MicroBolt’s LPC2106 can the debugger application. Each win- verter IC mounted on the MicroBolt use both the SPI and I²C interfaces dow is accessed and loaded with the development board. It’s the only IC on simultaneously, both the 12-bit ADC desired debug data by simply begin- my development board other than the and the EEPROM can be included into ning the debug printf argument with voltage regulators and the MicroBolt your MicroBolt design process by sim- the window number. module itself. With the help of a gaggle ply plugging in the ICs and writing Take a look at Photo 3. To place of jumpers, the MAX3244 handles the some supporting code. Circuit Cellar in the window labeled RS-232 interfacing duties for both of A standard LCD based on the Debug-9, all I had to do was code the MicroBolt’s nine-pin serial connec- Hitachi 44780 with a 2 × 7 dual-row the printf statement as follows: tors and the LPC2106’s pair of UARTs. connector or 14-pin single-row area printf("9Circuit Cellar\n");. There are multiple jumper configu- can also be attached to the MicroBolt From the looks of Photo 3, you may rations that allow either of the serial development board using the pin sets get the idea that the MicroBolt debugger ports to be DTE or DCE RS-232 ports. positioned to the left of the pair of application is by no means a heavy- Populating the U3 socket (to the upper nine-pin serial connectors. The LCD weight debugging system, but it can right of the MAX3244) with an RS-485 contrast potentiometer can be seen in come in handy if all you need to do is driver IC (MAX3485 or equivalent) the far left upper corner of the devel- have your program tell you where it is enables two-wire RS-485 communica- opment board shown Photo 4. tions using the two-position screw-down terminal, J3. Depending on how you WWW.GiURUMELE.Hi2.ROconfigure the jumpers, the MicroBolt development board is capable of sup- porting two RS-232 ports or one RS- 232 and one RS-485 communications port. You may have noticed that there are some empty eight-pin IC sockets on the MicroBolt development board in Photo 4. If you want, you can populate Photo 5—I could have purchased an adapter cable to Photo 4—There isn’t circuitry in the breadboard area. the MicroBolt board’s U4 socket with a This is the business end of my MicroBolt development mate the J-Link’s 20-pin JTAG interface to the board. Note that the MicroBolt module is mounted with MCP3202, which will add two chan- MicroBolt’s 14-pin JTAG interface. But what fun would its JTAG interface pins installed. nels of 12-bit ADC capability to your that have been?

84 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com Jumpers are used to con- LPC2000 Flash Utility saw nect the optional peripherals the MicroBolt module and and serial ports to the successfully erased and pro- MicroBolt’s I/O pins. Bulk grammed the LPC2106. I power for the MicroBolt thanked Phil and continued development board is sup- on with my JTAG experimen- plied by a 12-V wall wart, tation. It seems that the J- which is supplied with the Link JTAG module had over- MicroBolt hardware package. taxed the MicroBolt’s on- Two power rails are created board 3.3-V regulator and on the board by the 7805 (5 V) put it into thermal shut- and LM1117 (3.3 V) voltage down, which explains why I regulators. As you’d expect, couldn’t get the MicroBolt to the MicroBolt I/O is pulled respond to the LPC2000 Flash out to a set of headers adjacent Utility right after it had to a large breadboard area. Photo 6—This is the J-Link ARM programming application. Using this instead of failed. the LPC2000 Flash Utility eliminates having to move the program and run WORK WITH MICROBOLT jumpers around on the MicroBolt development board, among other things. ARMED & DANGEROUS I must admit that when my Handling this ARM was MicroBolt arrived, I was more inter- gle to the MicroBolt module using my just as much fun as disassembling and ested in attaching JTAG tools to it newly hatched adapter. Things worked reassembling my new GLOCK .45. As than anything else. So, I verified the just fine for a while. Without warning you can see in Photo 6, some really operational status of the development and with an absence of the dreaded IC slick programs support the J-Link. I’ve board and the MicroBolt module by smoke signals, the MicroBolt appeared proven without a doubt that the mating the module to the develop- to have failed. MicroBolt can be engaged as both a ment board and exercising the options The MicroBolt module was attached beginner’s learning platform and the within the LPC2000 Flash Utility. to the Segger J-Link shown in Photo 5 pivotal part of a professional ARM After I was satisfied that everything when things went south. The J-Link application. Micromint has made it was working as designed, I decided to error message told me that the easy to get into ARM because the solder in the 14-pin JTAG header. MicroBolt’s 3.3-V supply voltage had MicroBolt and the MicroBolt develop- Because the JTAG interface to my fallen below an acceptable level. The ment board aren’t complicated. JTAG dongle is of the 20-pin variety, I absence of the LPC2106 I/O power They’re ARMed and embedded. I lashed up a 20- to 14-pin JTAG cable. supply voltage (3.3 V) disabled the The home-brewed JTAG adapter pin LPC2106’s JTAG interface (and probably Fred Eady has more than 20 years of assignments are shown in Table 1. everything else electronic that experience as a systems engineer. He The finished product and the JTAG belonged to the MicroBolt). has worked with computers and com- dongle are shown in Photo 5. I figured I had done the MicroBolt munication systems large and small, After rechecking my point-to-point module in, but I couldn’t for the life of simple and complex. His forte is wiring work, I attached the JTAG don- me come to a logical conclusion as to embedded-systems design and com- how I had done it. I decided to move munications. Fred may be reached at 14-pin JTAG JTAG Signal 20-pin JTAG away from the J-Link and test the mod- [email protected]. connector connector ule using the original LPC2000 Flash 1 VTREF 1 Utility configuration. No dice. The SOURCES 2 GND GND Montgomery Gentry song “Gone” start- ICCV7 for ARM C Compiler 3 nTRST 3 ed running through my mind. I reported ImageCraft 4 GND GND my MicroBolt’s demise to Phil at www.imagecraft.com 5 TDIWWW.GiURUMELE.Hi2.RO 5 Micromint via e-mail and went to bed. 6 GND GND No sense in beating a dead horse. MicroBolt embedded controller 7 TMS 7 Phil called bright and early the next Micromint, Inc. 8 GND GND morning. I told him what I was doing www.micromint.com 9TCK9 when the MicroBolt went belly up. He LPC2000 Flash Utility and LPC2106 10 GND GND suggested that I power the MicroBolt microcontroller 11 TDO 13 from the 3.3-V pin instead of the 5-V Philips Semiconductors 12 RESET 15 pin. That entailed the moving of a sin- www.semiconductors.philips.com 13 VTREF 1 gle jumper on the MicroBolt develop- 14 GND GND ment board. J-Flash and J-Link software Table 1—JTAG is JTAG no matter how many pins you I started the LPC2000 Flash Utility SEGGER Microcontroller Systems put around it. and refired the MicroBolt. The www.segger.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 85 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

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

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

WWW.GiURUMELE.Hi2.RO

86 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 87 WWW.GiURUMELE.Hi2.RO

88 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 89 WWW.GiURUMELE.Hi2.RO

90 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 91 WWW.GiURUMELE.Hi2.RO

92 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com CROSSWORD

1 2

3 4 5

6

7

8 9

10

11

12 13

14

15

16

17

Across Down 2. A security system that protects data on a LAN from 1. Code named for its inventor (1915–1998) that can detect hackers. single- and double-bit errors. It can correct single-bit 4. A line of conductive material (e.g., copper) on a PCB errors. that carries an electronic signal. 2. A storage method in which the oldest data is retrieved 6. A single computer instruction that generates a first. sequence of simpler operations. 3. RAM that serves as a specialized high-speed storage 9. A programming term for the number of arguments or mechanism. operands a function or operator takes. 5. An electrical device that opposes the flow of current in 10. An electronic device that produces a signal voltage. a circuit. 13. A chunk of self-contained data sent across a network. 7. An electrical resistor, the resistance of which varies 15. The amount of data, measured in bits per second (bps), with the applied voltage. that can beWWW.GiURUMELE.Hi2.RO transmitted through a channel in a given 8. An energy-storing device that typically includes two period of time. parallel conductive plates separated by an insulator. 16. An electrical device designed to receive a predefined 11. The semiconductor material in a transistor from which signal and automatically transmit a predetermined charge carriers originate. reply. 12. A hardware device that attaches to a computer to 17. An electronic circuit that produces alternating current enable a particular software program to run. or voltage signals. 14. Name for a semiconductor manufacturing plant. 15. The British mathematician (1815–1864) who used mathematical formulas to represent logical reasoning. The answers are available at He wrote An Investigation of the Laws of Thought www.circuitcellar.com/crossword. (1854) and papers on calculus and differential equations.

www.circuitcellar.com CIRCUIT CELLAR® Issue 186 January 2006 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 59 AAG Electronica, LLC 64 DesignCon West 64, 91 JK microsystems, Inc. 92 Picofab, Inc.

88 ADM Designs, LLC 86 DLP Design 89 Kamiya Design, Inc. 90 Pulsar, Inc.

92 AP Circuits 41 Earth Computer Technologies 58 Keil Software 42 R4 Systems, Inc.

49 APEC 29 EasySync Ltd. 61 LabJack Corp. 59 R.E. Smith

9 Acon, Inc. 2 Echelon Corporation 91 Lakeview Research 31, 81 Rabbit Semiconductor

61 Advanced Embedded Technologies 87 EE Tools (Electronic Engineering Tools) 88 Lawicel HB 88 Rabbit Semiconductor

90 Aequus Research Inc. 38 EMAC, Inc. 39 Lemos International 41 Radiant, Inc.

91 All Electronics Corp. 15 ExpressPCB 89 MCC 87 Reach Technology, Inc.

63 Arcom 31 ezPCB 17 Maxstream 50 Rowley Associates

88 Aruca Technologies 86 FDI-Future Designs, Inc. 87 MechaBlox 86 ScanTool.net, LLC

7 Atmel 34 Freescale Semiconductor 91 Micro Digital, Inc. 88 Sealevel Systems

77 BMF Power 91 Front Panel Express 92 microEngineering Labs, Inc. 5 Sierra Proto Express

86 Bagotronix, Inc. 23 General Circuits, Inc. 95 Micromint 49 SPLat Control Pty Ltd

66 Bitscope Designs 88 Grid Connect 91 Mosaic Industries, Inc. 90 Swope Designs, Inc.

89 Bitwise Systems 89 Hagstrom Electronics 57 Mouser Electronics 90 Systronix

16 CadSoft Computer, Inc. 14 HI-TECH Software, LLC 74 MVS 91 TAL Technologies

87 Carl’s Electronics 40 ICOP Technology, Inc. C2 NetBurner C3 Tech Tools

3 Comfile Technology, Inc. 89 IMAGEcraft 61 Nurve Networks LLC 26, 27 Technologic Systems

90 Conitec 90 Intec Automation, Inc. 92 Ontrak Control Systems 87 Technological Arts

59 Copland Electronics 90 Intrepid Control Systems 87 PCB Fab Express 89 Tern, Inc.

88 Custom Computer Services, Inc. 48 IPC (Printed Circuits Expo) 79 PCB-Pool 38 Tianma Microelectronics

78 Custom Solutions, Inc. 86 Ironwood Electronics C4 Parallax, Inc. 92 Trace Systems, Inc.

65 CWAV 25,47 Jameco 86 Phytec America LLC 91 Triangle Research Int’l, Inc.

1 Cypress MicroSystems 55 Jeffrey Kerr, LLC 89 Phyton, Inc. 92 Xytronix Research & Design, Inc.

Preview of February Issue 187 ATTENTION ADVERTISERS Theme: Embedded Programming March Issue 188 Embedded Object-Oriented Programming Deadlines Dial-Tone Decoder LoonBoard Unified Bootloader Space Close: Jan. 12 Rooting Around Material Close: Jan. 19 Output Real NumbersWWW.GiURUMELE.Hi2.ROTheme: Number Crunching on a Budget: Custom PIC MCU Solution Trumps PC Robotics Simple Voice Changer BONUS DISTRIBUTION: APEC, PCB West, Multifunctional Home Control System Trinity College Robotics Contest

ABOVE THE GROUND PLANE Sampled Data Bandwidth: Filtering Call Shannon Barraclough APPLIED PCs Discover True 16-Bit Functionality: Explorer 16 Offers Welcome Flexibility now to reserve your space! FROM THE BENCH Power Over Ethernet Primer 860.872.3064 SILICON UPDATE Something Old, Something New e-mail: [email protected]

94 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director The Personal Touch

I guess being prophetic doesn’t have the mileage these days that it used to. When I write an editorial expounding the societal implications asso- ciated with the misuse of RFID devices, nobody reacts. My inbox isn’t filled with e-mails from counterculture enthusiasts praising my intuition or engineers criticizing my overly simplistic “the sky is falling” innuendo. Basically, I get to say my piece and life goes on. Of course, when I’m less prophetic and talk about ridiculous personal adventures like almost falling through the attic ceiling while stringing camera wires, I get a dozen e-mails describing similar situations along with nice stories about having read Circuit Cellar for years. I don’t have a clue what this means other than perhaps too much of what you read elsewhere is prophetic, and a little personal touch now and then is a relief. Like you, I look at all the trade journals, PC magazines, and popular technical web sites. All the fervor about a particular subject in these other publications gives me the incentive to discuss the same thing in my editorial. But perhaps after hearing a dozen opinions on the value (or not) of dual-core processors in embedded applications, you may not feel the need to discuss it further. However, when I talk about how the obsessive-compulsive, anal co-worker in the next cubicle should get a life rather than frown about your slovenly looking (only to them) horizontal filing system like I did last month, I’m likely to get a whole bunch of e-mails. I guess I shouldn’t be surprised. I talk about technology and things that I see affecting your professional career because Circuit Cellar strives to be a technical resource. At the same time, Circuit Cellar is more than just a source of technical information. Most of you don’t leave it on the pile with the rest of the trade magazines at the office. It’s at home where you read it and keep it for enjoyment. I can only surmise that when you read an editorial about profoundly technical subject matter, you subconsciously leave it on the desk at the office. When I throw in an editorial about my latest adventures in home control or discuss how ridiculous it is to put 38 circulator fans in a car seat, I get a bunch of e-mails from readers sharing opinions and views because that’s part of Circuit Cellar’s enjoyment value for them. In truth, I enjoy telling you about my own uses of technology more. For example, after hearing how a friend had $200,000 in water damage to his house (it’s a nice house ;-) from a failed oil burner pump, I thought I’d better improve the monitoring system on my home’s five-zone heat- ing system before going to my “cottage” this winter. While I already extensively monitor room temperatures, it might not tell me that one of the circulator pumps has failed, or that a thermostat is stuck, or that the oil tank is just plain empty until it’s too late. OK, add a few solid state relays to monitor the power applied to the blowers and pumps, add a bunch of thermistors on the outlet pipes, add a 6″ bundle of wiring back to the HCS, and we’re good to go. Well, even I think doing all that would be nuts. My ultimate solution was much sim- pler. Rather than involve the HCS at all, I found this really neat four-channel video web server (www.arucaelectronics.com) and simply installed a few video cameras. From the cottage, I can now see the full System 2000 boiler control panel with its two-dozen status lights, the physical oil gage, and the oil pump pressure gage. Problem solved. I could go on about the other two four-channel video servers I added along with this one, but that’s a story for another time. The issue here is how much naive discovery and personal adventure I get away with before we have to go back to the mundane world of professional credibil- ity. Like many students we frequently meet these days who haven’t a clue how to do math by hand because they’ve used calculators their whole lives, there are many readers who don’t have the benefit of being with Circuit Cellar for some part or all of the last 25 years. Long-time readers know that humor and discovery are essential ingredients in this very personal magazine. I don’t like having to espouse on dry technology issues every month, but I don’t want the new guys thinking I’m some whack-job who only likes to play in the cellar either. It’s a fineWWW.GiURUMELE.Hi2.RO line keeping all these interests in check. I just need you to bear with me when I seem to occasionally switch horses in midstream.

[email protected]

96 Issue 186 January 2006 CIRCUIT CELLAR® www.circuitcellar.com WWW.GiURUMELE.Hi2.RO WWW.GiURUMELE.Hi2.RO