iETHERNET DESIGN CONTEST WINNERS P. 30 • DESIGN YOUR OWN CONTROLLER CIRCUITRY P. 70 • PROGRAMMABLE LOGIC 101 P. 76 w w w . i r c u i t c e l l a r . c o m CIRCUITTHE MAGAZINE FOR COMPUTER CELLAR APPLICATIONS #214 May 2008 MEASUREMENT & SENSORS Build An Ultrasonic Height-Sensing System Electronic Data Logging & Motion Analysis The coLinux Development Platform Making Sense Of Compiler Output Construct A Portable LCR Meter ATA Interfaces For I/O Apps

05>

7925274 75349 $4.95 U.S. ($5.95 Canada) C2.qxp 3/3/2008 11:16 AM Page 1

SERIAL TO ETHERNET SOLUTIONS

Simple Ethernet connectivity for serial devices Works out of the box - no programming is required

Device P/N: SB70-100CR Customize to suit any Kit P/N: NNDK-SB70-KIT application with low-cost $69 SB70 development kit 2-port serial-to-Ethernet server Features: Qty. 100 with TTL support 10/100 Ethernet TCP/UDP mode DHCP/Static IP Support Data rates up to 921.6kbps Web-based configuration Need a custom solution?

NetBurner Serial to Ethernet Development Kits are available Device P/N: SB72-EX-100CR to customize any aspect of Kit P/N: NNDK-SB72EX-KIT operation including web pages, data filtering, or custom network SB72EX $139 applications. All kits include 2-port serial-to-Ethernet server platform hardware, ANSI C/C++ Qty. 100 with RS-232 & RS-485/422 support compiler,TCP/IP stack, web server, e-mail protocols, RTOS, flash file system, Eclipse IDE, debugger, cables and power supply.

Device P/N: PK70EX-232CR Information and Sales | [email protected] Kit P/N: NNDK-PK70EX232-KIT Web | www.netburner.com $269 PK70EX232 Telephone | 1-800-695-6828 4-port serial-to-Ethernet server Qty. 100 with RS-232 support 1.qxp 4/10/2008 12:50 PM Page 1 35.?AD?%$PDF  !- 2.qxp 4/2/2008 1:34 PM Page 1 3.qxp 1/30/2008 12:00 PM Page 1

ent Disp sc la e y r s o u l

F

m

u

u

c a

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

RoHS Compliant ISO 9001 Certified 9001 140001 TS16949

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

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

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

Noritake VFD Backlit LCD

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

TASK MANAGER

DIY Measurement And Sensing Projects FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia During the past two decades, measurement and sensing technologies MANAGING EDITOR MEDIA CONSULTANT have become increasingly important in the daily lives of average con- C. J. Abate Dan Rodrigues sumers. Today, a typical American home has at least one measurement WEST COAST EDITOR CUSTOMER SERVICE or sensor system that features embedded technologies. Electronic tem- Tom Cantrell Debbie Lavoie perature-measuring systems, health-monitoring medical devices, CONTRIBUTING EDITORS CONTROLLER motion-sensing security networks, and interactive gaming systems are Jeff Bachiochi Jeff Yanco Ingo Cyliax common examples. Robert Lacoste ART DIRECTOR KC Prescott As most of our long-time readers know well, many of these technolo- George Martin gies were first developed by members of the embedded design commu- Ed Nisley GRAPHIC DESIGNER Grace Chen nity and then presented in the pages of Circuit Cellar. For instance, back NEW PRODUCTS EDITOR John Gorsky Carey Penney in Circuit Cellar Issue 2 (March/April 1988), we ran an article by Tom STAFF ENGINEER Riley about building a four-channel, temperature-logging system. In PROJECT EDITORS Gary Bodley John Gorsky Circuit Cellar Issue 26 (April/May 1992), we ran an article by our founder Ken Davidson Steve Ciarcia about building a “people tracking” system for his house. David Tweed Such IR systems are ubiquitous these days. More recently, we ran James ASSOCIATE EDITOR Koehler’s article about building a proton precession magnetometer Jesse Smolin (Circuit Cellar Issue 202, May 2007). These are only a few of the dozens of articles about measurement and sensor systems that we’ve published ADVERTISING over the years. 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise This month, we present four new articles about do-it-yourself meas- PUBLISHER urement and sensor projects. I encourage you to read through each arti- Sean Donnelly cle and try your hand at at least one of these exciting projects. Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] Starting on page 16, Gerhard Oberforcher takes you step by step ADVERTISING REPRESENTATIVE Shannon Barraclough through the process of building a PIC-based ultrasonic snow depth sen- Direct: 860.872.3064, E-mail: [email protected] sor. Even if you don’t need to take accurate snow depth measurements, ADVERTISING COORDINATOR you can use the principles described in this article to build a measure- Valerie Luster ment system for various other purposes. E-mail: [email protected] Miguel Rusch’s prize-winning LCR meter will be a great addition to your workbench (p. 34). The meter enables you to monitor the analog Cover photography by Chris Rakoczy—Rakoczy Photography performance of any device under test. www.rakoczyphoto.com Turn to page 41 to learn how Steve Lubbers built a seizure-monitor- PRINTED IN THE UNITED STATES ing system for his dog. Following Steve’s advice will help you design a CONTACTS truly 21st-century electronic data logging and monitoring system. This SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] project proves that you can use your engineering skills to monitor seri- Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, ous, life-threatening conditions. Hanover, NH 03755-5650 Address Changes/Problems: E-mail: [email protected] Jeff Bachiochi presents the last theme-related article in the issue. In GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] “Control Circuitry,” he explains how to build a controller that can interact Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] with your favorite gaming console (p. 70). Using your design and pro- New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION gramming expertise to tweak an existing sensor-based gaming system 860.875.2199, E-mail: [email protected] can be an affordable alternative to buying the next expensive product to AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article. hit the market. Once you’ve read through these engaging articles, be sure to check out CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar David Lynch’s follow-up article on embedded development (p. 52), Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- Wolfgang Matthes’s article on ATA interfaces (p. 60), Tom Cantrell’s intro- scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders duction to MAX II technology (p. 76), and George Martin’s article about and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call “looking” into his C compiler (p. 83). 800.269.6301. Finally, take some time to study the amazing projects that placed at Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. the top of the WIZnet iEthernet Design Contest (p. 30). The projects range Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from an innovative WIZ810MJ-based irrigation timer/controller to a handy from plans, descriptions, or information published by Circuit Cellar®. embedded server application that enables you to find airfare deals on the 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. Internet. Congratulations to all of the winners! The reader assumes any risk of infringement liability for constructing or operating such devices. Entire contents copyright © 2008 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. [email protected] Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 11.qxp 12/4/2007 10:58 AM Page 1 214_TOC.qxp 4/9/2008 9:09 AM Page 6

May 2008: Measurement & Sensors FEATURES

16 Depth Measurement Construct An Ultrasonic Snow Depth Sensor Snow Depth Measurement Gerhard Oberforcher System (p. 16) 30 Contest Winners WIZnet iEthernet 2007 Design Contest 34 Where Analog And Digital Collide An Easy-To-Use LCR Meter Miguel Rusch Third Place Microchip 2007 Design Contest

LCR Meter 41 Electronic Data Logging And Analysis Design (p. 34) A How-To Guide For Building A Seizure-Monitoring System Steve Lubbers 52 Embedded Linux Development (Part 2) Create An Embedded Development Environment David Lynch 60 Advanced Technology Attachment I/O Build Your Own Monitoring System (p. 41) Use ATA Interfaces For General-Purpose I/O Applications Wolfgang Matthes

COLUMNS

70 FROM THE BENCH 83 LESSONS FROM THE TRENCHES Control Circuitry Making Changes Jeff Bachiochi A Look Into The C Compiler George Martin 76 SILICON UPDATE Designer’s Best Friend Tom Cantrell DEPARTMENTS

4 TASK MANAGER 93 CROSSWORD DIY Measurement And Sensing Projects 94 INDEX OF ADVERTISERS C. J. Abate June Preview 8 NEW PRODUCT NEWS 96 PRIORITY INTERRUPT edited by John Gorsky Who Said Variety Is Good? 15 TEST YOUR EQ Steve Ciarcia

6 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 12/10/2007 12:18 PM Page 1 npn214.qxp 4/9/2008 8:47 AM Page 8

Edited by John Gorsky Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. VOLTAGE-FEEDBACK AMP BALANCES SPEED AND POWER The ADA4857 is the lowest power voltage-feedback amplifier in its class, making it ideal for densely populated, thermally sensitive instrumentation equipment that requires high-speed signal conditioning. Operating at 850 MHz, the high-speed op-amp consumes 5 mA, less than half the power of competing voltage-feedback amps, while featuring the industry’s most well-balanced combination of performance specifications. The ADA4857 reduces input noise to 4.4 nV/rtHz, which is 50% lower than competing amplifiers. With –91-dBc distor- tion at 10 MHz, the new amplifier provides a 10-dB improve- ment over voltage-feedback amps that dissipate twice the power. For space-constrained medical imaging, ATE, and other multichannel instruments, the 5-mA supply current mini- mizes the need for active thermal management devices and passive cooling elements, such as fans and heatsinks, thus allowing system designers to reduce development costs and design complexity. The single-channel ADA4857-1 is available in 3 mm × 3 mm eight-lead lead-frame chip-scale package (LFCSP) and eight- lead small-outline IC (SOIC) packages. The dual ADA4857-2 is available in a 4 mm × 4 mm 16-lead LFCSP. The single-channel ADA4857-1 costs $0.85 per unit, and the dual ADA4857-2 costs $1.39 per unit, both in 1,000-unit quantities.

Analog Devices, Inc. www.analog.com

8 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com npn214.qxp 4/11/2008 2:00 PM Page 9

NEW PRODUCT NEWS 12-BIT, I2C SAR ADC DISSIPATES ONLY 1.5 MW The LTC2309 is a 12-bit ADC that communicates via an input channels because designers can easily communicate I2C-compatible two-wire interface with a 14-ksps throughput with multiple LTC2309 devices. rate. This flexible converter features an integrated multiplexer The LTC2309 is available in both commercial and indus- to measure eight single-ended input channels, four differential trial temperature grades. Prices start at $2.95 for 1,000-piece channels, or combinations of both. The input channels are quantities. software selectable for unipolar or bipolar ranges. Operating from a single 5-V supply, the LTC2309 draws just 1.5 mW at a Linear Technology Corp. 1-ksps throughput rate and only 35 µW in Shutdown mode. www.linear.com Packaged in a tiny 4 mm × 4 mm QFN-24 with internal reference, the LTC2309 is a great fit for portable instrumentation and space-con- strained designs. The LTC2309 achieves excellent DC specifi- cations when measuring unipolar or bipolar input signals, including ±1-LSB INL and DNL, ±6-LSB (max) zero-scale error and ±6-LSB (max) full-scale error. The LTC2309 also excels when digitizing AC input signals, measuring 73-dB SINAD and –88-dB THD at 1 kHz. The converter allows I2C data transfers of up to 100 kHz in Standard mode and 400 kHz in Fast mode. The ADC includes two address select pins that may be tied low, high, or left floating, thus providing nine unique I2C addresses. This is ideal for applications that require measurements of more than eight

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 9 npn214.qxp 4/9/2008 8:47 AM Page 10

NEW PRODUCT NEWS COMPACT AND POWERFUL GPS RECEIVER MODULE The TrineX CW27 is a self-contained GPS receiver module based on the NemeriX NX3 high-sensitivity A-GPS single- chip receiver. Using a new baseband processor and RF front end, the TrineX delivers superior GPS performance in a small surface-mount package that minimizes power consumption, maximizing battery life. The TrineX takes up only 24 mm × 24 mm of PCB space and connects directly to the host system through a UART using NMEA protocols for enhanced performance and flexi- bility. The device has been specifically developed for mobile hardware platforms running off batteries, where power con- sumption and small size are critical. Unlike many other options in this space, the CW27 delivers enhanced GPS tracking, down to –159 dBm, enabling tracking in many obstructed view environments such as urban canyons. The module offers an ARM7-based application processor and operates off a single 3.3-VDC supply. The TrineX CW27 costs $34 in 1,000-piece quantities.

NavSync www.navsync.com

PRECISION POWER OP-AMP FOR HIGH-VOLTAGE APPLICATIONS The OPA454 is a precision power op-amp, which operates on supplies up to 100 V and delivers a high-output current of ±50 mA with a 150-mA short-circuit limit. The driving force for the OPA454 design was high-voltage test equipment, which requires a combination of high voltage, high-DC accuracy, and significant speed. Hence, the OPA454 is an attrac- tive option for a wide range of precision op-amp applications, including optical communications, industrial control, data acquisition, power supplies, and regulators. The OPA454 is unity-gain stable and can track fast-moving signals because it has a slew rate of 10 V/µs and a gain- bandwidth product of 2.5 MHz. With a single or dual supply of ±4 V (8 V) to ±50 V (100 V), the OPA454 offers design flex- ibility and convenience in a single package, even for routine applications. High DC accuracy of 4 mV maximum offset and 5 µV/°C drift permits preci- sion DC measurement over tempera- ture. The OPA454 also has a low-bias current of ±110 pA that allows accu- rate measurements from high-imped- ance sources or sensitive current- shunt circuits. Additional features include a fast- acting enable/disable pin referenced to the common pin, which can be ground. This saves power and provides protection for the amplifier and the load. Also, an output status flag, refer- enced to the common pin, tells the user when an over-current or thermal overload condition occurs. This allows easy connection to low-voltage logic circuitry. The OPA454 is available now in an SO-8 PowerPAD package and costs $3.45 each in 100-piece quantities.

Texas Instruments, Inc. www.ti.com

10 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com npn214.qxp 4/9/2008 8:47 AM Page 11

NEW PRODUCT NEWS UNIVERSAL STRAIN GAUGE AMPLIFIER BOARD The SGAU is a small PCB assembly designed to amplify strain gauges arranged in a full Wheatstone bridge configuration. It is suitable for many appli- cations where a bridge or differential input amplifier is required. The SGAU is based on the AMP04 precision instrumentation amplifier. It may be operated with a single- or dual-power supply to provide single-ended or bipolar output. In addition to its gain and offset adjustment trimmer potentiometers, the SGAU includes an on-board 5-V regulator to provide an excitation voltage for strain gauge bridges. Screw terminal block connections and mounting holes round out the SGAU’s list of features, providing an easy-to-use instrumentation amplifier for many applications. The small circuit board (2.0″ × 1.0″ × 0 .6″) includes no surface- mount components, making it easy to modify for custom appli- cations. The SGAU costs $69.

Industrologic, Inc. www.industrologic.com

LOAD CELL AND INTERFACE WITH USB OR ANALOG OUTPUTS The iLoad Mini is a new miniature load cell based on the patented capacitive Plug and Sense technology. The sensor offers unprecedented simplicity and ease of use in a rugged, low-profile 1.25″ diameter package and heights between 0.5″ and 1″ depending on the configuration. The separation of the load cell from the signal conditioning interface board gives greater flexibility to designers and inventors who want to fit the sensor into small spaces. The iLoad Mini load cell accepts a 5-VDC input and outputs a baseline 5-V TTL frequency signal proportional to the applied load. The load signal is com- plemented by a reference signal that is sensitive to environmental effects such as temperature and humidity. This secondary signal can be used to compensate the baseline signal for temperature and humidity effects. The price of an iLoad Mini sensor starts at $99 for the base version in alu- minum with ±2% overall accuracy. Higher-accuracy versions made in 17-4 PH stainless steel are also available.

Loadstar Sensors, Inc. www.loadstarsensors.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 11 npn214.qxp 4/9/2008 8:47 AM Page 12

NEW PRODUCT NEWS TINY DIGITAL INFRARED TEMPERATURE SENSOR The TSEV01P is a digital infrared temperature sensor that measures only 8.5 mm × 15.6 mm × 4.7 mm. The benefit of this OEM module is a strong integration leading to a radical reduction of the outer dimensions of the sensor combined with a strong reduction of the power consumption. These so-called “thermopiles” are used to measure temperature in a fast, pre- cise, and contactless way. The sensor, housed in a TO metal can, provides an elec- tronic voltage depending on the incoming infrared radiation. Additional electron- ics are applied for analog and digital signal processing to compute the surface temperature of the object of interest. With the TSEV product family, all of these functionalities have been integrated to an electronic assembly on one PCB. Thus, the TSEV01P is the ideal choice for consumer and handheld applications, including mobile phones, PDAs, battery-operated (non-medical) thermometers, toys, and many industrial devices, which have limited room. The calibrated and temperature-compensated sensor system is equipped with a digital interface to provide straightforward integration to any system. It offers a resolution of 0.01°C and accuracies of ±0.5°C for 10° to 40°C. The output is via an I2C interface. The TSEV01P costs $7 in 1,000-piece quantities.

Measurement Specialties, Inc. www.meas-spec.com

NEW SIMULATOR SPEEDS UP DEVELOPMENT TIME An upgraded version of the award-winning uC/Probe is Additional upgrades in the current release include sup- now available. The uC/Probe is a unique new tool for port for TCP/IP and USB connectivity, meaning the embedded developers to monitor all of their embedded sys- uC/Probe can interface with virtually any embedded sys- tems designs in a live environment. tem available on the market today, or any PC when oper- By providing simulation on a Windows platform, users ating in Simulator mode. can test a good portion of their embedded software and The current release also adds Renesas Technology’s visualize it. Another advantage for users is that visualiza- emulator support, allowing all Renesas microcontrollers tion screens can be created offline and thus be ready when (M16C, M32C, SH, and H8 lines) to work with the the actual hardware shows up. The new features consider- uC/Probe, the addition of bitmaps to allow users to add ably strengthen the uC/Probe’s capabilities as a demonstra- logos and other graphics, and improved editing capabili- tion and marketing tool, because it can now demo new ties, including copy, paste, grouping, and snap-to-grid products without needing to have hardware connected to functionality. the PC. The uC/Probe eliminates the need to stop an application to get system feedback and saves considerable develop- ment time by visually allowing users to see the internals of a running embedded application. As a result, developers can ensure that the system is working properly or immedi- ately identify system instabilities that are visible only when the system is live. The uC/Probe works with compilers, any 8-, 16-, 32- and 64-bit CPUs, as well as DSPs. It can be used with any tool- chain that can generate an ELF/DWAFF or IEEE695 file, eliminating the need for custom programming or scripting. Data is displayed graphically on a PC running , and values can be numeric or shown as gauges, bar graphs, plots, graphs, LEDs, counters, or pie charts. The uC/Probe does not require you to write code and can operate with or without a real-time (RTOS). The product interfaces with hardware targets via J-Tag, RS-232C, TCP/IP, USB, and Renesas emulators through the HEW Target Server for data collection. The uC/Probe-STD is available and sold on a per-com- puter basis for $995. It can also be downloaded on a 30-day time-limited evaluation version.

Micrium www.micrium.com

12 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 25.qxp 3/3/2008 12:52 PM Page 1 npn214.qxp 4/9/2008 8:47 AM Page 14

NEW PRODUCT NEWS 16-BIT FLASH MICROCONTROLLERS FOR INVERTER CONTROL The 78K0R/Ix3 is a new line of 16-bit all-flash microcontrollers for inverter control applications. Built around the fast and efficient 78K0R CPU core, the 19 MCUs in the line-up are designed to enable a new generation of intelligent and eco- friendly appliances and motor drives. All of the devices in the line-up feature integrated inverter control circuits and deliver best-of-class power performance. Inverter control systems are found in an ever-wider range of products in response to consumer demand for more energy- efficient appliances. Fine-tuned control of motors and heating elements can deliver significant energy savings in products ranging from refrigerators and air conditioners to dishwashers and magnetic induction cooking appliances. The 78K0R/Ix3 MCUs, with 16-bit performance and 8-bit power consumption levels, are ideal for such applications. All of the devices in the line-up share the offered CPU power consumption of only 1.8 mW per MIPS and on-chip oscillators capable of driving timers at rates up to 40 MHz for fine- tuned inverter control. They also offer inte- grated hardware multiply and divide func- tionality for fast processing of mathematical algorithms and feature integration of all ana- log circuits required for inverter control, including comparators and integrated op- amps. Prices vary according to on-chip memory specifications. For example, the 78K0R/IE3 product with 64 KB of flash memory and 3 KB of RAM costs $5 per unit in sample quantities.

NEC Electronics Corp. www.necel.com

SOFTWARE-SELECTABLE USB ANALOG INPUT MODULES The USB-AI Series is a new line of low-cost USB analog input modules that include five models (USB-AI16-16A, USB- AI16-16E, USB-AI12-16A, USB-AI12-16, and USB-AI12-16E). The boards feature eight standard analog voltage input ranges, two factory current input ranges (4–20 mA or 10–50 mA) and includes a data sample buffer and hardware real- time calibration capability. A unique channel-by-channel programmable gain feature enables measurement of an assort- ment of large and small signals in one scan—all under software control at up to 500 kHz. For embedded OEM-type appli- cations, an additional miniature USB input header is provided in parallel with the type-B connector. The USB-AI Series can be integrated into any PCI-104 or PC/104 stack by connecting it to a USB 2.0 port usually included onboard with embedded CPU form factors such as EBX, EPIC, and PC/104 (especially important because many newer CPU chipsets do not support ISA and have plenty of USB ports). The flagship model, USB-AI16-16A, a 16-bit multifunction analog input board is ideal for precision measurement, analy- sis, monitoring, and control in countless embedded applica- tions. It can be used in most operating systems and includes a free Linux (including Mac OS X) and Windows 95/98/Me/NT/2000/XP/2003-compatible software package. This package contains sample programs and source code in Visual Basic, Delphi, C++ Builder, and Visual C++ for Win- dows. Also incorporated is a graphical setup program in Win- dows. Third-party support includes a Windows standard DLL interface usable from most popular application programs, and includes example LabVIEW VIs. Embedded OS support includes Windows XPe. The series ranges from $339 to $639.

ACCES I/O Products, Inc. www.accesio.com

14 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com eq-214.qxp 4/9/2008 9:09 AM Page 15

Test Your EQ CIRCUIT CELLAR Edited by David Tweed

Problem 1—The following figure shows the essential fea- Bonus Question—Note that with a 40-W load, the tures of a modern power-factor controller, which is a spe- 120-VAC line is going to be supplying an RMS current cialized form of boost regulator. of 300 mA, which has an average value of 270 mA. How do you account for the difference between this Coil Diode number and the 100-mA average current that the load AC Output sees? Control Switch AC C1 C2 Ref Problem 4—Getting back to the low-pass filter in the LPF Error Gnd voltage feedback loop, what effect does this have on the output impedance of the PFC circuit, as seen by What sort of current waveform would you expect to see the load? in the inductor? How does this relate to the input line current? Problem 5—What is the start-up transient for this cir- cuit like, and what are the worst-case conditions for Problem 2—Why is there a low-pass filter in the error startup? feedback path? What should its cutoff frequency be? Contributed by David Tweed Problem 3—Assuming a constant-current load for sim- plicity, describe the voltage and current waveforms in the output capacitor C2 in qualitative terms. How do they change, if you have a constant-power load, such as What’s your EQ?—The answers are posted at a secondary switching regulator? www.circuitcellar.com/eq/ You may contact the quizmasters at [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 15 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 16

FEATURE ARTICLE by Gerhard Oberforcher Depth Measurement Construct An Ultrasonic Snow Depth Sensor

Gerhard used the sonar components from an autofocus camera, a Microchip PIC18F452 microcontroller, and several off-the-shelf parts to construct an ultrasonic snow depth sensor system. The low-power design provides accurate snow depth measurements and is easy to integrate into other weather station systems.

Snowfall and snow depth measure- construct your own snow depth sensor an ultrasonic ranging head, an exter- ments are important to anybody who based on the ultrasonic hardware found nal ambient temperature sensor pro- receives regular snowfall. Several tra- in some models of Polaroid cameras or tected by a solar radiation shield, a ditional methods of measuring snow from off-the-shelf parts available from junction box, a snow board, and an accumulation include snow boards, SensComp (see Photo 1). A Microchip arrangement of four poles holding the snow pillows, rulers, and tipping PIC18F452 microcontroller measures sensor head rigidly (about 1.5 m) bucket rain gauges. Other methods the time interval for the sonar meas- above the snow board (see Figure 2). measure the “water equivalent.” One urement and provides system control An ultrasonic distance sensor must method uses a gauge that contains and serial data communication with have a suitable sound transducer, antifreeze to melt the snow as it col- the host system (see Figure 1). which can be used to transmit and lects. The increase in the volume col- receive. This is the case with the lected indicates the water equivalent SNOW DEPTH SENSOR Polaroid ultrasonic transducer. The of the snow. The water equivalent of The snow depth sensor consists of circuit emits a short burst of short snow can vary by as much as 50 to 1, depending on the climate. Ultrasonic snow depth measurement a) b) is commonly used at many automated meteorological measurement sites. The advantages of an ultrasonic snow depth sensor are low-power operation, and low maintenance. It also can be readily inte- grated into an existing weather station monitoring system. Unfortunately, only a handful of ultrasonic snow depth sen- sor manufacturers exist worldwide. Besides being practical, an ultrason- ic snow depth sensor is an ideal proj- ect for an embedded microcontroller, such as a Microchip Technology PIC. Readily available ultrasonic transduc- ers and driver boards can be purchased or salvaged from Polaroid autofocus film cameras. A working snow depth sensor, based on these components, was built in the fall of 2005.[1] The sensor has also been integrated into a home-based modular weather station Photo 1a—The snow depth sensor is ready to take on winter. b—The four-legged mounting structure provides stability that has been in operation since 2002. and is not subject to wind vibration. A solar radiation shield is mounted on the left support leg. It is painted bright In this article, I will describe how to white to reflect solar radiation.

16 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 17

wavelength sound toward the target. between the initiation of the transmit SensComp 6500 board. It has a beam The snow depth sensor operates at a burst and the received echo pulse. The angle of 15° and enables operation frequency of approximately 50 kHz microcontroller then calculates the dis- between 6″ and 35′ (see Photo 3). (see Photo 2). tance traveled with the speed-of-sound The transducer is fundamentally a After a built-in default blanking equation.[2] The ambient temperature capacitive microphone and requires a dead time of 2.38 ms to enable the must be measured to compensate for high polarization voltage in Receive transducer membrane to quiet down, the temperature dependency of the mode for the best receive sensitivity. The

the receiver portion is re-enabled by speed-of-sound travel time. The sensor’s SensComp driver generates a 400-VPP, the digital IC to process the echo sig- specifications are listed in Table 1. 49.4-kHz burst of 16 sine wave periods nal reflected from the target. When the resulting in a burst duration of approxi- echo arrives, a logic signal transition CAMERA SONAR HARDWARE mately 320 µs. When finished, a high pos- indicates the arrival of the pulse. The I am using the 600 series electrostatic itive voltage of approximately 200 VDC microcontroller’s hardware timer is con- instrument transducer from SensComp. remains on the transducer during the figured to capture the time difference The driver electronics are similar to the receive interval to provide the

Figure 1—This illustrates how the assemblies of the sonar unit are connected. The sonar head compartment houses the transducer, a temperature sensor, and a wire-wound heater resistor. The sonar compartment is vented to the outside via a small hole to allow pressure to equalize.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 17 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 18

Junction box (Hammond 1554GY)

J1 J3 J2

Ambient air Snow height temperature sensor sensor Radiation shield DC Power/RS-485 to meteorological station bus

Snow board

Figure 2—This is how the individual parts of the snow depth sensor are interconnected.

required polarization voltage for the camera, then the digital chip must be Receive mode of operation. Don’t replaced with a TL851CN. The chip touch the output because the high- used in the camera, although almost voltage pulses are sufficient to pro- identical, is designed to power down duce a noticeable tingle depending on the electronics briefly before each new your skin resistance. (I have personal measurement. The TL851CN allows experience with this phenomenon!) continuous operation without power The SensComp board uses a Texas down. You could use the original chip, Instruments chipset consisting of an but it would require the microcon- analog and a digital custom chipset. troller and an added transistor switch There is a difference between OEM to power down the board between SensComp boards and salvaged camera each measurement. This would boards. OEM boards allow re-trigger- require some small changes to the ing, whereas camera versions require firmware, which I have not tried. power down between measurements. However, it is more convenient to use If you use a board salvaged from a the replacement IC due to the burst

Power requirements 8 to 33 VDC, 1 A Power consumption 100 mA average at 15 VDC with brief 2-A peaks. The current will fall with increasing voltage. Measurement time Programmable Burst mode Output format Serial ASCII, 1,200 to 57,600 bps Communications mode Automatic or polled Communications interface Internally terminated RS-485 Half-duplex Tested distance measurement range Greater than 0.5 m to a maximum of 10 m Tested accuracy ±1 cm at close range increasing to ±4 cm at the upper limit of the range. Uses the external LM34 temperature sensor for compensation. Temperature accuracy of speed of sound ±1 cm from –40° to 60°C compensation (depends on temperature sensor exposure)

Transducer used SensComp series 600 instrument grade type Resolution Less than 1 mm Cone angle ±15° at –6 dB Maximum cable length 300 to 1,000 m at 9,600 bps Suggested cable type Four conductor shielded dual-twisted pair, 22 AWG Operating temperature –40° to (60°C) Dimensions Depend on the stainless steel coffee mug enclosure Table 1—This table lists the snow depth sensor’s specifications.

18 Issue 214 May 2008 CIRCUIT CELLAR® 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 19 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 20

mode of operation. Digi- and other factors. For Key carries the replace- short periods of time, ment IC. For further there are instances of information, refer to the total loss of echo signals module schematic in the with certain types of datasheet for SensComp fresh snow. 6500 series ranging modules.[3] COMMUNICATIONS An RS-485 communi- SPEED OF SOUND cation link is used as The measured travel part of a complete modu- time must be corrected lar weather station sys- for the dependency of the Photo 2—The snow depth sensor’s electronic parts are ready for installation on the mounting tem using several inde- structure. The temperature sensor will be mounted in a solar radiation shield to prevent speed of sound with tem- pendent sensors to com- excessive heating. The plastic film cans protect the connectors from the elements. perature, humidity, and municate with a remote- pressure. In this applica- ly located host comput- tion, only the ambient air temperature burst of rapid measurements that are er. Each system component responds is considered. stored in memory for averaging and to a unique address when polled by An external temperature sensor, calculation of the variance, which is a the remote host computer. mounted suitably in a solar radiation measure of the target quality. The I used a Microchip Technology shield, provides temperature input to controller can be programmed to gen- PIC18F452 microcontroller (see Figure 3). the computer to enable compensation erate between one and 32 burst meas- The 16-bit Timer1 is configured to for the change of speed of sound ver- urements. Typically, a variance below increment at a rate of 1 µs, derived sus temperature. If you refer to Wendy four can be achieved on a hard target. from the MPU timebase crystal. To Brazenec’s master’s thesis “Evaluation Any value greater than 50 is consid- measure the 1-µs resolution time of Ultrasonic Snow Depth Sensors for ered a poor target. The target quality is interval, the capture/compare register Automated Surface Observation Sys- dependent on the snow’s consistency is used. The ADC section is used to tems (ASOS),” the speed of sound in meters per second is related to the ambient temperature (T) in degrees a) b) Celsius.[2] The simplified equation is:

The distance can then be calculated with the following equation:

Because this computes the total travel distance, the result must be divided by c) d) two to obtain the distance to the target.

TARGET QUALITY Ultrasonic ranging imposes certain requirements on the orientation of the transducer, field of view, and the char- acteristics of the reflecting surface. To allow for the quality of the target reflectivity, the controller computes the mean variance based on the sum Photo 3a—This is the “business end” of the snow depth sensor. The tiny transducer pressure equalization hole is of differences relative to the mean near the seven o’clock position. The green shroud protects the transducer from wind-driven moisture to prolong its average. This method avoids the float- life. The 5-W heating resistor is located directly behind the transducer body to prevent condensation. b—The circuit ing-point calculations that traditional boards are circular to enable stack-type mounting inside the circular stainless steel enclosure. Insulation displace- standard-deviation calculations ment connectors complete the interconnections. c—All of the boards are mounted with interconnect cables in place. The small four-pin connector hidden behind the left-front mounting stud accepts the sensor cable carrying require. The lower the result, the more DC power and RS-485 communications. d—The sonar board is mounted directly over the transducer base to the readings are similar to each other. enable short connections. A gray plastic disk separates the transducer from the inside compartment to maintain a The controller triggers a consecutive good seal from the outside world.

20 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 21

6 V

Transducer compartment PIC18F452 U2 VCC ECHO RC2 RC6/TXD RO TI MAX483 A/B J5/J2 SensComp 6500 UART RC7/RXD DIR/RE- sonar board RB1 Electrostatic transducer BINH RD6 BLANK RD7 J2 PID 604142 INIT RD5 RB7 RB6 ISP Interface P/O A1 RES Sensor Q1/Q2 6 V compartment RD0 COMM LED PWM Driver RD3 heater RD1 HB LED JP1 RC5/SDO Serial LCD LM34 100 mV – 2.5 V, 10 mV/DEGF AN0 RC3/SCK interface Temperature 0.7 V Sensor offset voltage RB3/E sensor AN1 J3 RC2 PWM/DC 0–5 V Analog out Q1 VR1 2.5-V AN2 V Sonar AN3/ CC Voltage AN4 To A1-3 VREF reference 100 mV - 2.5 V, 10 mV/DEGF AN5 To external LM34 (P/O J2-ISP) from external air temperature sensor A1 – Voltage regulator board J1 To AN4 U2 J1 8-32 VDC IN LM2596 6-V SONAR DC

PWR/COMM J1 J2 LM2936-5 5-V DC

Figure 3—Interfacing the PIC18F452 microcontroller RS-485 Filter J1 To MAX 483 Interface protection is straightforward. The sonar board requires only a few connections.

measure temperature sensors and internal voltages. The UART is con- nected to an RS-485 transceiver in Half-Duplex mode. A serial LCD interface port is provided for future use in special applications. For basic operation, the Polaroid board requires only a transmit trigger signal and the use of the ECHO out- put signal to measure distance. Addi- tional interface I/O lines exist for more sophisticated applications. Please refer to the SensComp 6500 series ranging module’s datasheet for more information.[3] Although the digi- tal control IC allows multiple echoes, the PIC firmware does not take advan- tage of this possibility. To prevent transducer frost and con- densation damage, a small heater resistor is housed behind the transduc- er inside the transducer compartment. A National Semiconductor LM34 tem- perature sensor provides feedback for proportional temperature control. A firmware-based control loop is set to maintain the temperature around the freezing point. The 1-ms Timer2 ISR generates a 1-ms resolution PWM

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 21 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 22

drive signal to vary the heater output. Sonar state machine The firmware also can be configured executed every 5 ms to operate in Constant Differential by TIMER2 ISR Wait for run Tracking mode. As long as the transduc- command Power on er temperature is higher than ambient, condensation cannot occur. In two years Idle Sonar update flag = true of use, no visible damage or deteriora-

tion of the transducer was detected. Set up new Done measurement cycle POWER SUPPLY & SAFETY Init Sonar update flag = false The sensor’s power supply features a National Semiconductor LM2596 simple switcher TO-220-based buck Start new sonar measurement Print Send Output regulator. It produces 6 V at up to 3 A new data to power the Polaroid board and the Delay heater. A National Semiconductor Min 80-ms delay required by LM2936 LDO provides a clean, low- sonar module Calculate final noise 5 V to the controller. result Waits for echo Bursts not The circuitry includes protection Wait for signal or timeout complete components to limit overvoltages, echo condition Calc overcurrent, and transients. A self- resettable fuse (SRF) is used to limit Echo found Read Bursts the power supply current in case of complete internal short circuits or wrong DC No echo found Get Ccp1 data, polarity. The 1.5KE36CA protects -timeout calculate time Set target interval, check No break delay against overvoltages, transients, and error flag result the wrong polarity applied. The RS-485 No echo lines are also protected from transients found with SRFs. A MAX483 RS-485 half-duplex bal- anced transmission line data transceiver Figure 4—The sonar state machine decouples the fast PIC firmware from the slow sonar board signal timing. interfaces the UART with the weather station communication path. A unique ID enables multiple sensor communica- system clock after division by four by operational sensor parameters. The tions with other sensors sharing the the programmable prescaler. To enable communications protocol requires a same communications channel. measurement of the time interval, the unique address to enable the sensor to Five 10-bit ADC channels are used CCP1 interrupt ISR is configured to respond to external commands. This to measure the outputs of the follow- respond when the ECHO output line enables multiple sensors to share the ing devices in sequence: an LM34 air goes high. communications path on the RS-485 temperature sensor, an LM34 sensor To measure the time difference cable. For example, in my installation, DC-offset, a sonar 6-V power supply, between the start of the sonar pulse, a weather station and another sensor an external DC input voltage, and an the running 16-bit Timer1 count is share the same cable, each responding LM34 external air temperature sensor. captured when the Polaroid board to its assigned address. The ADC converter sets the interrupt starts a new measurement when trig- To avoid lengthy pauses in program flag when the conversion is complete, gered by the RD5 output signal. When execution, a state machine is used to triggering a call to the ADC interrupt the ECHO signal goes high, the cur- control the sonar board operation (see handler. The ADC interrupt service rent Timer1 count is captured via Figure 4). The state machine is executed routine averages the same channel n input pin RC2 and retrieved by the at a period of 5 ms from the Timer2 ISR. times. When the average limit is associated CCP1 interrupt ISR. The state machine can run for either reached, it increments the ADC chan- single sonar measurements or a burst nel number and the process repeats. SOFTWARE DESIGN mode. The sensor’s firmware is designed to The ADC ISR is configured to use TIME INTERVAL MEASUREMENT provide control and communications interrupts to signal an end of conver- The ECHO output of the Polaroid by polling from a remote host. Hard- sion. A scheduler in the Timer2 ISR board connects to the RC2 timer/cap- ware interrupts are used to enable a controls the update rate. The ADC read- ture input of the PIC18F452 micro- real-time response. The firmware pro- ings can be averaged if desired. This controller. The 1-MHz time base for vides convenient access to the con- way, the firmware always has a set of Timer1 is derived from the 4-MHz troller EEPROM to permanently store freshly updated analog values available

22 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 23.qxp 4/2/2008 2:01 PM Page 1 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 24

address. If the address matches, the actual command interpreter is called. This parses the command string and exe- cutes commands and parameters sequen- tially until all commands are processed. It is possible to send multiple commands in one transmission. For example, send- ing \nU10VA3XI3\r\n would be execut- ed in sequence until all command letters are processed. With the above example, the unit would respond with \nURC V2.00, 31-Oct-07 315 13r\n. Con- catenation of commands is useful when you want to reduce the communications overhead and improve efficiency. The firmware maintains a status word to monitor system operation. A variety of information such as temperature sen- Figure 5—This is a plot of the snowfall from November 2007 to the end of February 2008. Occasional poor snow reflectivity after a fresh snowfall shows up as a sensor failure and zero output at random intervals. Also note the sor malfunctions, loss of target, target wide temperature swings. too close, temperature controller failure, heater state, and low DC supply voltage, are available. In normal operation, all when needed and never needs to wait how the query returns its data. For bits are zero. Any non-zero bit consti- for ADC conversions to complete. example, \nU10A\r\n returns all ana- tutes an abnormal situation. Refer to the The RX UART is set up to generate log fields. Sending \nU10A2\r\n Help file for more documentation. an interrupt whenever a new character returns only the analog field two. is received. The associated receive Sending \nU10A2,4\r\n returns ana- SENSOR CONFIGURATION data interrupt service routine main- log value fields two to four. The sonar snow depth sensor is tains a command buffer for the com- For instance, sending the request housed in a modified insulated stain- mand processor. No TX ISR is used to firmware version command U10V\r\n to less steel coffee mug. I chose the mug buffer outgoing data. the sensor would return \nURC V2.00, because it was inexpensive, would The Timer2 ISR provides the master 07-JUL-11\r\n. Sending \nU10A2 provide reliable protection against the timing for the various tasks of the sys- returns the analog voltage on channel elements, and was the perfect size. An tem. The Timer2 (ISR) is configured to AN2 with \n1023\r\n. The leading \n externally mounted temperature sen- execute at a period of 5 ms. The ISR is character is not strictly required when sor inside a solar radiation shield pro- responsible for scheduling several using a terminal program for manual vides temperature input to allow com- activities: triggering the ADC to start testing, but it is mandatory for reliable pensation of change in the speed of a new measurement, sonar measure- stand-alone system operation when sound versus temperature. The snow ment rate, heartbeat timing, tempera- you’re using another computer for data sensor electronics assemblies are split ture control timing, heater resistor communications. It functions as a delim- up into several sections. PWM, and hardware I/O updates. iter for the beginning of a new command. The snow depth sensor is mounted Some commands require parame- about 4.5′ above a 2′ × 4′ piece of ply- COMMAND PROCESSOR ters. They are sent in the format wood with four legs made of 0.5″ gal- The sensor uses a simple command \nU10cn,m\r\n, where c is the com- vanized electrical tubing. Because set to respond to commands from the mand letter, n is the index, and m is Edmonton, Canada, seldom receives host system. Please refer to the pro- the new value. more than 3′ of snow in the winter, gram Help file (son_cmds.txt on the To change an EEPROM parameter, the chosen height was considered ade- Circuit Cellar FTP site) for an exten- send \nU10P5,16\r\n. Note that 5 is quate. It is important to remember that sive list of commands and additional the EEPROM register number and 16 due to the single transducer method information. The command processor is the new data. used here, the sonar transmit-to-receive responds to simple ASCII commands. The command processor is executed turn-around time imposes a minimum Command strings are divided into once each time the main loop repeats. target distance of about 45 cm. Other queries and commands. For example, If no new commands are received, it methods of sensor support can be used. \nU10V\r\n or \nU10A\r\n are returns without further action. If a new In many installations, the sensor is queries, while n\U10K0\r\n or command is received, it analyzes the mounted on metal tubing supported by \nU10P5,20\r\n are commands. received buffer content until the com- poles or support towers. The radiation Some queries can be used with or plete command has arrived. Then, it cone of the 600 series transducer can be without a parameter. They control compares the command prefix and easily calculated using the equation in

24 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 34.qxp 3/3/2008 4:00 PM Page 1

8DBE:I>I>DC :8A>EH:9 >bV\^cZVc^cYjhignÒghiB8JXVeVWaZd[deZgVi^c\Ydlcid%#.K#>bV\^cZ hdaji^dchi]ViVgZbdgZedlZgZ[ÒX^Zcii]Vcndji]dj\]iedhh^WaZ#>bV\^cZhbVaaZg [dgb[VXidghVcYadlZghnhiZbXdhih#>bV\^cZWZhi"^c"XaVhhiddahi]ViZcVWaZ ^bbZY^ViZhnhiZbYZh^\c#I]Vc`hidi]ZgZbVg`VWaZZc\^cZZg^c\\V^chd[djgcZla^cZ d[B8JÉh!ndjXVchide^bV\^c^c\VcYhiVgiXgZVi^c\ndjgcZmi\gZViegdYjXi#

MMM$I?B78I$9EC%FE?DJ/

BEM;IJ LEBJ7=; % =H;7J;IJ FEM;H ;;IJ

>CIGD9J8>C<I=:8-%*&;.mm/I=:;>GHIA>C:D;B8Jh 9:H>C

SIL-003_CC_8.375x11.125.indd 1 1/31/08 3:06:47 PM 2805014_oberforcher.qxp 4/9/2008 11:36 AM Page 26

the article “Ultrasonic Snow Depth It was not important to pack the data These may be difficult challenges to Sensors For Measuring Snow In The in a more compact format. Data trans- meet because some research on the U.S.” by Wendy Brazenec, Nolan fer to the Windows 2000/XP computer Internet has produced evidence that Doesken, and Steven Fassnacht.[4] uses a Windows-based parallel port these problems seem typical for The radiation cone size in feet is transfer utility program (Briggs Soft- sonar-based measurement. Perhaps, related to distance: works Link Maven). It’s easy to diligent further experimentation and remotely move the data and delete old research may solve some of the prob- Cone []radius = 0.194Cone( []height ) data files from the laptop’s hard drive. lems. Therefore, with the snow depth sen- A National Instruments LabVIEW- Monitoring snow height with an sor mounted at 4.5′, the cone diame- based program is planned to replace ultrasonic sensor proved to be an ter is 1.75′ and the chosen 2′ × 4′ ply- the MS-DOS-based QuickBasic log- effective method to record the local wood is large enough to contain the ging program to enable monitoring snow height over the course of a win- radiation beam. and control with modern computers. ter. Designing this instrument was Additionally, a web server interface straightforward due to the availabili- ENVIRONMENTAL PROTECTION might enable access from outside the ty of a suitable ultrasonic transducer Because the electronics compart- home. Practical guidance for siting and interface chips. The microcon- ment is hermetically sealed, a desic- and mounting a snow depth sensor is troller provided essential peripheral cant pack is used inside to prevent offered in the documents listed at the support to enable accurate measure- internal condensation. The desiccant end of this article. ment of time intervals, whereas pack is replaced at the beginning of using C language allowed speedy each winter. It reduces internal rela- SNOWFALL RECORDING development and experimentation. tive humidity to about 10%. It should An example of the snowfall The address-based communications be renewed when the RH inside the received in Edmonton in the winter of protocol allowed easy integration sensor exceeds 30%. A measurement 2007–2008 is shown in Figure 5. I with an existing weather station. strip can be left inside the sensor to think this is a good place to point out Although the recorded results were monitor the RH. a couple of distinctions about the accurate most of the time, more The transducer is housed in a com- recording of snowfall. This is the work needs to be done to address the partment inside a machined Delrin amount of snow that has fallen since problems caused by wind and poor base housing. It is sealed from the the first flakes have fallen. To obtain snow composition. The acoustic electronics compartment. A tiny hole the new snowfall, the data should be reflectivity and absorption of fresh to the outside provides air pressure graphed and then examined for steps snowfall varies widely and presents venting to prevent electrical shorts of in the graph. The difference in reading challenging problems. Commercially the transducer membrane due to air for each step is the new snowfall available sensors seem to suffer from pressure variations. An outside amount. the same problem.[1, 2] Perhaps some shroud offers some protection of the To accurately determine the snow research will help improve sensor sensor opening from moisture blown depth, the data file should be graphed performance. sideways by strong winds. An o-ring in a program such as Excel and exam- Integrating the physical design into provides a hermetic seal for the elec- ined for the beginning and end of each an insulated stainless steel coffee mug tronics compartment. snowfall event. The difference of each was a good idea. The affordable mug event should be added up to obtain has served well as a durable electron- SONAR OPERATION the total snow depth. Due to melting, ics shelter. Thus far, the system has The snow depth sensor requires a a loss of snow depth occurs. survived two winters without any host program that polls the sensor peri- sign of transducer deterioration. I odically. The weather station uses an IMPROVEMENTS TO COME old second-hand 25-MHz 386-based The observed signal losses due to Gerhard Oberforcher received his low-power laptop computer for low- wind and low-density snow require education in the 1970s as an indus- power consumption. The computer investigation. Wind has produced a trial electronics technologist in uses only 0.5 A at 12 V with the dis- loss of signals due to the target sig- lower Bavaria, Germany. He has play off. The original hard drive was nals being deflected, preceded by a over 30 years in the electronics replaced with a 64-MB flash memory rapid loss of target quality indica- industry, and he has worked with IDE 2.5″ drive to avoid mechanical tions. Wind can also degrade the dis- industrial embedded control elec- wear out. The logging and display pro- tance accuracy somewhat. Also, the tronics since 1998. Gerhard current- gram was written in compiled sensor occasionally stops working due ly develops embedded control sys- Microsoft QuickBasic Version 4.5. The to an insufficient echo signal after tems for Dycor. In his free time, he logging program is configured to output some types of new snowfall. The vari- enjoys VHF to microwave ham radio the data in a Microsoft Excel-compati- ability of the snow’s composition also experimentation and weak-signal ble, comma-separated format for easy seems to affect reflectivity, resulting communications, developing meteo- importing into a spreadsheet program. in poor sensor performance at times. rological instruments, researching

26 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805014_oberforcher.qxp 4/14/2008 9:54 AM Page 27

old technology, and trying to build Temperature Sensors,” DS006685, LM2596 Voltage regulator, LM2936 high-stability frequency sources. His 2000. voltage regulator, and LM34CAZ tem- web site is devoted to old German perature sensor Philips Semiconductors, “TL431C amateur radio equipment and tech- National Semiconductor Corp. Datasheet: TL431C, TL431AC, nology (www.ve6aqo.no-ip.com). www.national.com TL431I, TL431AI, LM431AC Adjustable precision shunt regula- PROJECT FILES 600 Series instrument transducer tors,” 853–1927 17795, 1997. To download code, go to ftp://ftp.circuit SensComp, Inc. www.senscomp.com cellar.com/pub/Circuit_Cellar/2008/214. SOURCES REFERENCES PIC18F452 Microcontroller TL851CN Sonar ranging control Microchip Technology, Inc. Texas Instruments, Inc. [1] Campbell Scientific, Inc., “SR50 www.microchip.com www.ti.com Sonic Ranging Sensor Instruction Manual,” 2007, www.campbellsci. com/documents/manuals/sr50.pdf. [2] W. Brazenec, “Evaluation of Ultra- sonic Snow Depth Sensors for Automated Surface Observation Systems (ASOS),” M.S. thesis, Col- orado State University, 2005, http://ccc.atmos.colostate.edu/ pdfs/Brazenec_Thesis_ALL.pdf. [3] SensComp, Inc., “6500 Series Rang- ing Modules datasheet,” 2004, www.senscomp.com/specs/6500% 20module%20spec.pdf. [4] W. Brazenec, N. Doesken, and S. Fassnacht, “Ultrasonic Snow Depth Sensors for Measuring Snow In The U.S.,” Colorado State Uni- versity, http://ams.confex.com/ams /pdfpapers/101687.pdf. RESOURCES Maxim Integrated Products, Inc., “Low-Power, Slew-Rate-Limited RS- 485/RS-422 Transceivers,” 19-0122, 2003. Microchip Technology, Inc., “PIC18F852 Data sheet: High-Perfor- mance, Enhanced Flash Microcon- trollers with 10-Bit A/D,” DS39564C, 2006. National Oceanic and Atmospheric Administration’s National Weather Ser- vice Forecast Office, “Snowfall Measur- ing Procedures,” www.crh.noaa.gov/jkl /?n=snow_measurement. National Semiconductor Corp., “LM2596: LM2596 Simple Switcher Power Converter 150 khz 3a Step- Down Voltage Regulator,” DS012583, 2002. ———, “LM34: Precision Fahrenheit

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 27 56-57.qxp 7/2/2007 10:52 AM Page 1 56-57.qxp 7/2/2007 10:52 AM Page 2 winners.qxp 4/9/2008 11:44 AM Page 30

WINNERS ANNOUNCEMENT The WIZnet iEthernet Design Contest 2007 gave engineers throughout the embedded design community a chance to join the Ethernet revolution while competing for a share of $15,000 in cash prizes and international recognition. Designers from around the world quickly stepped up to the challenge by incorporating WIZnet’s W5100 hardwired TCP/IP Ethernet controller in innovative embedded projects. Within weeks of the contest launch, designers began submitting their exciting, next-generation, Ethernet-enabled embedded systems. After spending many long days and nights closely studying the entries and judging them on their technical merit, originality, usefulness, cost-effectiveness, and design optimization, the judges presented their scores to the contest administrator. The results are now final, and we’re proud to announce the winners.

Congratulations to everyone who took part in the contest!

FIRST PLACE Drip Irrigation Controller The irrigation timer with advanced planning (ITAP) is a truly next-generation irrigation con- trol system. Featuring a WIZnet WIZ810MJ net- work module and an Atmel ATmega168, the innovative controller provides user interaction through a standard web browser. As a result, the system doesn’t have a keyboard or an LCD. The single-controller unit can manage up to eight zones. No software installation is required. Its functionality is split between the browser-based user interface and the hardware-based web serv- er, data model, and control logic. The web server is used to read and write the internal data model. Its other function is to return files stored in “My project is an irrigation timer. Timers are simple devices, but their internal program memory. Precision irrigation user interfaces are unreasonably complex. An Ethernet connection made control is now a reality because the system pro- it possible to correct this imbalance by using a remote browser in place of vides useful information such as watering schedules a local LCD and keypad. Once browser-connected, it was possible to add ‘what if’ planning tools that would be unthinkable on a stand-alone device. and zone activity. The hardware is simply an ATmega168, a ULN2803 driver chip, the WIZnet module, and not much else. I had been looking at various ways of adding browser support to a USB-based design. Previously, I had rejected Thomas Bereiter Ethernet for either cost or complexity reasons. When the design contest Italy [email protected] introduced the WIZnet module, it was instantly clear that it would great- ly simplify the design. With the WIZnet module, I could keep the parts count down and not waste scarce flash memory on networking code.” — Thomas Bereiter

To see these projects and more, visit www.circuitcellar.com/wiznet/. winners.qxp 4/9/2008 11:44 AM Page 31

SECOND PLACE LED News Ticker The handy LED News Ticker brings the news to you by display- ing up-to-date headlines in a scrolling format. The system fea- tures a main board and eight slave boards attached to dot-matrix LED displays. The main board features a Microchip Technology PIC18F2525 microcontroller connected to a WIZnet WIZ810MJ Ethernet module, which uses the W5100 to provide an easy-to-use interface to the Internet. The LED News Ticker requires no interac- tion to operate. Once powered up, the device immediately connects “The LED News Ticker consists of a main board that communi- to the Internet and downloads news updates every 15 minutes. It cates to eight individual slave boards. The main board is fairly handles all DHCP leasing and DNS resolving, allowing you to simple, using only a PIC18F2525 and a WIZ810MJ module to con- use dynamic IP addresses. nect to the Internet. Each slave board piggybacks to a single 8 × 8 dot-matrix LED display, which is controlled by a PIC18F2221. The main board scrolls news headlines across the display by manipu- James Blackwell lating data in a frame buffer that is sent to the slave boards. U.S. The WIZnet modules really simplified the design of my system [email protected] without sacrificing any usability. I plan on using them in future projects as well.” — James Blackwell

THIRD PLACE DMX Portal The well-designed DMX Portal is an affordable DMX lighting con- troller. You can use the novel system to remotely control up to 512 channels through an IP-based network or directly interface them to embedded systems with a serial connection. It was designed to be perfectly suited for designers who want to off-load DMX manage- ment and refreshes from the main system controller. It’s also useful for distributed lighting systems where low-cost Ethernet wiring is more practical than expensive RS-485 wiring. The prototype includes an external EEPROM for scene storage and a Microchip “The DMX Portal is a self-contained lighting controller for embedded systems and large distributed sys- Technology PIC18F4620 tems. I started this project because I wanted to be able to control moving lights and other special effects microprocessor. A WIZnet that use the DMX protocol from a system that was low cost and could change the lighting state based on digital triggers or simple commands from other systems. The WIZnet parts were a good fit for my design WIZ810MJ evaluation board for several reasons. I was already using the PIC’s hardware UART for my optional RS-232 interface, which is connected to the SPI on the required me to generate the DMX serial output completely in software. Since the DMX output requires PIC development board. precise timing to generate the correct bit rate, I need to disable all interrupts while the DMX data is being refreshed. The W5100 offers a very large buffer which is sufficient to store incoming commands arriving while the processor is unable to process the incoming data. Another reason the parts were a good Matt Ernst U.S. fit was that the chip handles all the tasks of receiving and transmitting a UDP packet.” [email protected] — Matt Ernst

FOURTH PLACE Remote Real Virtual Instrument Interface With the amazing Remote Real Virtual Instrument Interface, you can control any musical instrument with a MIDI input and capture its audio output over the Internet. You can also use the well- designed streaming media device to record audio if you don’t need MIDI. It features a WIZnet W5100 hardwired TCP/IP chip, a Ramtron VRS31L3074 microcontroller, and a Texas Instruments TLV320AIC23B audio CODEC. The system’s software is split into two parts: an embedded portion for the VRS31L3074 microcontroller and a PC portion for the “My project is a networked audio and MIDI interface that integrates VSTi plug-in. The PC-side software provides the interface with virtual music studio software that supports the VST standard. The host sends UDP packets with MIDI data over the network to the proces- to the virtual music studio software. sor and the processor outputs the MIDI data on its MIDI port. A syn- thesizer responds to the MIDI data by playing a sound. The audio CODEC Clemens Valens samples the synthesizer output and transfers the samples to the proces- France sor. The processor fills UDP packets with these samples and sends them [email protected] | www.polyvalens.com over the network to the host. The host then plays the sound. The W5100 allowed me to use simple hardware to build my project. I was actually looking into some kind of FPGA solution when this one came along. No need to sacrifice half of your processor power for a TCP/IP stack.” — Clemens Valens

To see these projects and more, visit www.circuitcellar.com/wiznet/. winners.qxp 4/9/2008 11:44 AM Page 32

HONORABLE MENTION Portable Network Service Monitor

This portable network service monitor was developed to help network “We built a handheld network monitor administrators supervise datacenters. The handy monitor—which fea- that is not only an inexpensive solution, tures a WIZnet WIZ810MJ module and an Atmel ATmega128 micro- but also an extremely flexible one. The controller—is equipped with a 4 × 20 LCD that can display important device consists of a WIZnet WIZ810MJ module, an Atmel ATmega128L microcon- messages from any configured server in a local network. It also troller, a power supply, a 4 × 20 LCD, and a continuously checks connectivity to predefined services on different TTL-to-RS-232 converter for debugging. machines. When problems occur, it triggers an alarm. The WIZ810MJ module fits quite well in an 8-bit TCP/IP-enabled design without external memories, thus saving money and Alexander Popov & Peter Popov space. We enjoyed working with the mod- Bulgaria ule because of the easy hardware inter- [email protected] facing and good how-to documentation.” — Alexander Popov & Peter Popov

ThermoNet The ThermoNet is a web-based, remote control, residential HVAC thermostat. The well-designed system includes an easy-to-use LCD front panel and a built- in web server. The front panel includes four buttons: Mode, Fan, Up, and Down. The hardware consists of a WIZnet WIZ810MJ module connected to an Atmel ATmega128 microcontroller external memory interface via direct memo- ry mapping. An Atmel DataFlash chip provides ample storage for embedded web pages and is easily updated with new web pages and other files via a Windows-based program.

Kevin Houser U.S. “ThermoNet is a web-enabled, dual-use project. It was designed and built to provide an easy-to-use web interface to manage heat- [email protected] ing and cooling energy usage, as well as water usage for irrigation. The primary parts used are an Atmel ATmega128, a WIZnet WIZ810MJ Ethernet engine, a Dallas RTC with 32 KB of nonvolatile static RAM, a 512 KB to 2 MB Atmel DataFlash memory, two temperature sensors, and a 2 × 16 LCD with LED backlight. The WIZnet parts were almost perfect for my project because they allowed me the freedom to implement any UDP or TCP/IP protocols I cared to develop or use. Many microcontroller-targeted Ethernet solutions are simply serial-to-Ethernet adapters or provide a canned web server implementation with limited expandability.” — Kevin Houser

FATE: Flexible Audio Transmission Over Ethernet This project addresses the idea of digital audio for the masses. The purpose of flexible audio trans- mission over Ethernet (FATE) is to set up a simple dedicated wired Ethernet network. You can then use the network to coordinate the distribution of high-quality audio signals throughout a building and the area around it. The useful design uses a full parallel bus interface to a WIZnet W5100 IC. The IC is memory mapped on the “auxiliary bus” (expansion bus) of the processor core. Its register values can be seen and manipulated at any time. Interrupts aren’t used.

John Clayton U.S. “My project is an atypical way of looking at audio distribution to speaker boxes. It separates the [email protected] audio signal from the raw power. That way, the power can be provided right at the speaker boxes, and the information signal can be transmitted to a set of surround-sound speakers directly, using dedicated CAT-5 wired Ethernet links. Digital audio is noise immune, and the mantra of my project becomes: ‘No more MONSTER cables! Use these cheap CAT-5 cables instead!’ I enjoyed the self- contained nature of the WIZ810MJ, especially the cool Ethernet jack with built-in pulse trans- former. I also liked the ‘auto-crossover-cable adjustment’ feature of the W5100 chip.” — John Clayton

Travel WIZard The incredible Travel WIZard is an embedded server application that helps you find airfare deals. The useful system uses Kayak, an online travel search engine, to explore the Internet. It then returns data that can be graphed to reveal the cheapest time of year to travel. The Travel WIZard features a WIZnet W5100 Ethernet controller and a Microchip Technology PIC24FJ128GA010 MCU, which resides on an Explorer 16 development board. The board includes a 32K × 8 serial EEPROM, LEDs, buttons, and a 2 × 16 LCD.

Matthew Pennell & Aaron Thomas U.S. [email protected] “The Travel WIZard is an embedded server data-mining application. It allows the user to acquire airfare data to look for trends in ticket price. The software is written in such a way so as to support eventual expansion to other automated Internet tasks. Ultimately, we wanted to see if we could design a customizable platform that could be programmed to do any type of automated online data mining task. In addition, of course, to the WIZ810MJ with W5100, the system consists of a Microchip Explorer 16 development board with a PIC24FJ128GA010 MCU and 32K × 8 serial EEPROM. From a hardware perspective, we appreciated how easy it was to prototype with the WIZ810MJ plug-in module. From a software perspective, we found it easy to quickly learn to use the W5100. We found the part to be an ideal tool for learning the nuts and bolts of how the Internet actually works under the hood.” — Matthew Pennell & Aaron Thomas To see these projects and more, visit www.circuitcellar.com/wiznet/. winners.qxp 4/9/2008 11:44 AM Page 33

HONORABLE MENTION Web Camera The versatile Web Camera system can take a picture at a resolution of 640 × 480 or 320 × 240, pan the camera horizontally and vertically, and change its IP and gateway address to match a network. Photos are taken with a C328 JPEG compression module, which serves as a JPEG-compressed still camera. The host can send a snapshot command to capture a full-resolution, single-frame still picture. The pic- ture is then compressed by the JPEG engine (OV528) and transferred to the host. After each photo is divided into 64-byte segments, a WIZnet WIZ810 Ethernet module transmits the packets over the Internet.

Minas Kalarakis “My project is a Web Camera whose images can be accessed using the Internet, instant messaging, or a PC application. The project Greece involves a PC application that enables the user to access and control the camera. The user can rotate the camera vertically and hori- [email protected] zontally via the PC-based application. The heart of the Web camera is a Microchip dsPic30F4013 microcontroller, which puts the photos in packets and uses the WIZ810MJ module to send them to the Internet. The competition was a great opportunity to use the ready-to-use module with the W5100 chip on it.” — Minas Kalarakis

Time Server The well-designed Time Server keeps a master time and date clock that is synchronized to the U.S. WWVB time-code signal. It exists on the Ethernet network and serves time and date information accord- ing to the SNTP, DAYTIME, and TIME protocols. Client devices can connect to the system, request the time/date, and synchronize their local clocks. Because the Time Server doesn’t rely on Internet servers, it can be used in secure networks that aren’t connected to the Internet. A WIZnet W5100 provides the interface to the Ethernet network. A Freescale MC9S08QG8 microcontroller is used to decode the time- code pulse stream, update a real-time clock, and serve time/date information to clients on the Ethernet network.

Steven Nickels U.S. [email protected] “The Time Server is a fixed-function node on an Ethernet network that provides time and date information referenced from the NIST WWVB time-code radio signal. Once I developed the interface code that set up a socket connection, using the W5100 was very simple. I especially liked that I didn’t have to compile a huge Ethernet stack. The SPI interface was especially important in the Time Server design since I wanted to use a microcontroller with a low pin count. Additionally, since the TCP/IP stack is embedded in the W5100, I don’t have to worry about code integration issues, large flash and SRAM requirements, or license and royalty costs.” — Steven Nickels Greener Lawn: A Sprinkler Control System The well-made Greener Lawn system gathers historical weather data and forecasts and then makes intelligent watering decisions based on that data. The design features an ATmega128 processor con- nected to the Internet through a WIZnet WIZ810MJ. The weather forecasting and rainfall totals come from the National Weather Service’s FTP server. Linux shell and scripts gather the data and parse out the rainfall totals. This is stored as plain text files on the Linux web server. A PHP script running on an Apache web server enables you to configure the sprinkler controller. A second PHP script ties all of this information together into a single downloadable file that is requested by the WIZ810MJ.

Zack Clobes U.S. “A long-time pet peeve of mine has been watching underground lawn sprinklers running during a rain shower, or when it’s obvious that a [email protected] shower is coming at any moment. It seems like such a waste to consume that energy and water. The Greener Lawn sprinkler controller sys- tem aims to be smart enough to make some basic decisions about whether or not it’s a good idea to water the lawn. It consists of two pri- mary pieces: the controller and a web server. An ATmega128 processor connected to the Internet through a WIZnet WIZ810MJ is the controller that actually controls the pump and solenoids. I was able to offload all of the physical Ethernet packet handling to a separate ‘black-box,’ thereby allowing me to use the relatively simple and inexpensive microcontroller. Knowing that I had a good network controller that, with just a few lines of code, would start responding to ping requests expedited the development process.” — Zack Clobes

NIETO: An NCID and NTP Client The NIETO is an innovative network caller ID and NTP client. Featuring a WIZnet W5100 and an Atmel ATmega644, the system uses TCP to attach to an NCID server to retrieve and display caller ID information on an LCD. As an IP client, NIETO attaches to an NCID server and retrieves caller ID data over the Internet. The most recent call is always displayed.

Thomas Glembocki U.S. [email protected]

“I built NIETO in order to have a standalone box on my LAN to retrieve caller ID info without having to use a PC. The WIZnet W5100 provides four full TCP/IP sockets so that very little programming is needed to establish a TCP connection over Ethernet with a server. I was able to use the standard GCC C compiler WinAVR to open TCP sockets and send and receive data without any knowledge of what was taking place under the hood. The W5100 took care of all the Ethernet framing stuff and the TCP acknowledges, CRC checking and the like. It contains large enough buffers to handle TCP/IP frames without tying up precious CPU RAM space. In my case, all the CPU RAM was dedicated to storing caller ID data instead.” — Thomas Glembocki To see these projects and more, visit www.circuitcellar.com/wiznet/. 2805020_rusch.qxp 4/11/2008 11:10 AM Page 34

FEATURE ARTICLE by Miguel Rusch

THIRD PLACE CONTEST WINNER Where Analog And Digital Collide An Easy-To-Use LCR Meter

Miguel’s portable LCR meter makes it easy to analyze the analog performance of virtually any device under test, whether in the lab or on the job.The dsPIC30F4012-based meter uses DDS techniques and DSP methods to condition the resulting voltage and current signals. Its handy user interface and graphic LCD make it easy to operate and read.

In the back of my mind, I keep two idealize the component, leading to components, there are no markings on lists of tools that I would like to add very poor accuracies. chip capacitors, making identification to my electronics workbench. The There were two uses for an LCR impossible. Second, switching power first is made up of tools that I will meter that motivated me to add it to supplies are now used extensively. Mea- inevitably own one day. I just have to my wish list. First, I like to work with suring inductor characteristics such as wait for the right project to come up SMD components; however, even when the quality factor (Q) is critical to to justify the purchases. The second is using relatively large 8050 package ensuring efficient voltage conversion. I a wish list of things I will probably never justify or afford, such as a spec- trum analyzer, a hot air rework sta- tion, or a digital oscilloscope. An LCR meter was firmly on the second list until I decided to build one for the Microchip 16-bit Embedded Control 2007 Design Contest (see Photo 1). In this article, I’ll describe my design. As you’ll see, you can use digital methods to measure the frequency domain per- formance of passive components.

LCR METER Why an LCR meter? Over the last decade, digital multimeters have become commodity items, constantly dropping in price to almost implausi- ble lows. However, there is little avail- able for the hobbyist to characterize component performance in the fre- quency domain. For the most part, LCR meters have remained on the benches of research and development laboratories. Sure, some multimeters Photo 1—The dsPIC-based LCR meter prototype was built around Microchip Technology’s 28-pin 16-bit development include a capacitance measurement board. The system includes three other boards: a user interface board (front left), an analog board (front center), and function, but they use methods that an antialiasing filter board (front right).

34 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805020_rusch.qxp 4/9/2008 9:15 AM Page 35

action induces a volt- its position in time relative to the DUT DUT age across the feedback crossing. In practice, several points Voltage Current resistor that is propor- are evaluated and the results are aver-

1-kΩ Source tional to the current aged. Because measurements are resistance 1 kΩ flow through the DUT. made simultaneously, the relative – Device under test – + (DUT) The current and phase between waveforms is easily + voltage waveforms are evaluated. sampled simultane- There is an important caveat regarding ously. After correcting the use of the described method: it is any DC offset, the totally reliant on the data being a pure Figure 1—This is the basic circuit for making AC impedance measurements. zero-crossing point is sinusoid. Therefore, the applied test The voltages across and current through the device under test (DUT) are determined. The waveform must be a high-quality sinu- measured simultaneously. crossing point is first soidal source and the acquired data estimated by using a must not include any other frequency am sure that in addition to my initial linear regression between points on components. Both issues are addressed needs, you will have many other uses either side of the crossing (see Figure 2). with digital methods. First, the wave- for this tool. The maximum error of the method is form is accurately constructed using When I started the project, I wanted set by the ratio of the test frequency direct digital synthesis (DDS) technol- the LCR meter to be small, portable, to the sample frequency. An area on ogy. Second, the acquired data is band- and battery-powered, much like a either side of the initial guess is iter- limited using digital signal processing multimeter. I wanted to be able to test atively evaluated by applying the for- (DSP) filters. across a number of common frequen- mula: cies (100 Hz, 1 kHz, and 10 kHz) with THE BIG PICTURE a 1% basic accuracy. Finally, I wanted Figure 3 shows the main parts of the a clear and modern interface to display system. The core device is a Microchip the measurements to the user. Technology dsPIC30F4012 micro- The formula calculates the error processor, whose system clock is BACK TO BASICS between theoretical and measured val- derived from an external 6-MHz crys- Existing commercial LCR meters ues of points a0 and a1. The width of tal feeding an internal 16× PLL, result- use a number of methods to establish the search area is determined by the ing in 24-MIPS operation (see Figure 4). the real and complex components of error due to the initial guess. The step The oscillator frequency was chosen to AC impedance. Although measuring size applied to the previous equation allow ADC sample rates that were the total impedance (Z) is relatively determines the improved error. The exact multiples of the test frequency. trivial, phase information is more dif- point representing the minimum error The analog measurement block and ficult to obtain accurately. My design is the zero-crossing point. Using this a user interface block support the core makes simultaneous measurements of zero-crossing point, the waveform microprocessor. Extensive use of the the voltage and current and applies amplitude can be calculated based on SPI port was made to maximize func- simple trigonometric equations to the value of any measured point and tionality from the 28-pin dsPIC recreate and compare the device. For example, the waveforms. LCD’s 8-bit parallel port is Figure 1 is a simplified controlled by a Microchip depiction of how the Technology MCP23S08 measurements are made. SPI GPIO. The analog A sinusoidal waveform of block also consists of sev- a0 a known frequency is eral SPI devices, including buffered by an op-amp and two Microchip Technology then applied to the device MCP6S91 PGAs, an Ana- a1 under test (DUT) via a g log Devices AD9833 DDS source resistance. Current signal generator, and a flowing through the DUT Microchip Technology is directed to the inverting MCP41010 10-kΩ digital input of a second op-amp. potentiometer. The chip The output voltage of the select (CS) signal between

op-amp ensures that the dt the digital potentiometer current flowing through and the GPIO were able to the feedback resistor is be shared due to the Figure 2—Analysis of recorded data starts with determining the zero-crossing point. Initially, equal to that flowing a linear regression is made as a “guess” point. An iterative error function is then run in instruction set bit mask- through the DUT. That the neighborhood of the guess point to find the point of minimum error. ing, further reducing the

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 35 2805020_rusch.qxp 4/9/2008 9:15 AM Page 36

screw terminals. RCA plugs were dsPIC30F4012 User interface used because they are inexpensive and perform well at the test frequencies.

GPIO In the final design, four separate RCA 128 x 64 Graphic LCD plugs will be employed, each with their shield connected to the outer

SPI Module terminal to enable better noise immu- nity. The DUT is connected via a pair Control buttons (x3) Resistor ladder of parrot clips, which enable hands- arrangement 10-bit ADC free use for axial components. A tweezer test lead will be made for SMD parts.

CREATING A WAVE Analog input stage Creating the sinusoidal test signal Antialiasing filters (PGA) easily could have been the most diffi- cult part of this project. Luckily, I Device under test Direct digital synthesis (DUT) waveform generator found an effective solution in the form of an AD9833 DDS signal gener- ator chip. The device runs as a SPI Figure 3—The dsPIC30F4012 core communicates with five devices in the analog stages and the user interface via slave whose 10-bit DAC outputs a a SPI. User input is made by switches in a resistor ladder that is digitized by the ADC module. square, triangle, or sine wave based on an internal 28-bit frequency-setting required pins. User input requires only contains the analog measurement register and an external clock signal. a single pin because control buttons components. The antialiasing filters A DDS chip enables the creation of are interfaced to the ADC with a are constructed on a separate proto- waveforms over a wide frequency resistor ladder. board. Jumper wires connect the range with low distortion and requires The prototype system was built boards. no additional filtering. The master around Microchip’s 16-bit 28-pin The DUT is connected via a set of clock signal for the DDS chip was cre- development board. I also built three test leads to the analog board. The ated from the dsPIC30F4012 PWM port. other boards (see Photo 1). One board prototype used RCA connectors The clock frequency was set at 1 MHz carries the user interface, which con- between the four-wire test leads. The to deliver both good frequency resolu- sists of a graphic LCD and control but- PCB cable shielding is connected to tions from the 28-bit control register tons. Another custom-etched board the analog ground plane by a pair of and minimize noise transfer to the

Figure 4—The prototype was built around a modified Microchip 16-bit 28-pin development board. The remaining schematics are available on the Circuit Cellar FTP site.

36 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805020_rusch.qxp 4/9/2008 9:15 AM Page 37

measurement’s frequencies. Microchip Technology

MCP6022 op-amp—to minimize Signal + Noise + ANALOG STAGES source impedance. For this project to be effective, I had The op-amp stages need lead to get heavily involved in the black art compensation by way of a small- Low-pass –61-dB Attenuation antialiasing filter from 10 kHz to of analog design. The nature of this capacitance (47 pF paralleled 50 kHz device requires high accuracy and low with the feedback resistor). This 6th Order analog (Butterworth) filter noise amplification over a wide range was necessary to ensure stability, of gains. Because considerable amplifi- especially for stages with mini- cation is required for devices at either mal gain. The capacitor value 10-bit ADC 100-kHz Sample rate extreme of the impedance spectrum, was carefully chosen to not + input offset and other errors can easily attenuate the test frequency. saturate op-amp outputs. With this in The previous stage output is 1-kHz Test 100-kHz Test mind, the bipolar sections of the ana- centered on 2.5 V but still 10-kHz Test frequency frequency log circuit were handled via Analog requires additional gain for frequency Devices AD8629 zero-drift op-amps impedances greater or smaller whose 1-µV offset and 0.002-µV/°C than the source resistance. The 32-Tap LP FIR + 48-Tap LP FIR + drift are orders of magnitude below signal is amplified in binary steps Decimate x 8 Decimate x 16 the expected signal range. (e.g., 2, 4, 8, 16, and 32) by a The task of the first analog stage is Microchip MCP6S91 SPI PGA. to condition the test signal. The signal The reference pin for this op-amp 8-Tap IIR + 8-Tap IIR + 8-Tap IIR + from the DDS chip is approximately is tied to the same 2.5-V reference Butterworth BP Butterworth BP Butterworth BP

0.3 VPP, and its common mode voltage voltage as the previous stage. (CMV) is approximately 0.3 V. The sig- The non-ideal realization of Minimal noise nal is fed through a single-order, low- the design is caused by the high- signal pass RC filter to further isolate clock frequency impedance of the noise. From there, it is directed to the DG418L analog switch, a quanti- Figure 5—Test waveforms are first passed through antialiasing filters (sixth-order Butterworth) before being digitized by the 10-bit inverting input of an AD8629 op-amp. ty not covered in the specifica- ADC at 100 ksps. Down-sampling and FIR low-pass filtering is The op-amp is configured to generate a tion sheet. At 10 kHz, the switch performed on data from the 100-Hz and 1-kHz tests. The final stage before data analysis is IIR band-pass filtering. nominal 1-VPP signal with 0-V CMV. displays approximately 3-dB The required offset is achieved via a attenuation and also introduces voltage present on the non-inverting additional phase shift. Both have to be on the test frequency. In the case of a input that is adjusted by the MCP41010 compensated for. A more suitable com- 10-kHz test, the signal is passed 10-kΩ digital potentiometer. ponent with a higher cut-off frequency directly to an IIR band-pass filter that The resultant signal from the first will be substituted in future revisions. limits the bandwidth to only the fre- stage is fed via a 1-kΩ 0.1% source quency of interest. In the case of the resistor to the DUT. A four-wire SIGNAL CONDITIONING 1-kHz and 100-Hz tests, the signal Kelvin clip test lead is used to mini- The flow of signal conditioning must first be low-pass, FIR-filtered, mize the effects of the lead resistance. stages is illustrated for each test fre- and decimated. The rate of decimation The test signal passes through the quency in Figure 5. Before being sam- is dependent on the test frequency, DUT and into the inverting input of a pled by the dsPIC ADC, each signal is either at a rate of eight or 16. Decima- ground-referenced AD8629 op-amp. passed through an LP antialiasing fil- tion is required in this system at The current flowing through the device ter to ensure that the Nyquist-Shan- lower test frequencies to minimize is then imposed as a voltage across the non sampling theorem criterion is the size of data needed to represent a 1-kΩ 0.1% feedback resistor. met. In this case, the sample rate (Fs) single test cycle. It allows compliance The differential signals for voltage is 100 kHz and the ADC is 10 bits; with Nyquist criterion while only and current are directed to separate therefore, the filter needs to reduce relying on a single antialiasing filter. differential instrumentation-style the signal strength by approximately amplifiers constructed of three 61 dB between 10 kHz (highest fre- USER INTERFACE AD8629 op-amp sections each. The quency of interest) and 50 kHz (Fs/2). You interact with the device via gain for this stage is selectable via a This task was achieved by a sixth- three control buttons. You receive Vishay Intertechnology DG418L ana- order Butterworth filter. Microchip’s information via a 128 × 64 pixel log switch, resulting in either G = 2 or free FilterLab 2.0 was used to design graphic LCD using a Toshiba T6963C G = 128. The final op-amp in this dif- this filter and generate the passive chipset. The eight data lines are driv- ferential configuration is referenced at component values. en via an MCP23S08 SPI GPIO. The 2.5 V—provided by a Microchip Once the signal has been suitably RD signal is supplied as an inversion Technology MCP1525 precision volt- band-limited, it is digitized by the 10-bit of the WR signal via a general-purpose age reference and buffered by a ADC. The next action is dependent NPN transistor rather than using an

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 37 2805020_rusch.qxp 4/9/2008 9:15 AM Page 38

additional GPIO line. The two remain- and then only the last few frames are Following offset correction and band- ing control lines, CE and C/D, are driv- stored for further analysis. pass filtering, the dataset is scanned for en directly from general I/O pins. I used FastAVR’s FastLCD V1.2.0 to the maximum value. If it’s below a pre- The screen contrast is controlled by create the graphics displayed on the set threshold, the gain is increased a connection to a PWM pin clocked at LCD (see Photo 2). The free program (doubled) and the acquisition starts 1 MHz (required for DDS operation). enables you to quickly create and pre- again. This process is continued until Currently, the contrast is not user- view graphics before exporting them either a suitable gain is found or the adjustable, although this functionality as a text file in a number of formats, maximum gain is reached. will be added in a later revision. Simi- including one suitable for the Toshiba The second loop within the test larly, backlighting control is not chipset. Graphics were stored in pro- function acquires data in a similar implemented in the prototype. This is gram memory as constants, represent- way to the previous loop, correcting required to improve battery life. ing a sizable amount of data. the offset and filtering the resulting array. The main difference is that FIRMWARE TAKE A MEASUREMENT additional code is executed to calcu- I wrote the system’s code in C and Figure 6 illustrates a simplified pro- late the crossing point and from this compiled it with the contest version of gram flow for the function call that the impedance and phase angle. The Microchip’s C30 compiler. Code was performs each test. The first tasks number of times the loop executes is developed as many individual func- involve setting the ADC module, set- dependent on the argument passed to tions, which could be tested in isola- ting the DDS chip for the desired fre- the function. tion. Developing the code in small quency, and setting the gain for both Calculations of the parameters other pieces was necessary because the pro- channels to a minimum value. The than impedance and phase angle are gramming tool I used (PICkit 2) did function of the initial acquisition loop is made within RUN_TEST(). This calcula- not support the debugging of dsPIC to auto-range the gain for each channel. tion is dependent on the circuit model devices. Coefficients for the DSP filters were designed using Momentum Data Sys- Initialize ADC tems’s dsPIC FD Lite. The resulting assembly files from this program have Initialize DDS output to be slightly modified to suit versions

of MPLAB C30 v1.30 and higher Initialize gain (low setting) because the standard declarations used

are no longer allowed by the compiler. Acquire samples Before using a digital filter on a

small data sample, its delay line has Correct offset to be set appropriately. Because the

initial value of the acquired dataset Band-pass filter could lie anywhere within the sinu- soid, there is a chance the data could Increase gain Sufficient appear to the filter as a step input, N gain? which would cause ringing throughout Y the dataset. The process of setting the Acquire samples delay line involves running a set of data whose length is an exact multiple Correct offset of the period many times through the filter and ignoring the resulting output Band-pass filter data. Setting the delay line for IIR filters Calculate phase & impedance in this way doesn’t present problems; however, the actual frequency of the Sufficient “100-Hz” test was adjusted to Sum result with previous N results? 100.80635 Hz to present an exact sinu- Y soid period with an integer-sized data Divide result by num samples set. The FIR filters used for down-sam- pling cannot use recorded data because Reset DDS output there is a strict requirement on the cycles between ADC buffer flags. Instead, the initial 50 cycles of the filter Figure 6—Two main loops make up the program structure that performs tests. The initial loop auto-ranges the analog use fresh data to set up the delay line stage gain before the second loop makes a complete measurement.

38 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805020_rusch.qxp 4/9/2008 9:15 AM Page 39

capacitance represents an impedance prototype as a fixed (e.g., 2 V) bias that value significantly above the measure- is isolated from the measurement ment ceiling. Future revisions of this equipment by small-value DC-blocking design will add a calibration cycle to capacitors. measure and compensate for the paral- Input overload protection is another lel capacitance. feature that is especially important for large electrolytic capacitors. It is easy FURTHER DEVELOPMENT to add to the design. When the DUT is To correctly measure the impedance, connected, stored energy in the device or more importantly the equivalent will discharge into the measurement Photo 2—Test results are displayed on the graphic LCD. Graphics were created with FastAVR’s free program series resistance (ESR) of electrolytic circuit. Effective protection can be pro- FastLCD V1.2.0. The data was exported in a format to capacitors, a DC-bias voltage must vided by varistors or Zeners coupled suit the Toshiba T6963C chipset and stored as constants be applied. I’ll add this to the next with forward-biased diodes. in program memory.

under consideration. Auto mode attempts to first check if the Parallel mode is suitable (small capacitance); otherwise, the series model is used. The resulting parameter values are recorded to a global structure. A call to functions within the graphics module displays the values within this structure. It also dis- plays the circuit elements graphically.

SYSTEM PERFORMANCE The prototype system’s performance is very pleasing. The user interface is easy to use, push button operation is handy, and the graphic LCD is clear and easy to read. Measurements appear to meet the required accuracy (less than 1%), and repeatability is excellent. Because the system can automatically choose the most suitable frequency and circuit type, making basic measurements is very easy. Currently, the program implements a five-cycle averaging function on the result to improve stability and accura- cy. While this is a useful function, it has the disadvantage of increasing the overall test cycle time. A test on “automatic” will take up to 5 s to fin- ish. A fast test feature is needed in the next prototype to enable quick sorting of parts at a lower accuracy. Typically, LCR meters implement short-circuit and open-circuit calibra- tion. Tests on this device have shown that use of the four-wire method has resulted in a series resistance error that is significantly less than the lower- limit impedance that can be measured. Open-circuit tests, however, have shown that there is approximately 3.5 pF of parallel capacitance in the test leads. At frequencies below 10 kHz, this

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 39 2805020_rusch.qxp 4/9/2008 9:15 AM Page 40

The final version of this project will Contest, visit www.circuitcellar.com RESOURCES be incorporated into a multimeter- /microchip2007/. style enclosure. It will include bat- Agilent Technologies, Inc., “Imped- tery power for portable use. ance Measurement Handbook,” 2006, Author’s note: I want to express my http://cp.literature.agilent.com/litweb/ WHAT’S NEXT? gratitude to Circuit Cellar and Microchip pdf/5950-3000.pdf. Technology for running the Microchip This project was my first implemen- 16-Bit Embedded Control Design Con- Analog Devices, Inc., “A Technical tation of embedded DSP technology. It test. It was a fantastic experience. Tutorial on Digital Signal Synthesis,” was also my first introduction to 1999, www.analog.com/Uploaded Microchip’s 16-bit processors. The Files/Tutorials/450968421DDS_ toolchain and development tools sup- Miguel Rusch lives in Melbourne, Tutorial_rev12-2-99.pdf. plied by Microchip made coding this Australia, with his wife Katherine. Hitachi, “Application Note AN-029: type of controller quick and painless. He earned a Bachelor of Engineering Interfacing and set-up of Toshiba The compiler was easy to use and all of (Mech) degree from Monash University T6963C,” 2004, www.hitachi-displays- the library files were well-documented. in 2004. Currently, Miguel is work- eu.com/doc/AN-029_Interfacing_and_ I’m pleased that I can now cross the ing in the automotive industry, set-up_for_Toshiba_T6963C.pdf. LCR meter off of my wish list. In addi- where he has several years of design K. Lacanette, “Application Note 779: tion, while adding a new and valuable experience. One day he hopes to con- A Basic Introduction to Filters— tool to my workbench, I have learned a vert his all-consuming electronics Active, Passive, and Switched-Capaci- great deal about both analog and digital hobby into a real job in the embed- tor,” National Semiconductor, Corp., design. Now I look at the remaining ded arena. You can contact Miguel at 1991, www.national.com/an/AN/AN- items on my wish list and wonder [email protected]. 779.pdf. which tool I should attack next. Per- Texas Instruments, Inc., “Stability haps a dsPIC spectrum analyzer! I PROJECT FILES Analysis of Voltage Feedback Op-Amps Including Compensation Techniques Editor’s note: To learn about the other To download code and additional files, Application Report,” SLOA020A, 2001, projects that placed in the Microchip go to ftp://ftp.circuitcellar.com/pub/ http://focus.ti.com/lit/an/sloa020a/ 16-Bit Embedded Control 2007 Design Circuit_Cellar/2008/214. sloa020a.pdf.

SOURCES AD8629 Op-amp and AD9833 wave- form generator Analog Devices, Inc. www.analog.com

FastLCD V1.2.0 FastAVR www.fastavr.com

dsPIC30F4012 Microprocessor, Filter- Lab 2.0, MCP23S08 SPI, MCP41010 dGPIO, MCP6022 op-amp, MCP6S91 PGA, MPLAB C30 compiler, and PICkit 2 programmer Microchip Technology, Inc. www.microchip.com

dsPIC FD Lite Momentum Data Systems, Inc. www.mds.com

T6963C Chipset Toshiba America, Inc. www.toshiba.com

DG418L Analog switch Vishay Intertechnology, Inc. www.vishay.com

40 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 41

FEATURE ARTICLE by Steve Lubbers Electronic Data Logging And Analysis A How-To Guide For Building A Seizure-Monitoring System

Steve’s electronic monitoring system enables pet owners and vets to monitor the patterns of epileptic seizures in dogs. The real-time, ATmega32-based system logs the number of seizures and measures the time between them.

My canine companion, Princess In this article, I’ll describe the Xenia, Ohio, I learned that a seizure (or Leia, often spent her days curled up in design. You can build a similar system epilepsy) is essentially a “short circuit” the corner of my electronics dungeon for your dog, or you can use the design of normal brain activity. An epileptic wondering what was so amazing and principles I’ll describe to build a moni- seizure is a body’s physical response to fascinating about wires and electronic toring system to suit your needs. the short circuit of the control center. circuits. She figured that a long walk This occurs in a host of living crea- with a squirrel to chase would be ANATOMY OF A SEIZURE tures, including humans and dogs. much more fun. Then, one sunny sum- During a series of conversations Secondary epilepsy occurs when mer evening, she entered the dungeon, with Linda Truman, a local veterinari- there is an underlying cause for the looked up at me, and began to convulse an at Docton’s Animal Clinic in seizure. It is treated by identifying and uncontrollably! She was experiencing her first epileptic seizure. Later, I wondered if all of my wires and chips could be used to help her in her hour of need. Research showed that of the 55 million dogs that are household pets, 2.2 million suffer from canine epilepsy! That rep- resents a lot of worried pet owners consulting their veterinarians for reg- ular treatment. Could I design a system that has the potential to improve the life of millions of dogs? With this question, I began the process of creating what I call the a) b) “Doggie 911,” which is an electronic monitor for Photo 1a—My dog Princess is wearing the prototype of the Doggie 911 monitor. The data says “No Seizure Today!!!” b—The monitor K-9 epilepsy (see Photo 1). mounts inside a plastic container.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 41 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 42

The actual seizure (the ictus) is indi- cated by intense physical activity as Y Doggie Logger the brain “short circuits.” The ictus Sensor Storage PC lasts between several seconds and sev- X platform eral minutes. The final stage of the Offline analysis Linear seizure is called the ictal stage. During IR Link the ictal stage, the intense physical

Real-time Seizure Mobile device activity abates over minutes to hours. analysis records Instrumented pet (e.g., PDA) The ictal stage continues until the patient returns to “normal.” Phone dialer In the case of minor and infrequent K-911 seizures, nothing needs to be done. Phone The seizure will pass and the dog will return to its happy, normal self. In the case of frequent seizures or seizures Figure 1—The system is made up of two components, a data logging system and a real-time data analysis system. that last for an extended period of They combine to create an electronic monitor for canine epilepsy. time, the seizure can cause the brain to overheat and can be fatal. In these cases, medication is needed to prevent attending to the underlying condition. Truman also told me that seizures the seizures from starting so they Idiopathic epilepsy is diagnosed when progress through four basic stages as don’t progress to a fatal stage. there is no known cause for the the patient progresses from an initial Immediate medical treatment is rec- seizures. In many cases, idiopathic mood change, to a seizure, and finally ommended if a single seizure’s ictus epilepsy is inherited or inherent to returns to normal. Stage one is the pro- stage lasts longer than 5 minutes or if specific breeds of dog. Because I’m drome. This stage may occur hours or more than one seizure occurs within a talking about pets and not human days before the actual seizure. The pro- 24-hour period. Medication is usually beings, the cost considerations for the drome is exhibited by a mood or behav- prescribed for an animal that experi- testing and treatment of secondary ior change. The aura signals the start of ences seizures more frequently than epilepsy can cause a veterinarian to a seizure. The aura is indicated by once every other month. simply treat secondary epilepsy as physical symptoms such as salivation, The veterinarian asks two impor- idiopathic epilepsy. trembling, whining, and nervousness. tant questions to determine if the

a) Idle and seizure spectrum 5000 4500 4000 8 Hz 3500 3000 18 Hz 2500 28 Hz 2000 38 Hz

Magnitude 1500 48 Hz 1000 500 0 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101 106 111 116 2-Second time slices

b) Treat spectrum 5000 4500 4000 5 Hz 3500 3000 18 Hz 2500 28 Hz 2000 38 Hz Magnitude 1500 48 Hz 1000 500 0 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 2-Second time slices

Figure 2—A set of discrete frequency components can be used to help identify a dog’s activities. The graphs show the magnitude of five discrete frequencies with respect to time. The more motion the dog has at a particular frequency, the higher the magnitude peak.

42 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 43

seizures can be ignored or if a life- Slow loop time of medication should begin: Fast loop How often do the seizures occur and Init @ 10 ms how long do they last? The Doggie 911 system can answer these ques- Update async timers tions. Hardware diagnostics

SYSTEM OVERVIEW Get acceleration After observing several of

Princess’s seizures, I noticed that External drivers there was a distinctive tremor run- Frequency detection ning through her body during the active (ictus) portion of the seizure. I Seizure Data display wondered if the pattern was unique evaluation and could be used to detect the

occurrence of her seizures. I came up Seizure record(s)

with a design for a system that Start/stop would automatically detect the recording Record data seizures. The ultimate goal was to to flash detect the presence of seizures,

record when they occur, and if possi- Done ble, to notify me when a seizure is in progress. The completed system contains a Figure 3—The Doggie 911 software is built from two simple control loops. A slow background loop performs housekeeping motion/vibration recorder called the chores and interacts with the user. A fast interrupt-driven loop reads the motion sensors and evaluates the motion “Doggie Logger” and a real-time data to detect a seizure. monitoring system (K-911) that detects and reports the presence of a infrared data link gives you access to I determined that my seizure record- seizure (see Figure 1). The Doggie the recorded seizure details. ings contain approximately 12 minutes Logger is made up of a sensor plat- of data. To record longer streams of form, data storage, and a data link for DATA LOGGING normal motion activity, I selected off-line analysis. The sensor platform The Doggie Logger is conceptually memory with several megabits. is a dual-axis accelerometer. The quite simple! A data logger is Tests were conducted by hooking accelerometer measures the motion attached to a motion sensor to record the Doggie Logger to Princess’s collar. and vibrations of an instrumented the motions of a dog. An initial sam- I then played games, went for walks, pet (see Photo 1a). A CPU constantly pling rate of 50 Hz was arbitrarily and generally got funny looks from the reads the acceleration (motion) val- chosen from the examples supplied neighbors because my dog had a ues and stores them in memory. An with an Analog Devices ADXL202EB strange device mounted on her head. RS-232 link is used to connect the accelerometer evaluation board. The An early prototype was destroyed by a Doggie Logger to a PC for data analy- workload on the CPU and the quick roll over and a scratch from a sis. I use custom C code and amount of data that would be paw. This lead to several hardware Microsoft Excel to process and visu- acquired seemed reasonable at this revisions resulting in a device that alize the motion data. sample rate. The sampling rate was looked less like a science experiment The seizure detector (the K-911) kept when I discovered that the and more like a commercial device. contains a sensor platform connected fastest musical tempo on my wife’s I collected several hours of data to to a real-time processing algorithm. electronic keyboard was “Presto,” use as a reference pattern for a normal A phone dialer and a user interface 200 beats per minute, or about three dog and to ensure that all of the bugs provide connections to the outside beats per second. I figured that a dog were worked out of the system. I col- world. Like the Doggie Logger, the shouldn’t move much faster than my lected data on everything from a sleep- sensor platform is an accelerometer. wife’s fingers! Later analysis of actual ing dog, to a walking dog, to a dog The acceleration data is processed seizures showed that the interesting playing fetch! All that remained was through a real-time frequency-detec- data frequencies are below 30 Hz. to collect the elusive seizure pattern. tion algorithm. When the seizure fre- The data logger is used to collect Now that the logger was ready, I quencies are detected in the motion 16 bits of data from each of the two patiently waited for the next seizure data, a digital output is triggered to motion axes at a rate of 100 Hz to so I could record the data. Ease of place a phone call. Details of when enable signal processing of 50-Hz operation was essential so that dog sit- the seizure occurred and how long it data. The raw acceleration values are ters, friends, and family could all be lasted are stored in memory. An recorded for a PC to process. In practice, ready to capture the important data

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 43 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 44

status data.

(a) (b) (c) (d) HARDWARE DIAGNOSTICS Frequency bin Count Over Inside gate My most common hardware prob- over (e) Magnitude Magnitude Count lems during development were caused 8 Hz threshold threshold Seizure by a missing accelerometer evaluation 18 Hz Count active board or by a missing DataFlash chip. 28 Hz Under under Outside gate 38 Hz The current diagnostic software per- 48 Hz forms tests on the two items and then displays the results via LEDs and the user serial port. A larger framework is Figure 4—A set of five discrete frequency components are examined to identify the signature of a seizure. A left behind to test battery voltage and seizure is indicated when each of the discrete frequencies is above or below its threshold for a specified number of other future failure points. samples. When all of the conditions are met, the dog is having a seizure. The Analog Devices accelerometers contain a test feature that enables a when the infrequent seizures and begged for treats. Motion data in forced change in the reading. With occurred. The operation of the Doggie the 8- to 18-Hz region, as well as this feature, the diagnostics software Logger consists of turning on the motion at 28 Hz and higher frequen- will take a series of readings with and power and hitting the record switch. cies indicates that the dog is engaged without the forced deflection. The Motion data is retrieved from the Dog- in normal activities and not having a readings are compared to ensure that gie Logger by connecting it to a serial seizure. an accelerometer is connected and port on a PC and performing text cap- Data analysis revealed that a responding. If no accelerometer is con- ture with HyperTerminal. The ASCII unique motion signature indicates nected, then the readings won’t text-based acceleration/motion data was the presence of a seizure! It is now change. This lack of change in read- somewhat slow to transfer, but it was time to modify the logger to detect ings is used to signal a missing or easily read by Excel and custom C code. seizures in real time. The K-911 will failed accelerometer. monitor the dog’s motion. A seizure- The Doggie Logger’s data is stored ANALYSIS detection algorithm must continu- in a separate memory chip. The origi- The Doggie Logger data was run ously search the real-time motion nal logger used removable SD flash through an FFT to produce a display of data looking for the pattern of a memory chips. At times, the chip was time versus frequency versus intensity. seizure. If a seizure is detected, then missing or loose. The diagnostic soft- From these plots, I could visualize the the time and length of the seizure ware was used to signal memory prob- data to look for clues to detecting a should be determined and stored in lems. The current hardware uses a sol- seizure. A set of discrete frequencies was memory. Optionally, I would like to dered-in memory chip relegating the selected and analyzed. The frequencies of be notified that a seizure is occur- diagnostic to a hardware construction interest for seizures and normal activi- ring. Ideally, the final device should and debugging aid. ty are shown in Figures 2a and 2b. The retain the logging facilities because I seizure patterns were compared to the currently have only data from the USER INTERFACE patterns obtained from normal dog seizures of one dog. A Start/Stop switch and user com- activities. mands are monitored in the back- I discovered that during a seizure, SOFTWARE & SLOW LOOP ground. The features were not consid- Princess’s motion showed high-inten- The Doggie 911 software combines ered time-critical because a few sec- sity frequency components less than the features of the Doggie Logger data onds of data logged or lost at the end 25 Hz and little other motion. In con- logging system and the K-911 seizure of an experiment were not important. trast, a sleeping dog showed relatively no detector into an integrated software Similarly, the user keyboard requests motion and a healthy dog engaged in package. The majority of the software must respond only “soon enough” so normal activity showed motion across operates from two control loops (see that you don’t think the system has the entire frequency spectrum analyzed. Figure 3). A slow main loop interacts locked up. Operational status of the Based on the data analysis, I sum- with the user interface and controls system is conveyed by four PCB- marized the discrimination of a switches, while a faster interrupt-driv- mounted LEDs. An LED mounted canine seizure as follows: Motion in en loop logs data and processes the among the circuitry indicates that the only the 8- to 18-Hz frequency region motion data. RS-232 driver is active. A yellow LED indicates the presence of a seizure. The slow loop initializes the hard- flashes when the system is recording. Figure 2a shows the recorded motion ware and software before beginning a The yellow LED stops flashing and data of my dog as she goes from rest- continuous multi-second loop. The stays on to indicate that the flash ing at record 1 to a seizure at record background loop performs a series of memory is full. A green LED flashes in 51. Figure 2b shows the recorded hardware diagnostics, checks the status time with the fast loop to indicate that motion data as my dog fetched toys of the Start/Stop switch, and displays the power is on. A red LED indicates

44 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 45

that a seizure record has been stored determine the interval between spond with the 50-Hz bandwidth of to the internal memory. seizures whether it is minutes, hours, the accelerometer’s hardware filters. A The primary use for the serial inter- or days. To track the interval, the hardware multiplexer (and associated face is to upload logger data. Logger data system maintains a 32-bit timer that software) is used to attach each is displayed as ASCII text to simplify begins counting at system startup. accelerometer to the input-capture the capture and processing of the data. For convenience, the timer can be set hardware. The serial interface supports a host of to reflect the time of day, although Motion data is stored in an external additional commands to test and debug all that is really required is the inter- flash memory chip. The secondary the system. Refer to the module seri- val (in days) between seizures. storage software was developed from al.c on the Circuit Cellar FTP site to Seizures less than one day apart indi- datasheets and application notes that find additional commands. cate a need for immediate medical describe the use of Atmel’s AT45 treatment. series DataFlash memory. FAST LOOP The “fast loop” is a 10-ms interrupt ACCELERATION CAPTURE FREQUENCY DETECTION where the Doggie 911’s real work is Canine motion is measured with a During data analysis, I proved to done. CPU hardware Timer2 provides an dual-axis PWM output accelerometer myself that the seizures that Princess interrupt-driven timebase. The 10-ms (an Analog Devices ADXL202).[1] The experienced could be detected by the timer is divided down to provide the PWM signal ranges from 0 to 1 ms to evaluation of a set of discrete frequen- seconds-based times used in the slow indicate an acceleration of –2 to 2 G. cies. I referred to Circuit Cellar to loop. The fast loop updates the slower CPU hardware Timer1 is used in an select a suitable frequency detection timers and collects the 100-Hz accel- input capture mode to provide a 16-bit algorithm. The articles “DTMF eration data and logs it to flash memo- value that represents the acceleration. Decoder” by Chris Coulston, Brian ry (see Figure 3). Acceleration data is Conversion to the actual acceleration Nypaver, and Jeffrey Rimko (Circuit processed to search for the presence of value (in G) is not required. All that Cellar 187, 2006) and “Telephone a seizure. If a seizure pattern is detect- the system needs is the difference Message Watchdog,” by Jingxi Zhang, ed, seizure data is recorded to on-chip between readings to indicate the Yang Zhang, and Huifang Ni (Circuit memory. motion. The accelerometer readings Cellar 171, 2004) provided a good The Doggie 911 is required to are recorded every 10 ms to corre- starting point based on the Goertzel

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 45 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 46

Figure 5—The heart of the system is an Atmel ATmega32L processor with an external DataFlash memory chip to store hours of motion data. A set of LEDs and switches provides a simple user interface.

algorithm used to detect telephone to determine the presence of a the seizure records will be automati- dialing tones. seizure or normal puppy dog activity. cally displayed. Hopefully, that With ideas from the previous arti- The seizure is detected, as shown in response is “No Seizures Detected!” cles, I created my own version of the Figure 4. The current magnitudes at However, if there has been seizure Goertzel algorithm. Fixed-point math each frequency are compared against activity, you will be presented with a was used to enable each of the indi- their magnitude thresholds (a). A list of when the seizures occurred. A vidual frequencies of interest to be counter value indicates how long the veterinarian can use the number of identified in 123 µs. Goertzel code magnitude of the specific frequency seizures, the duration of the seizures, was further modified to remove mag- has been above or below its calibrat- and the time between seizures to nitude-squared and square-root calcu- ed magnitude (b). The current count- determine medical treatment lations. Because my goal was to com- er value is compared against the cali- options. pare the detected magnitude with a brated counter threshold (c). The pre-programmed threshold value, the counter threshold indicates if this HARDWARE DEVELOPMENT deleted steps could be compensated condition has been passed (d). If all In the System Overview section of for by modifying the threshold values the frequencies’ calibrated thresholds this article, I provided an outline of during calibration. Up to eight indi- have been passed, then there is an the required hardware. A CPU is sur- vidually calibrated frequencies are active seizure (e). rounded by motion sensors, memory, a processed on both the X and Y axes in A “seizure record” is my name for wireless user interface, and a remote 2 ms. This timing falls well within the information that specifies the dialer link (see Photo 1b). the 10 ms required to maintain real- time and duration of a K-9 seizure The entire hardware configuration time processing of the incoming accel- detected by the Doggie 911. A soft- is a straightforward construction of eration data. ware-based 32-bit timer marks the functional blocks around the CPU. start and end times of the seizure (or Because the device is intended to be SEIZURE EVALUATION & RECORDS seizures). The start time and the dura- mounted on a pet, size and durability Magnitudes of up to eight selec- tion are stored in the CPU’s on-chip were important considerations! I table frequencies are computed by EEPROM at the end of the seizure. chose to have a PCB manufactured to the frequency detection algorithm. Once a seizure record is stored, an LED hold the various components. Hard- My earlier data analysis showed that is illuminated to indicate that the wired flash was selected for data stor- the magnitude of motion at frequen- Doggie 911 contains at least one age, and low-power components were cies of 8, 18, 28, 38, and 48 Hz were “seizure record.” chosen for longer battery life. The useful in detecting seizures in my When you subsequently connect to entire device was mounted safely dog. The five frequencies are analyzed the Doggie 911, the contents of all of inside a plastic container that attaches

46 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 47.qxp 2/1/2008 11:51 AM Page 1 48.qxp 4/9/2008 9:31 AM Page 1

Exclusively at Jameco… The Lowest Prices… Guaranteed!

Save 3% to 5% Save 15%-25% Save 30% or more! Looking to save on thousands of Save more when a specific Looking for killer deals? Jameco Name Brand components? Jameco manufacturer is not required. Major buyers often find Factory Overruns offers their popular products for 3% Brand semi’s are sourced from 5-6 from some of the industry’s biggest to 5% below market price, and we major manufacturers, plus we offer names. That means savings of 30% guarantee it! Jameco brand and generic passives and more to you! for even greater savings.

3 Levels of Choice 3 Levels of Savings

Other Jameco Advantages:  We offer over 300 Major Manufacturers  99% of catalog products ship the same day.  Lowest prices guaranteed, or we pay 10%. Order 24 hours a day, 7 days a week www.Jameco.com Or call800-831-4242 anytime

SEMICONDUCTORS • PASSIVES • INTERCONNECTS • ELECTROMECHANICAL • POWER 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 49

to the dog’s collar. If Princess gets records. ATmega32L CPU. her way, the next version will be Motion detection is accomplished Looking to the future, I thought even smaller and more compact. using an Analog Devices ADXL202EB wireless data access would be more ±2-G PWM-based accelerometer eval- convenient. My PDA contained an CPU & MOTION SENSORS uation board. Following the applica- IrDA port, so I selected infrared as my The Atmel ATmega32L was an tion notes from Analog Devices, I wireless connection medium. IrDA is excellent choice for this project. The supplied 0.1-µF filter capacitors for a supported by using the Microchip hardware design was simplified 50-Hz bandwidth and a 124-kΩ resis- Technology MCP2150 self-contained because the CPU includes a hard- tor for a sampling period of 1 ms. A IrDA adapter, wired according to ware UART, a hardware SPI, and an counter/timer inside the CPU meas- Microchip’s application notes (see internal oscillator (see Figure 5). ures the accelerometer pulse to deter- Figure 6). The IrDA chip is connected Software development was made eas- mine the acceleration at a given to the CPU’s UART channel. Various ier by Atmel’s in-circuit programma- instant in time. Changes in accelera- iterations of the project supported bility and on-chip debug support. tion from one sample to the next either RS-232 or IrDA. The 16-bit timer capture input pro- indicate the motion of the sensor and vides the required interface to the consequently the motion of the REMOTE DIALER PWM accelerometer. The L suffix attached dog. One of my goals was to have the CPU reduces power consumption to Doggie 911 notify me when a seizure allow a longer battery life. The avail- USER INTERFACE occurs. From the CPU side, it was able 32 KB of ROM and 2 KB of RAM The original Doggie Logger was cre- only necessary to provide a digital out- fits the software with a bit of room ated to collect large amounts of put port that toggles when a seizure left over for future development. An motion data. A simple RS-232 inter- occurs. The digital output was con- added bonus was the internal EEP- face was used to transfer the data to a nected to an optically isolated output ROM! With this non-volatile memo- PC for analysis. The Maxim Integrated that can be used as a switch closure to ry available, I could potentially strip Products MAX563 single-chip, 3-V, control an arbitrary external device. I out the logger functions for a simpli- RS-232 converter was connected to scrounged up an old burglar alarm fied seizure detector only model and the CPU UART to provide access to dialing system that was designed to still have storage for the seizure the user interface running in the place a phone call when the switch on

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 49 63.qxp 12/4/2007 10:30 AM Page 1

PC Oscilloscopes & Analyzers

DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

4 Channel BitScope 2 Channel BitScope Pocket Analyzer

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

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

Networking Flexible network connectivity supporting  multi-scope operation, remote monitoring and data acquisition. Data Export Export data with DSO using portable CSV files or www.bitscope.com  use libraries to build custom BitScope solutions. 2805019_Lubbers.qxp 4/9/2008 9:19 AM Page 51

computer as a high school science fair project. Since high school, he has achieved an Extra Class Amateur Radio License and a B.S. in Computer Science. Steve currently builds ama- teur radio embedded systems for fun and embedded automotive electronics for profit.

Princess Leia is a 10-year-old, mixed- breed canine (a combination of beagle and Australian cattle dog). She inherit- ed a beagle’s genetic defect that leads to idiopathic epilepsy. Princess has lived with seizures for eight years.

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

REFERENCE [1] Analog Devices, Inc., “Preliminary Technical Data ADXL103/203: Low Cost ±1.5g Single/Dual Axis Accelerometer,” 2003. Figure 6—The motion data stored in the system is accessible through an IrDA wireless link. The wireless link is based on Microchip’s MCP2150. The dog’s motion is captured by an Analog Devices accelerometer. RESOURCES a transmitter is pressed. The optoiso- prescribed an initial dosage of medica- Canine Epilepsy Resource Center, lator triggers the transmitter switch. tion. In the coming months, the Dog- www.canine-epilepsy.com. There are various commercial systems gie 911 will monitor Princess to aid C. Coulston, B. Nypaver, and J. that can place a series of phone calls the vet in determining the correct Rimko, “DTMF Decoder,” Circuit with recorded messages when they are dosage. Cellar 187, 2006. activated. In many cases, pet owners have no real idea of how often their pet has S. Schlanger, “AN758: Using the FLASH MEMORY seizures. The lack of accurate data MCP2150 to Add IrDA Standard Con- The CPU SPI bus was used to inter- forces veterinarians to err on the side nectivity,” Microchip Technology, face to external flash memory. From a of caution and prescribe medications Inc., DS00758A, 2001. hardware perspective, the approach sooner rather than later to avert a con- J. Zhang, Y. Zhang, and H. Ni, “Tele- enables a huge selection of memory tinuous (and possibly fatal) cluster of phone Message Watchdog,” Circuit components to be used for the actual seizures. The detailed data collected Cellar 171, 2004. storage. by my invention will be instrumental In various prototype circuits, I in determining the correct time to used an Atmel AT45DB161 and an begin medicating pets. I SOURCES AT45DB321 DataFlash. The 16- and ADXL202EB Evaluation board 32-MB chips are pin compatible and will Editor’s note: This project earned Hon- Analog Devices, Inc. hold between one and three hours of orable Mention in the Atmel AVR www.analog.com continuous data, depending on the chip. Design Contest 2006. To learn about the contest and the other prize-win- ATmega32L CPU, AT45DB161 SUCCESS! ning projects, visit www.circuitcellar. DataFlash, and AT45DB321 DataFlash The Doggie 911 has shown a trend com/avr2006/. Atmel Corp. of seizures with shortening duration www.atmel.com but increasing frequency. Particularly Steve Lubbers ([email protected]) start- disturbing was a cluster of multiple ed his budding electronics career in MCP2150 Controller seizures within a 24-hour period. the days of “Ciarcia’s Circuit Cellar” Microchip Technology, Inc. Based on this data, my veterinarian when he designed an 8080-based www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 51 2804018_lynch.qxp 4/9/2008 9:25 AM Page 52

FEATURE ARTICLE by David Lynch Embedded Linux Development (Part 2) Create An Embedded Development Environment

David finishes describing his coLinux cross-development platform that runs on Windows.You can create an embedded development environment with him on coLinux or other versions of Linux.

In the first part of this series, I compilers capable of digesting the kernel coding style guidelines so focused on creating a virtual Linux Linux kernel, virtually all Linux ker- closely resemble my personal style environment on a Windows system nels are built using the GNU tools that I could have written the standard. using coLinux. coLinx is real Linux (e.g., GNU Make and the GNU compil- But I have had to adapt to numerous running under Windows as a process. er collection (GCC)). Autoconf/AutoLib and often radically different program- It uses Linux device drivers communi- show up on complex projects outside of ming styles for client projects. cating with Windows services to map kernel development. GIT, CVS, and Source/version control managers access to Windows resources (e.g., subversion are the primary source/ver- (SCMs) are incredibly valuable tools. disk, network, and memory) to Linux. sion control managers. While advanced Any developer who does not use an In this article, I’ll concentrate on the skills with any or all of these might be SCM should drop everything and learn process of creating an embedded devel- useful, only a basic understanding of one—any one, immediately. SCMs are opment environment. Although I’ll some of them is critical to most useful outside software development. I describe how to build that environ- embedded development work. am trying to encourage my wife (a ment under coLinux and I’ll assume My top 10 Linux commands for lawyer) to make use of Tortoise SVN the Debian coLinux install from the embedded developers are: cd, mv (the Windows Explorer integration of previous article, little of this process (rename), cp (copy), ls (dir), rm (delete), subversion) for all of her writing. I is specific to coLinux. find, grep, vi, make, and man. Embed- have never regretted putting anything ded Linux kernel development into an SCM. I have frequently found GUI TOOLS requires an understanding of program- myself wishing I had. Linux developers, particularly ming for hardware, basic competence GIT is the SCM used for Linux ker- embedded Linux and kernel develop- in C, and possibly the assembler for nel development. It has an approach ers, are still primarily, if not exclu- the target embedded system, the text and style uniquely suited to the sively, a command-line-driven edit, editor of your choice, the presence of a requirements and preferences of Linux build, and debug cohort. GUI develop- GNU GCC cross-compiler for the tar- kernel developers. If you are intent on ment tools such as Eclipse are a major get, and a very basic understanding of participating in Linux kernel develop- force dominating Java development Make. More complex tasks, such as ment and contributing to the public and making steady inroads into most board bring up, require slightly more kernel source repository, a minimal other areas of application development than a cursory understanding of the con- understanding of GIT would be close (including Windows) but still have figuration/build environment unique to to indispensable (http://linux.yyz.us/ only a toehold in kernel and embed- the Linux kernel. Embedded, Linux, and git-howto.html). ded development. There are few GUI open-source software development is as CVS and subversion are the domi- tools for embedded Linux or kernel chaotic a reflection of different program- nant choices elsewhere. Subversion is development, and few kernel develop- ming styles as might be found in any slowly supplanting CVS because it is ers could name (or care to) any GUI other area of software development. The primarily a kinder, gentler, and more tools for Linux kernel development. It Linux kernel has a set of programming powerful version of CVS, but numer- is also worth noting that even under style guidelines that are mostly adhered ous other choices exist. Competence Windows most GUI development to. But programming style is irrelevant with an SCM, while valuable, is not tools are layers on top of command- unless you are hoping to include your essential for embedded Linux develop- line tools. Under Linux, this is even board support/drivers in the distribution ment. The same is true of the plethora more true. While there are a few other kernel. I am fortunate that the Linux of open-source Linux/Unix tools. I use

52 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804018_lynch.qxp 4/9/2008 9:25 AM Page 53

which can be rough equivalent of the Windows \Docu- retrieved using ments and Settings\username directories. apt-get or dse- Under Linux, home directories are lect. I recom- typically in /home/user, but the home mend dselect directory for an account can be set by because it is a editing /etc/password. friendlier text- You can add lines to /etc/passwd based GUI wrap- such as: per around apt, but the apt com- src:x:32767:32767:/usr/src:/bin/false mands are scriptable and This creates a user src that cannot more concise log on with a home directory of and suitable for /usr/src. Now ~src can be substituted print. wget is a almost anywhere for /usr/src. It is fre- command-line quently useful to create similar short- web file retrieval cuts for frequently used long and diffi- Photo 1—This is a Linux terminal session with an example of the adduser command. tool. lynx is a cult paths. text HTML Alternatively, you can create sym- browser. bolic links in your home directory to GIT for Linux kernel work and sub- The remainder are standard Linux common targets: version for most everything else. Both x86 development tools required by have dozens of commands and Crosstool to build a cross-platform cd ~ options. Daily work with either version of GNU tools: ln -s /usr/src src requires the use of at most a handful of commands. I rarely need to create a apt-get install wget Now ~/src can be used anywhere new repository, a project within a apt-get install lynx instead of /usr/src. repository, or a new branch or tag apt-get install patch within. Every day I need to add new apt-get install bison LINKS files, remove existing files, and com- apt-get install flex Hard links, symbolic links, aliases, mit my recent work. On rare, but crit- apt-get install gcc and home directory shortcuts are ical, occasions I need to revert to an apt-get install libc-dev used liberally in Linux. Once you get older version. Specific to participating apt-get update the hang of them, you will wish you in Linux kernel and other open-source apt-get upgrade had them in Windows. Windows has projects, I need to produce diffs or mkdir /opt/crosstool both hard links and a limited imple- patches reflecting changes since a mentation of symbolic links but they branch or tag. When I need to per- COMMANDS are rarely used because applications form infrequent tasks, I look them Linux best practices advocate per- and a few Windows tools are con- up—Google is your friend. The com- forming tasks in a user account with fused by them and behave unpre- mands for the daily tasks in most the minimum privileges needed for dictably. Windows .lnk files have a SCMs tend to be simple and friendly. the task. Crosstool enforces this prac- vague resemblance to symbolic links. Unless your target CPU is an x86, it is tice by failing to build under as the I use them for several similar purpos- highly likely that you will need cross- root user. To create a new user exe- es. They do not have the same poten- platform development tools. Many soft- cute, the adduser command will tial for bad, unintended consequences ware consultants are in the business of prompt for required information (see under Windows, but they also have providing pre-compiled GCC cross tools Photo 1). The only critical elements less power. as well as support for various targets are a user ID and a password. Linux has tools supporting most and platforms. Still, the most frequent The Linux su command switches compressed archives. The ubiquitous approach is to build your own. users. “su test” will prompt for the Linux/Unix archive is the tar file. Tar Crosstool is a commonly used set of password for the user test and logon is a Unix archive file that predates zip scripts for building cross-platform ver- as test. “exit” will return to the pre- files. A .gz (or tgz) extension indicates sions of the GNU compiler collection vious logon. Change to the new that the archive was compressed using tools. Crosstool is available at user’s home directory. “~” is a very gzip. A .bz2 extension indicates bzip2 http://kegel.com/crosstool. It also makes handy shortcut that always refers to compression. sense to create the /opt/crosstool direc- the current users home directory, Change to the test user’s home tory that Crosstool will install into. while “~user” is a shortcut referring directory, download, and unarchive Regardless, I need a small collection of to the “user” home directory. Crosstool. Then, change to the Linux software development tools, Unix/Linux home directories are the Crosstool directory being extremely

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 53 2804018_lynch.qxp 4/9/2008 9:25 AM Page 54

careful about exact syntax: frequently use an open coLinux ssh GNU Makefile to build the UartLite (putty) session to use Linux tools—such HelloWorld example using Crosstools. cd ~ as grep, sed, find, sort, and uniq—as Eliminating the -DSTANDALONE wget http://kegel.com/crosstool/cross well as the excellent scripting afforded from the Makefile would create an ordi- tool-0.43.tar.gz by Bash to perform and automate tasks nary Linux ppc405 executable. Comment- tar -xzvf crosstool-0.43.tar.gz that are more difficult under Windows. ing out the definition of CROSS_COM- cd crosstool-0.43 A note of caution: under Windows, PILE would result in an x86 version. lines in text files are typically delimited Many Makefiles are simpler than this. The Crosstool readme refers to docu- with carriage return/line feeds. In More information on GNU Make can be mentation that can be viewed with: Linux, the newline (line feed) is used. found at www.gnu.org/software/make/. A large number of Linux tools and a Like almost everything else I’ve lynx doc/crostool-howto.html smaller subset of Windows tools are described, a limited understanding of either aware of this and make appropri- a few simple Make commands is suf- CROSS-PLATFORM TOOLS ate adjustments or are oblivious to this ficient for most ordinary work. I am building PowerPC 405 cross-plat- in a way that enables them to work Linux kernel source can be down- form tools, and there is already a suitable regardless. But there are cases in both loaded from the Debian archives with: Crosstool script. There is a matrix on the Windows and Linux where a text file in Crosstool site that cross-references ver- the wrong format will cause unusual apt-get install linux-source-2.6.18 sions of the GNU tools against platforms errors that are not readily traceable to a and indicates which combinations can be text file format. In general (with excep- Alternatively, git can be installed: built successfully, but not all failures are tions), programming languages and fatal. Cross-compiling a Linux kernel is compilers—particularly those such as apt-get install git-core not necessary if you are just developing GCC that are cross-platform—are obliv- embedded Linux applications. If you are ious to text file format, while OS-spe- And the git repository of Linus Tor- porting Linux, or if you are developing cific tools, such as Notepad or scripting vald’s current development kernel standalone applications for a target, you languages, tend to get confused. The source can be pulled with: may not care about glibc. There are rare vim text editor—available under Linux, instances where it may be critical to apt-get vim, as well as for Windows git clone git::/git.kernel.org/pub use a specific version of the GNU tools, (www.vim.org)—reads files in either /scm/linux/kernel/git/torvalds/ glibc, and the Linux kernel, but in most format normally and preserves the origi- linux-2.6.git linux-2.6 instances, the most recent working nal format, but it can optionally convert combination for a target is acceptable. to either (see Photo 2). There are also CROSS-COMPILE Building the most recent ppc405 cross- numerous small utilities for both Win- Cross-compiling a Linux kernel only platform tools can be done with: dows and Linux. Listing 1 is an example differs in that the target ARCH and

./demo-powerpc-405.sh

This will take a large amount of disk space and a long, long time (hours) even on a fast processor. Once Crosstool has finished building, every- thing is in place to begin embedded cross-platform development. The logical first program is Hel- loWorld. Photo 2 is a minimal standalone Hello World for the Pico Computing E1x cards using the Xilinx UartLite UART. If coLinux is installed with cofs1 assigned to C:\ and mounted as /win- dows under coLinux, you can easily copy files between Windows and Linux. If you have the coLinux network set up you can install samba under coLinux and map the coLinux disk to a Windows drive let- ter. Either way, where possible, you can use your favorite Windows tools to a large extent while doing embedded Linux software development. Conversely, I Photo 2—Editing UartLite Hello World with Windows/Vim.

54 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 55.qxp 4/9/2008 9:30 AM Page 1 2804018_lynch.qxp 4/9/2008 9:25 AM Page 56

Listing 1—This is a GNU Makefile for building the UartLite HelloWorld example using a ppc405 gcc cross compiler.

CROSS_COMPILE=/opt/crosstool/gcc-3.4.1-glibc-2.3.3/powerpc-405-linux-gnu/bin/powerpc-405-linux-gnu-CC=${CROSS_COMPILE}gcc LD=${CROSS_COMPILE}ld CFLAGS= -O2 -g -c -DPIC -Wno-multichar -Wreturn-type -fmessage-length=150 -DSTANDALONE LDFLAGS= --omagic

HelloWorld.elf : HelloWorld.o $(LD) $(LDFLAGS) -o HelloWorld.elf HelloWorld.o

HelloWorld.o : HelloWorld.c $(CC) $(CFLAGS) HelloWorld.c

all : ${MAKE} HelloWorld.elf

clean : -rm HelloWorld.o HelloWorld.elf *.o

CROSS_COMPILE path need to be speci- would be to copy the board support can be an effective shortcut. Linux fied much like the HelloWorld Makefile. from the most similar existing target. kernel software and drivers are a mov- I use the shell script in Listing 2 to There are many for each architecture ing target: even LDD3 contains wrap the kernel Make process so I do to choose from. numerous references that are now not have to repeatedly type the long Adding drivers to an existing target obsolete. In addition to using drivers paths needed to cross-compile a kernel. is a significantly simpler project. The for similar hardware as a template, it Note that typing ./cross menuconfig third edition of Linux Device Drivers often makes sense to take a careful will set up Make for cross-compiling by Jonathan Corbet, Alessandro Rubi- look at the code for popular drivers and invoke the standard linux kernel ni, and Greg Kroah-Hartman is the because bug fixes and changes usually configuration tool. “bible” for developing Linux drivers. show up there first. Recent Linux ker- A starting point for creating Linux Again, using the most similar existing nels provide UIO—user space I/O kernel board support for a new target driver for your hardware as a template template driver. This requires adding the PCI card ID to the template driv- er, and then allows a user space pro- gram to access the device directly. This is a fast way to prototype and debug a Linux driver with very mini- mal kernel programming. Building coLinux and the cross-plat- form development environment has involved complex commands and options that are not the norm for embedded Linux development. But the end results are critical to the objective of supporting embedded Linux develop- ment. The coLinux project does not come with prebuilt coLinux images for embedded development but it pro- vides the opportunity to do so.

UPGRADES At Pico Computing, I created a cus- tom coLinux installer that automates the creation of a minimal cross-platform development environment similar to the one described in this article with the ppc405 and MicroBlaze Crosstool, Linux source including Pico E1X Platform sup- port, as well as other sources and tools needed to start right into embedded Linux development on the Pico E1X Platforms. While researching this article,

56 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 57.qxp 4/9/2008 9:30 AM Page 1 58.qxp 4/9/2008 9:30 AM Page 1 Sensors08 CircuitCellarAd.qxd 3/13/08 3:05 PM Page 1

June 9 - 11, 2008 sensors expo Donald E. Stephens Convention Center Rosemont, Illinois & conference www.sensorsexpo.com

Advances in Measurement, Monitoring, Detection and Control

New Approaches • New Technologies • New Applications • New Ideas

Education: OPENING KEYNOTE Featuring Nine Research-Based Technical Tracks: • Novel Approaches to Measurement & Detection • Wireless Sensing • Systems & Embedded Intelligence James • Power Management, Battery Technology & Low-Power Sensing • Sensor Standards McLurkin • Emerging Technologies & Applications MIT Roboticist, Inventor, Researcher, Teacher Including Three ALL-NEW Tracks Examining: • Transportation Infrastructure & Structural Health Monitoring “Engineering • Machine Health & Predictive Maintenance • “Green” Sensing Technologies & Applications Creativity”: Exercises for And Three Optional Pre-Conference Symposia: the Right Brain • Digital Data Acquisition & Analysis Symposium • Nanotechnology & MEMS/MST/Micromachines Symposium • Energy Harvesting for Powering Sensor Applications Symposium

Expo Hall – Over 200 key suppliers showcasing their products and solutions at Sensors Expo.

Register Today & Take Advantage of the Early Bird Rates or Sign-up Now for Your FREE Expo Hall Pass! Register at www.sensorsexpo.com or call 877-232-0132. Please use your source code: 303M

Produced By: Official Publication: Gold Sponsors: Silver Sponsor: Media Sponsor: 2804018_lynch.qxp 4/9/2008 9:25 AM Page 59

Listing 2—cross is a shell script to cross-compile a Linux kernel for the ppc405 and copy the kernel executable to Windows.

#!/bin/sh

#delete pre-existing compiled linux kernel if present if [ -f arch/ppc/boot/images/zImage.elf ]; then rm arch/ppc/boot/images/zImage.elf fi

#specify the default linux configuration file to be used if one does not already exist DEFCONFIG=pico_e1x_defconfig if [ -f .config ]; then DEFCONFIG= fi #invoke the standard Linux Kernel Makefile with arguments for cross compiling make $1 ARCH=ppc ${DEFCONFIG} CROSS_COMPILE=/opt/crosstool/gcc-3.4.1-glibc-2.3.3/powerpc-405-linux-gnu/bin/powerpc-405-linux-gnu- #if successful copy the newly build kernel image to the host windows system if [ -f arch/ppc/boot/images/zImage.elf ]; then cp arch/ppc/boot/images/zImage.elf /windows/Pico fi

I discovered that this approach is not like to use coLinux primarily as a black busy attempting to automate his home unique and several other embedded box build service for Windows develop- and coerce his two children away from platforms provide coLinux-based ment tools—using MSDEV to inject screens and into the outdoors to help development environments. build commands and retrieve results. build their home. The coLinux development platform I am working to integrate some of I’ve described provides a workable base the features of coLinux with hosted RESOURCES that can be expanded in many direc- embedded development on my target coLinux, www.colinux.org. tions. All embedded development tasks platforms, so my Linux target has driv- can be accomplished on the minimal vir- ers like conet, cofs, and cobd, which J. Corbet, A. Rubini, and G. Kroah-Hart- tual Linux. After building the cross-plat- enable it to access resources on the man, Linux Device Drivers, O’Reilly form tools, the Debian Linux running Windows host during development. I Media, Inc., Sebastopol, CA, 2005. under coLinux could be substantially Jeff Garzik’s Linux Pages, “Kernel Hack- pared down and fit into a single virtual David Lynch ([email protected]) is a ers’ Guide to git,” http://linux.yyz.us/git disk image. Alternately, a Windows partner at Pico Computing (www.pico -howto.html. XServer, such as XMing, could be computing.com), the owner of DLA Sys- installed and Linux Xwindows clients tems (www.dlasys.net) software con- GNU Make, www.gnu.org/software/ could run under coLinux to provide a sulting, and an architect, with projects make/. complete Linux desktop system running ranging from automated warehouses to Linux Kernel Archives, www.kernel.org. concurrently on Windows (see Photo 3). embedded OS ports. When he is not At least one developer at Pico would working (playing) with computers, he is Linux Kernel Installation, http://97k. eu/howto/kernel.htm.

Linux Kernel Mailing List FAQ, www. tux.org/lkml/. D. Lynch, “How to Port Linux When the Hardware Turns Soft,” Linux Journal, 2007, www.linuxjournal.com/article/9362. PuTTY: A Free Telnet/SSH Client, www.chiark.greenend.org.uk/~sgtatham /putty/. Vim the Editor, www.vim.org.

Xming Info, www.straightrunning.com/ XmingNotes/.

SOURCE Crosstool Photo 3—Here you see Windows, running the Xming Xserver, connected to coLinux on the same machine. coLinux is running the Gnome desktop with a number of GUI application windows open: Solitare, Firefox, thunderbird, calculator, Dan Kegel and an xterm. http://kegel.com/crosstool

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 59 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 60

FEATURE ARTICLE by Wolfgang Matthes Advanced Technology Attachment I/O Use ATA Interfaces For General-Purpose I/O Applications

Using modern PC interfaces for connecting application-specific hardware can create a wide range of problems for embedded designers (e.g., slow communication and long latencies). In this article, Wolfgang describes a viable alternative: an ATA interface. Employing ATA as the low-latency embedded interface allows you to apply miniaturized motherboards instead of typical industrial platforms, which are considerably more expensive.

When PC systems are used in interfaces for connecting application- interface standards will lead to spend- embedded systems, it is necessary to specific hardware poses some prob- ing more money. Various fees have to select appropriate interfaces for lems. Latencies can be long. This be paid for licenses, for membership in attaching application-specific hard- relates especially to USB and Ethernet. the standardization committee, for ware. The basic requirements are Typical latencies are in the order of 10 acquiring a vendor ID, for getting the obvious. Hardware as well as software to 20 ms regardless of the data rate. design certified (to ensure conformity), should be easy to develop and inex- Readily available bread-and-butter and more. pensive. Low latencies are more solutions (above all, the serial commu- important than impressive data rates. nication over USB) are comparatively EXPLOITING THE ATA INTERFACE The legacy interfaces of the past slow. Developing full-blown high-per- One legacy interface boasting low were comparatively well suited to formance solutions (based on USB, latencies and high data rates can be these requirements. To build an Firewire, PCI Express, and the like) found on even the most contemporary adapter for the ISA bus or the parallel requires a lot of effort. More often motherboards—the advanced technology port requires only a few LS TTL pack- than not, applying contemporary attachment (ATA) interface. ATA is ages. Attachment via RS-232 still a mainstream drive interface, requires only a small microcon- so long-term availability could be troller and a receiver/transmitter a) Write access taken for granted. The most com- combo IC (like the good old pelling advantage is simplicity. The 1 MAX232). Register address Valid legacy ATA interface (Parallel ATA) is

But many contemporary PCs DIOW- essentially a modified ISA bus. have no legacy interface at all. PC Hence, it should be easy to develop hardware in “industrial” form fac- Data bus2 Write data I/O adapter hardware. The hard-

tors (like PC/104 or PICMG) sup- b) Read access ware/software API is straightfor- ports those interfaces, but it is ward—a small register file accessible expensive. Register address1 Valid by I/O instructions. ATA registers Modern PC interfaces are can be accessed directly (under DOS DIOR- designed mainly with multimedia or Linux) or via comparatively simple and gaming applications and with Data bus2 Read data port drivers. Serial ATA (SATA) is

ease of use in mind (e.g., extreme 1: CS0-, CS1-, DA2...0 principally nothing more than two data rates, support of continuous 2: Data bits DD7...0 (8-bit Access) wire pairs to push around register datastreams, and dynamic Figure 1—The programmed I/O (PIO) operation of the parallel contents between the host adapter attach/detach). Exploiting these ATA interface is based on simple access cycles. and the attached device. Because

60 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 61

ATA is essential for booting the sys- tem, appropriate support is deeply embedded within the BIOS and the operating systems. In this article, I will concentrate on programmed I/O (PIO) operation of the parallel ATA (PATA) interface without provisions for supporting attachment of SATA protocol converters (see Figure 1). PATA is still supported on new moth- erboards in small form factors (such as Mini-ITX or Nano-ITX), particularly because it is still a mainstream inter- face for optical drives. Employing ATA as the low-latency embedded interface enables you to apply such motherboards instead of typical industrial platforms Photo 1—This low-cost industrial PC is based on a Mini-ITX motherboard interfaced to the real-world via an ATA (like PC/104, EBX, EPIC, or PICMG), I/O adapter. The number 1 indicates the CPLD containing the ATA I/O circuitry. The number 2 indicates the exter- which are considerably more expensive nal interface connector. The number 3 indicates the diagnostic LEDs. The number 4 indicates the front-panel I/O attachment. The front panel comprises an LCD dot-matrix display, three push buttons, and an incremental (see Photo 1). encoder. Typical ATA I/O adapters will fit into small CPLDs. Eventually, the application-specific circuitry could the appropriate hardware. A microcon- between software and external hard- find its place within the same CPLD, troller connected via a serial port, ware, as well as between two programs: too (see Figure 2a). ATA interface USB, or Ethernet is an obvious exam- one running on the PC and one on adapters can be provided for the ple. On the market, such hardware the microcontroller. It poses some attachment of widely available I/O (integrated circuits, modules, starter challenges. hardware, like Opto 22-compatible kits, and so on) is available in abun- In embedded systems design, typical racks, ISA or PCI I/O cards, and dance. Contemporary development application problems lead to some PC/104 modules (see Figure 2b). software is comfortable and, more kind of state machine, executing the often than not, free. following steps: first, fetch input data MOTIVATION But this approach has severe draw- (from sensors, operator panels, and the Low-latency control problems could backs too. Generally, there is the like); second, perform the necessary be solved outside of the PC by providing problem of functional partitioning decisions and calculations to deter- mine the next state and the outputs; third, emit output data (to actuators, Application- a) Application specific circuitry displays, and the like); and finally, environment ATA Adapter (CPLD) return to the first step. Functional partitioning is an art PC Platform rather than an exact science. It has to ATA General-purpose Relays, ATA Interface ...... be done even if you can get the I/O ports or optocoupler, adapter Field cabling application-specific ADCs, (front end) microcontroller together with its digital circuitry DACs, etc. ... programming environment for free. Whether it is a trivial task or not b) depends on the complexity of the Industry-grade second step. If the decisions and cal- I/O modules ATA Adapter (CPLD) culations to be executed in this step

PC Platform require a lot of computing power and ... memory capacity, low-cost external ATA ATA Interface ISA Bus ISA Field cabling adapter adapter hardware (i.e., PIC, AVR, or a small (front end) ... FPGA) will not do. In some cases, intermediate microcontrollers (i.e., Blackfin or ARM) would help. But many applications have to cope with vast performance requirements and Figure 2a—An ATA I/O interface adapter can accommodate the application-specific circuitry. b—Other adapter circuits high complexity. Many users expect emulate industry-standard interfaces, so readily available I/O hardware (PC/104 modules, industry-grade ISA cards, PCI cards, and the like) can be supported by up-to-date, low-cost PC platforms based on inexpensive motherboards (like the look and feel of Windows and the Mini-ITX or Nano-ITX). availability of advanced graphics,

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 61 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 62

tion of nine registers or I/O ports (see Data bus Host DD15...0 Drive(s) Table 1). So, it may seem a somewhat 16 trivial task to design appropriate inter- DA2...0 Addressing CS0- 3 face adapter circuitry. Such an adapter CS1- would resemble an old-fashioned ISA

DIORD- Read and write strobes I/O card, consisting essentially of an DIOWR- address decoder and attached input

IORDY and output registers. INTRQ But this obvious approach will not

DMARQ DMA work flawlessly. Because ATA was not DMACK- developed as a universal I/O interface,

RESET- but exclusively as an interface for attaching disk drives and other mass- CSEL Drive selection/signaling PDIAG- storage devices, some potential con- DASP- flicts are to be taken into considera- tion: the activities of the BIOS and the Figure 3—Here are the signal lines of the parallel ATA interface. operating system, the design of con- temporary host adapters, and the coex- istence of I/O adapters and drives database and networking services, ATA I/O can be seen as a viable (especially at the same ATA cable). and so on. This way, comparatively alternative in application areas that humble embedded control tasks and are the traditional domains of the SYSTEM SOFTWARE typical performance-hungry Windows (expensive) small-form-factor industrial During the boot sequence, the sys- applications become closely inter- PC modules. tem software (BIOS and operating sys- twined. Often, a practically viable tem) tries to detect which host function partitioning cannot avoid PRINCIPLES OF OPERATION adapters and drives are present. employing external high-performance In the beginning, ATA was a Because disk drives are essential to platforms (e.g., based on PowerPC or stripped-down ISA bus. The signal boot the system, the activities are Coldfire processors) running their lines are shown in Figure 3. Refer to deeply embedded within the system own real-time OS. (In other words, Figure 1 for the principal access software—they are not delegated to all of the decisive functions have cycles. Early host adapters comprised device drivers (which could be unin- been delegated to the external sub- only a data bus buffer and some stalled, if necessary). Hence, it is not system. The Windows PC is merely address decoding circuitry. The possible to circumvent them. Usual- used as an operating console, file addressing provisions were reduced to ly, BIOSes try to detect drives by server, print server, and network three address lines and two pre-decod- writing 00H (master) and 10H (slave) hub.) ed chip selects, supporting the selec- into the DH register and reading the Partitioning splits the development process into independent tasks (i.e., PC programming, microcontroller programming, and FPGA design). Without partitioning (all application programs reside in the PC), program development can be done completely within one environment (like Visual Basic, C#, or Delphi). From an average Visual Basic, C#, or Delphi program- mer, you can expect a PC-only solu- tion, not a mixture of PC program- ming, microcontroller programming, and hardware design. Therefore, many embedded sys- tems designers resort to the alterna- tive approach: leave all program activities to the PC and attach the application-specific hardware via Photo 2—One experimental platform suffices to try out different ATA adapter circuits because modern CPLDs can low-latency interfaces, especially via be programmed in the application system. The Xilinx XC95108 CPLD on this ATA I/O trainer can accommodate 8255 emulation, ISA emulation, and much more. The number 1 indicates an ATA connector. The number 2 indicates PCI cards, PC/104 modules, and a CPLD. The number 3 indicates diagnostic LEDs. The number 4 indicates an ISA (PC/104) slot with a PC/104 more. module. The number 5 indicates an Opto 22-compatible I/O connector.

62 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 63.qxp 4/9/2008 9:29 AM Page 1 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 64

DH register’s content Register block CS Register address Register (see Figure 4). This back. DA register will be delib- Command block 1- 0- 2 1 0 Hex Read access Write access erately prevented from HOST ADAPTERS 1 0 0 0 0 0 Data being read. A read ATA host adapters 1 0 0 0 1 1 Error Features access to the DH regis- reside in the mother- 1 0 0 1 0 2 Sector count ter will deliver “noth- board chipset. Experi- 1 0 0 1 1 3 LBA Low (7...0) [Sector no.] ing,” which results in ments have shown 1 0 1 0 0 4 LBA Mid (15...8) [Cylinder no. low] reading a constant that host adapters on 1 0 1 0 1 5 LBA High (23...15) [Cylinder no. high] value FFH. To avoid true legacy (remark- 1 0 1 1 0 6 Device [Device/Head (DH)] conflicts when the ably old) mother- 1 0 1 1 1 7 Status Command BIOS tries to detect boards behave like the ATA configuration, ISA devices. There are Control block 0 1 1 1 0 6 Alternate status Device control I will not use the no access restrictions. value 0H (in the bit Table 1—The ATA register file comprises only nine registers. The five registers in the colored section Data can be written will be used in ATA I/O adapters. positions 3...0 of the into and read from all DH register) as a valid ATA registers. But you cannot expect (see Photo 1). port address. So, my adapter will be contemporary host adapters to hidden completely from the configu- behave the same way. You can rely PRINCIPAL SOLUTION ration software and will pass the only on compliance to current ver- The solution relies on a few simple boot and initialization sequences sions of the ATA standards. provisions and tricks. I will consider without being noticed. Although additional ATA ports can only register addresses, which have be provided easily by insertion of no side-effects in the hardware (like ADDRESS SPACE appropriate add-in cards, it is advan- command initiation) and for which Four ATA registers are employed tageous to allow for the coexistence the ATA standard permits read and (see Table 1) and 15 of the 16 possible of I/O adapters and drives at the write accesses at random. The values in the bit positions 3...0 of the same cable—especially when the device/head (DH) register will be DH register are valid for port selec- cute, small motherboards are used used for device and port selection tion. Accordingly, an I/O adapter may

64 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 1/28/2008 4:14 PM Page 1 66.qxp 4/9/2008 9:29 AM Page 1 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 67

comprise up to 15 selec- one microcontroller-like table ports with up to four 7 6 5 4 3 2 1 0 8-bit-port comprising a addressable registers each. – – – Device I/O Port selection (port address) data register and a direc- In other words, a register tion register. But even the address space of 60 (i.e., Figure 4—This is the format of the DH register. detailed schematic of this 15 × 4) bytes will be sup- simple circuit would ported. an industrial computer system based occupy too much space. Hence, I will By applying the principles of 48-bit on a Nano-ITX motherboard featuring concentrate on the basic principles. addressing (ATA-6 and higher), an one parallel and two serial ATA ports. address space of 2,040 bytes (i.e., 255 × The parallel ATA port is used to REFERENCE DESIGNS 8) can be supported. All of the ATA attach one drive (DVD or flash memo- Based on Xilinx XC9500 CPLDs, some registers used (compare Table 1) are ry) configured as device 0 (master) and ATA I/O adapters have been designed included in the 48-bit addressing some I/O adapter ICs (CPLDs or and—of course—tested intensively. scheme. FPGAs), which together constitute Photo 2 shows one of the test plat- the device 1 (slave). forms. Porting to other families of DEVICE SELECTION To support such configurations, programmable ICs should pose no Whether the adapter will be selected each adapter IC has to be assigned to difficulties. The design documenta- or not depends on DH register bit a different subset of I/O port address- tion, including complete Xilinx ISE position 4 (DEVICE) and an input sig- es. Each adapter should write to ATA projects, detailed schematics, and nal MASTER/SLAVE SELECT. This registers or drive the ATA data bus descriptions is readily available for input can be connected to the inter- only if the DH register contains a downloading. The four designs men- face signal cable select (CSEL) or tied valid port address. tioned below fit into Xilinx XC95108 to a fixed potential (low or high). To CPLDs. Expect more to come. select the device, load the DH register PATA CIRCUITRY The first design is five universal with the corresponding value (with 0, An ATA I/O adapter consists of I/O ports. The I/O ports are similar if the I/O adapter is configured as the gates and flip-flops. The principle of to the typical I/O ports of well- master, or with 1 if it is configured as operation is comparatively simple, known microcontroller families (e.g., the slave). especially if only PATA is supported Microchip PIC and Atmel AVR). (there are no complex state machines Under program control, each of the MORE THAN ONE ADAPTER IC and the like). Very basic adapters fit 40 (i.e., 5 × 8) I/O lines can be used It should be possible to attach more into small CPLDs, containing 32 to as an input or as an output. Each I/O than one I/O adapter without resorting 36 macro cells. An appropriate exam- port comprises a direction control to the obvious principle of master/slave ple adapter consists of the ATA front- register (DIR) and a data register (DAT). selection. An application example is end circuitry (described below) and The DIR bit positions control the

ATA Front end Write data W_DAT ATA ATA Interface ATA Connector ATA Address signals DEC Read data A2...0

Port address in ... DH register Output Input SEL DH3...0 registers data GEN_REG_ Write address R_DAT Access enable ACCESS decoder D RG Write strobe ... WR_PULSE Hdw reset CLEAR READ_ADRS CE DEC Read data CLK selection CLR

D RG Read address ...... decoder CE DEC CLK CLR Port address ATA Output enable (read access) decoder ......

Figure 5—This ATA I/O adapter is based on a front-end function block. The read data lines are attached via data selection circuitry. Address decoding, data selection (e.g., by means of multiplexers), and output registers are application-specific.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 67 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 68

programs, ATA I/O hardware can be accessed directly by I/O instructions. It DMACKn could not be simpler (especially when CS1n GENERAL_ACCESS compared to attempts to program a DMARQ USB host adapter without system-pro- CS0n vided APIs). In Windows, programming via simple DA0 A0 port drivers will lead to the usual DA1 A1 latencies like the well-known I/O pro- DA2 A2 gramming of the parallel port. In this CSEL respect, ATA I/O could be seen as a substitute for the good old parallel DH_ACCESS port, which is lacking on nearly all contemporary commercial-grade motherboards (at least in small form SLAVE_SELECT factors). However, if the latencies are to be avoided, the entire I/O part of DIOWn WR_PULSE the application program must be writ- DIOR DIORn ten as a kernel driver. RD_PULSE FUNCTION BLOCKS RESETn CLEAR Because you want to support the development of truly application-spe- cific I/O adapter hardware, it is advan- Figure 6—This part of the principal ATA front-end schematic shows the ATA address and control signals together tageous to distinguish between the with the basic address decoding, distinguishing between the I/O registers (GENERAL_ACCESS) and the DH register (DH_ACCESS). ATA side and the application side of the adapter circuitry (see Figure 2). direction of the corresponding I/O pins. 8-bit I/O cycles and to the support of Obviously, the circuitry that con- If the DIR bit is set to zero, the pin ISA interrupts. nects directly to the ATA interface is configured as an input, with the The fourth design is parallel port could be some kind of standardized pin driver in a high-impedance state. emulation. The circuit behaves like an function block. This function block If the DIR bit is set to one, the pin is IEEE 1284 standard printer port (SPP) is called the ATA front end. Figure 5 configured as an output. The poten- with optional support for the bidirec- shows the function block together tial (low or high) on the pin corre- tional (PS/2) mode. In addition to the with the application-specific inputs sponds to the bit in the DAT register. 17 signal lines of the parallel port, two and outputs and the corresponding Contrary to the operation of some universal ports are provided. address decoding circuitry. Output microcontroller ports (e.g., Atmel AVR), data is held in registers. Input signals only the potentials on the pins can be RELATED SOFTWARE do not require particular registers read back. This Spartan solution was ATA interface adapters should be because the front end contains a chosen to make the design fit into a 108- programmed like microcontrollers’ I/O common Read data register. Hence, macrocell CPLD. Therefore, the modifi- ports. The description of a particular they can be attached via a data selec- cation of DIR and DAT register contents interface adapter will show the accessi- tor. has to be done by software (based on reg- ble registers, the corresponding The front end contains the DH regis- ister copies held in RAM). With respect addresses, and if necessary, the meaning ter, the data paths, and the basic to internal processing speed and RAM or effect of each individual bit position. decoding circuitry (see Figures 6 and 7). capacity, PCs are obviously superior to The only difference between the The principle of operation will be little microcontrollers. Consequently, low-level programming of a conven- explained by referring to the corre- the speed penalty is negligible. tional I/O circuit (like the vintage sponding Boolean equations. The second design is 8255 emula- 8255) and corresponding ATA I/O pro- A PIO access according to the ATA tion. This circuit behaves like an 8255 gramming is that the I/O register standard should be executed if there is in mode 0. In addition to the three access must be preceded by loading no DMA access and if the selection 8255 I/O ports, two universal ports are the device selection bit together with lines CS1– and CS0– are high and low, provided. the port address into the DH register. respectively (see Table 1): The third design is ISA interface Source code examples (in C) are avail- GENERAL_ACCESS = !DMARQ * emulation. The purpose of the circuit able on the Circuit Cellar FTP site. DMACK– * CS1−− * !CS0 is to support ISA I/O cards and, above all, PC/104 I/O modules. Hence, the ATA I/O & THE OS The DH register is accessed if PIO access ISA emulation could be restricted to Under Linux, DOS, or in stand-alone has been initiated and if the DH register

68 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804016_Matthes.qxp 4/9/2008 9:24 AM Page 69

is selected via the ATA address lines: port register addresses is left over to API. Designing appropriate adapter hard- DH_ACCESS = GENERAL_ the application-specific circuitry. The ware is comparatively easy. It requires ACCESS * DA2 * DA1 * !DA0 READ_ADRS signal has to be activat- nothing more than a small CPLD—and ed by the application-specific circuit- a few gotchas to be considered. ATA I/O The ATA I/O adapter has been selected if ry. It should be active if the current adapters have been attached to all kinds the device address bit in the DH register port address in the DH register is a of PC motherboards. Besides the obvi- matches the master/slave configuration: valid port address of the particular ous application of using up legacy ATA I/O adapter (selective addressing). hardware, it is especially compelling to DEVSEL =+ DH4 * SLAVE_SELECT I highly recommend that you design apply such adapters together with !DH4 * !SLAVE_SELECT = DH4 xnnor SLAVE_SELECT the address decoders carefully. So- miniaturized motherboards of the called alias addresses (caused by incom- commercial high-volume market, such A common access-enable signal for the plete or sloppy address decoding) are to as Mini-ITX, Nano-ITX, and Pico-ITX. other four supported ATA registers be avoided. Each ATA I/O adapter Supporting Serial ATA (SATA) will be will be asserted if a PIO access is exe- should react only on valid addresses. the next logical step. I cuted, if the ATA I/O adapter has been selected, and if the current access does DATA PATH STRUCTURE Wolfgang Matthes (w.matthes@t-online. not address the DH register: Because CPLDs do not support tri- de) has developed peripheral subsys- state buses, separate read and write data tems for mainframe computers and GEN_REG_ACCESS = GENERAL_ conducted research related to special- ACCESS * DEVSEL * !DH_ACCESS paths have to be provided. Write data are propagated from the ATA data bus to the purpose and universal computer If a read access with a valid port internal write data bus. Read data are architectures for the last 20 years. He address is executed, the ATA data bus clocked into the synchronization regis- has also taught Microcontroller driver is to be enabled as long as the ter and driven onto the ATA data bus. Design, Computer Architecture, and read strobe line is asserted: Electronics (both digital and analog) at the University of Applied Sciences READ_ENABLE = GEN_REG_ THE NEXT STEP In contemporary PCs, ATA is the last in Dortmund, Germany, since 1992. ACCESS * READ_ADRS * !DIOR remaining low-latency interface provid- Wolfgang’s research interests include The decoding of the particular I/O ing a straightforward hardware/software advanced computer architecture and embedded systems design. He has filed over 50 patent applications and Read data synchronization written seven books. Read data ATA Data R_DAT(7:0) D[7:0] Q[7:0] DD(7:0)

E PROJECT FILES RD_PULSE C To download code and schematics, go to Write data ftp://ftp.circuit cellar.com/pub/Circuit_ W_DAT(7:0) Cellar/2008/214.

DH Register READ_ENABLE W_DAT(0) DH0 RESOURCES DI0 DO0 DH0 W_DAT(1) DH1 DI1 DO1 DH1 W. Matthes, “ATA Interface Misused,” W_DAT(2) DH2 DI2 DO2 DH2 Elektronik, 2006. W_DAT(3) DH3 DI3 DO3 DH3 W_DAT(4) Device selected DI4 DO4 ———, “Input/Output Device for DH_ACCESS CE Attachment to a Drive Interface,”Ger- WR_PULSE C man patent application DE 10 2005 CLEAR CLR 002 339.8. SLAVE_SELECT DEVSEL The ReAl Computer Architecture,

GENERAL_ACCESS www.realcomputerarchitecture.com. GEN_REG_ACCESS DH_ACCESS Technical Committee T13 AT Attach- ment, “ATA Standards,” www.t13.org.

READ_ADRS DIOR SOURCE

Figure 7—Here are the data paths and the DH register. To avoid metastability conditions at the ATA data bus, XC95108 CPLD asynchronous read data will be clocked into a synchronization register by the leading edge of the ATA read Xilinx, Inc. strobe signal. www.xilinx.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 69 27805002-Bachiochi.qxp 4/9/2008 9:23 AM Page 70

FROM THE BENCH by Jeff Bachiochi

Control Circuitry Advances in video game technologies and controllers are changing the ways we interact with gaming consoles. If you don’t want to buy expensive power pads and controllers, you can follow Jeff’s lead and build your own controllers with much of the same circuitry.

Dance dance revolution! And what accomplish tough moves. It’s crazy to information on the PS2 (or any other a revolution it was! see the footwork necessary to com- system you are interested in). Of Konami’s “Dance Dance Revolution” pete at the upper levels of these con- course, everyone is trying to get you (DDR) was one of the first “video tests. to buy something, so you might have games” to involve its participants in a The newest variation to the dancing to work a bit to get through the ads. level of physical activity beyond typi- theme is to perform in a new way. In this case, although I could have cal exploration and defensive thumb Activision’s “Guitar Hero” (GH) lets hooked up a scope to the PS2 and fig- twiddling. Although there is a signifi- you perform like a rock star. Don’t ured out the interface, I knew I could cant amount of memorization want to take years of music lessons? save some valuable time by seeing what involved with many games (e.g., when No problem. With GH, you can per- information was already out there. A to use a particular weapon, where to form like a rock star right away. Out number of sites offer the same pinout find a hidden prize, or how to obtain a with the floor mat and in with the and command reference, but I like goal), the sedentary posture associated guitar controller. The controller does- Hardware Book (www.hardwarebook. with playing them isn’t conducive to n’t have strings; it has just five but- info) because it has a lot of informa- combating obesity. DDR requires play- tons for one hand and a strummer tion on one site. ers to memorize and perform foot (button) and a whammy bar (one-half The next roadblock was (and often movements in time with on-screen of an analog joystick) for the other is) a special connector that might be cues and “hip” soundtracks. Instead of hand. The on-screen cuing is similar necessary to make a connection to using a typical hand-held joystick, the to DDR. Pick your song and start per- proprietary equipment. The least player, or “dancer,” steps on a colorful forming. While you aren’t actually expensive approach is to get a con- floor mat divided into pressure-sens- playing the real notes (after all, you troller expansion cable. The advantage ing areas. Body weight triggers the have only five buttons), it’s your syn- of the cable is that you get both male input. Screen cues designate which chronization that produces the highest and female connectors for a single areas to step on. Successful triggering, scores. price, sometimes for as low as $3. stepping on only the appropriate area This month, I’ll show you how to With a connection pinout and an idea at the appropriate time, scores high investigate the Sony PlayStation 2’s about what the communication proto- points. This is similar to learning to (PS2) controller interface and replace a col is, drawing up a schematic and dance by following painted footprints controller all with the same circuitry. putting together a prototype is on the floor. First, you’ll use the circuitry in Figure 1 straightforward. The PS2 interface It’s no wonder music provides a con- to simulate the PS2 system and make requires five signal lines (besides nection to others. Our lives are full of inquiries about which peripheral is power and ground). The controller naturally occurring rhythmic sounds plugged into it. Then, the same cir- operations require 16 bits plus four and many individuals even carry a cuitry will be configured to look like a analog inputs. That’s a total of 25 con- music player around with them. It’s PS2 peripheral controller. To begin, I trol lines. Some 28-pin, flash-memory- not too hard to understand why the will examine the communications based microcontrollers have just DDR craze has caught on. Arcades medium of the PS2. enough I/Os. I could have chosen to offer a string of DDR machines. They go to a 40-pin device, but I wanted to usually have railing that not only keeps SEARCH keep it as inexpensive as possible. the dancer from losing their balance, With your favorite search engine, The design in Figure 1 can be used but it also provides added leverage to you can look around the ether for to perform two different tasks. It’ll

70 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 27805002-Bachiochi.qxp 4/9/2008 9:23 AM Page 71

Figure 1—This schematic can be used for a number of functions. As a controller, the SPI is configured as a slave and the microcontroller collects data and replies to a master SPI device (PlayStation 2). As a controller identifier, the SPI is configured as a master and queries a connected controller for type and status. The LCD displays the controller type and button status. As a monitor, the SPI is only a slave input device. It can display raw data from a PS2 or from a controller.

begin its life acting like a PS2 gaming hooked up to answer these com- controller (see Figure 2). The con- system and send out command bytes mands, communication would cease. troller acknowledges each byte looking for a controller. When a con- However, I would now have the for- received with an ACK. This enables troller is plugged into the circuit, the mat necessary to interrogate a con- the controller to signal when it is fin- controller will answer back with data troller, the same information an Inter- ished processing the byte received bytes indicating what it is and the sta- net search provided, so I could continue. from the system. This includes writ- tus of its inputs. Because the reply can To look like a PS2 system, the ing a data byte (reply) to the SPI be several bytes in length, I wanted to microcontroller needs to communi- buffer. Remember that the SPI mode collect this information and display it cate with a SPI format as a master and uses separate data in and out lines, in an intelligent format other than on provide an *SS (ATT) select line to the enabling data to pass in both directions an LED. This requires being verbose. I chose adding an LCD

to the circuit because all of the ATT inputs would not be necessary

when acting as a system. CLK If I was doing this project

without knowing the proto- CMD col, I would first program it to look like a controller to DAT the PS2 and display the com- mands it sent. I would then ACK ensure the system sends out two bytes, 0x01 and 0x42. Figure 2—The clock timing is 250 kHz (for the PS1) and 500 kHz (for the PS2). The clock is idle high with data changing on the Without a real controller falling edge and sampled on the rising edge. The controller acknowledges each 8-bit transfer (except the last).

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 71 27805002-Bachiochi.qxp 4/9/2008 9:23 AM Page 72

at the same time. The only catch is system brings ATT high. that the data pertinent to the last The SPI port on the Microchip command isn’t passed until the next Technology PIC16F737 is set up with command is clocked. a 250-kHz clock, the maximum rate If a controller is connected, it will of a PlayStation 1 (PS1). (The PS2 will respond with its own identification, as run at 500 kHz, but running slower is well as a number of data bytes defined acceptable.) The clock idles high and by its identification. As long as the con- data changes on the falling edge and is troller continues to acknowledge each read on the rising edge. In Table 1, you byte it receives, the master will contin- can see that if I send out an 0x01, a ue to send out additional idle com- controller will respond with meaning- mands. (While the documentation I less data (because it doesn’t know found states 0xFF, I see 0x00 being sent what I want yet). If the second byte I for idle.) When the system retrieves the send is a 0x42, a controller should expected number of data bytes, it will respond with a byte identifying itself. cease communications by raising ATT. At this point, I will need to adjust The controller need not ACK once the the number of additional requests

Sequence System command Controller response (byte/bits) Controller First 0x01 0xFF (meaningless) All Second 0x42 0x12 PSX Mouse 0x23 NegController 0x41 Standard digital pad 0x53 Analog controller green 0x73 Analog controller red Third 0xFF 0x5A All Fourth 0xFF 0xFF PSX Mouse L D R U ST — — — NegController L D R U ST — — SL Standard digital pad L D R U ST — — — Analog controller green L DRUSTJRJLSLAnalog controller red Fifth 0xFF — — — — — R L — PSX Mouse — — — B A R1 — — NegController SQ X CI TR R1 L1 R2 L2 Standard digital pad R2 X CI R1 TR SQ L1 L2 Analog controller green SQ X CI TR R1 L1 R2 L2 Analog controller red Sixth 0xFF Delta vertical PSX Mouse Steering (0x00=R, 0xFF=L) NegController None Standard digital pad Right joystick (0x00=L, 0xFF=R) Analog controller green Right joystick (0x00=L, 0xFF=R) Analog controller red Seventh 0xFF Delta horizontal PSX Mouse I button (0x00=out, 0xFF=in) NegController None Standard digital pad Right joystick (0x00=U, 0xFF=D) Analog controller green Right joystick (0x00=U, 0xFF=D) Analog controller red Eighth 0xFF None PSX Mouse II button (0x00=out, 0xFF=in) NegController None Standard digital pad Left joystick (0x00=L, 0xFF=R) Analog controller green Left joystick (0x00=L, 0xFF=R) Analog controller red Ninth 0xFF None PSX Mouse L1 button (0x00=out, 0xFF=in) NegController None Standard digital pad Left joystick (0x00=U, 0xFF=D) Analog controller green Left joystick (0x00=U, 0xFF=D) Analog controller red

Table 1—This is a PlayStation command/response table for various controllers. Depending on the controller, there are up to 9 bytes of pertinent response.

72 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 27805002-Bachiochi.qxp 4/9/2008 9:23 AM Page 73

Initialize SPI Interrupt

Save received byte Initiate a command to response table sequence by placing 0x01 into SSPBUF

Y Second byte? SPI Done? Determine total number of N bytes to look for N

Y

Legal Y Last device? byte? N Flag done N Y Display “No device” Put next Same device command into as last time? N SSPBUF Display appropriate Y device message Display data IReturn

Figure 3—This is a block diagram of the application used to query and report on the type of controller that is plugged into the circuit. The circuit looks like a PlayStation to a controller.

depending on the type of controller control register and high when talking that is responding. Once I have gath- to the data register; read/write (RW) ered all of the data, I will use the LCD high to read and low to write data; to identify the controller. and data strobe (E) to latch the data. In I have a standard 4 × 20 LCD. 4-bit mode, you must perform two Although the display has an 8-bit data actions for each byte (MSN then LSN). bus, I am using the alternate 4-bit Because the LCD powers up in 8-bit mode to converse with it. The LCD mode, the first transfer is an 8-bit requires three control lines: register transfer. Although the data bus has select (RS) low for conversing with the eight I/O lines, only the top four are

Initialize SPI Interrupt

N N Received Select button 0x01? pressed? Y Y Send idle Clear Set appropriate appropriate bit in table bit in table N Received 0x42? Check and save Look for other Y the state of the possible remaining buttons commands Send next byte from table N A/D conversion ready?

Y More?

Put conversion value into table - Start conversion on the next channel IReturn

Figure 4—This application enables the circuit to look like any type of controller to a PlayStation 2.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 73 27805002-Bachiochi.qxp 4/9/2008 9:23 AM Page 74

the current status to a table. The table is, in fact, a list of the responses that we will use when the system sends a com- mand to query the status of the con- troller. The buttons are all tested and the data table is updated accordingly in the main loop of the application. That’s all that happens in the main loop. Converting the four joystick posi- tions is a bit different because the conversions take time. Although the ADC produces an interrupt on “end- of-conversion,” if an interrupt occurs during a transmission from the PS2, the transmission will be lost. The PS2 will give up if it gets no response (ACK) in approximately 60 µs. (That’s 60 instructions running with a 1-µs instruction time.) Instead of using the interrupt, I poll the interrupt flag in the main loop. The main loop can Photo 1—Families that play together. I guess it takes fewer hours to learn the skills necessary to become a “Guitar Hero” than to actually learn how to play the guitar. As for me, gimme a real axe any day. then branch to a read and store the conversion whenever the conversion is finished, yet still be interrupted by connected to the LCD. So, when you the correct data. The correct data the SPI interrupt whenever communi- write a byte to those eight lines, only should have been 0x01, but I was cation is requested. The A/D routine the top four have useful data (logic sending 0x01. Is that a typo? No it also increments the analog channel so levels). Because the lower four are not isn’t. Let me explain. Had I paid suffi- the next joystick is converted, all four connected, the data on them goes cient attention to the specifications, I in round-robin fashion. nowhere. This sequence places the wouldn’t have assumed the data was SPI communication from the PS2 LCD into 4-bit mode and it will most significant bit (MSB) first (as in controller has top priority and is the remain in 4-bit mode until it is pow- standard SPI hardware). In fact, it is only interrupt routine. Once a SPI ered down. This is the only time that least significant bit (LSB) first. Because interrupt has occurred (the last of 8 bits your transfer will be a single-action I couldn’t define this using the hard- are clocked into the receiver), there is transfer. All communications must ware SPI, I had a choice. I had to no time for lollygagging around. I treat now consist of two transfers (MSN either bit bang an SPI port or trans- all communications (while ATT is then LSN). This is important to remem- form all of the data going to or coming low) in this interrupt without leaving ber for two reasons. To stay in sync with from the hardware SPI. I chose the lat- after each character is processed. I the LCD, all remaining transfers must be ter. I simply remapped all of the data look for the 0x01 (0x80 in your reverse in pairs. Second, if you are using a and stored it in reverse order. I origi- case) and then look for a query com- debugger that keeps the power on and nally thought I could use a routine to mand (0x42). The data I need to reply you halt and restart the program again, take the data and reverse it before with is already formatted in a table the single transfer that initializes the writing it into the SPI buffer (or after and the bytes can be transmitted to LCD to 4-bit mode will put the LCD out reading a byte from the SPI buffer), the PS2 as it continues requesting of sync the second time around because but I found that this took too much data. If at any point the ATT line goes its already in 4-bit mode! time (more on this later). high, the system has discontinued Figure 3 shows how the circuit is communication, so the interrupt used to identify controllers that are SETTING THE STAGE routine is exited and the main loop plugged into the connector J1. (Note Now that we’ve identified various continues updating the status of the that the SDI and SDO need to be controllers using the circuit to emu- buttons and joysticks. remapped on the connector because the late a PS2, it’s time to make the circuit The documentation I found so far SPI I/Os can not be remapped by the act as a controller to the PS2. This has not mentioned any other com- application. This can be done by moving application has less to do with emulat- mands other than 0x42. This seems the jumpers on JPx.) When I powered up ing the PS2, however, because we are rather limited. I know from experi- the circuit, I thought I had something not “in charge” of the timings. Every- menting that the analog joystick has a wired incorrectly because there was no thing is a lot more critical. We need to button on it that can change its format response from any controller plugged keep track of the present button (digital) from “standard digital pad” to “analog in. Then it hit me. I wasn’t providing and joystick (analog) states and apply controller.” When initially powered, it

74 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 27805002-Bachiochi.qxp 4/11/2008 10:58 AM Page 75

defaults to “standard digital pad.” This you would need to add a level shifter might be so it can be backward-compati- on the TX output if you wanted to ble to a PS1. On the PS2, when a game implement this function. like “Guitar Hero” is used, the con- troller is automatically redefined as an AXE MEN “analog controller.” This means that Once the controller is recognized by there must be other commands issued the PlayStation, the hard part is done. by the PS2 that the controller can Constructing the controller of your respond to. A little more fishing around fantasies takes a bit of dreaming. Com- on the ’Net revealed a text file on mercial video games use buttons and Lynxmotion (www.lynxmotion. joysticks that can take some pretty com/images/files/ps2cmd01.txt) that heavy abuse. You might imagine some has a bit more sketchy information. special implementation for a physically I’ll leave this for you to investigate if challenged friend. For this project, I you are interested. As you can see in wanted to convert an old guitar into a Figure 4, I left room in the code for controller. To prototype the inputs, I cut “other additional commands” to be out a guitar shape from a piece of thin recognized and responded to. But for masonite. Photo 1 shows a picture of my my purposes, this is all that’s neces- youngest son Kris and me battling it out sary to achieve my goal. “Guitar Hero” style to one of his favorite tunes. I can’t come close to his SPILLING THE BEANS mastery, even when I play in the lowest I thought that I might be able to dis- levels! I can only hope that college life play PS2 communications using the contains time for studies amongst the LCD. The PS2 sent out communications heavy concert schedule. Incidentally, the about every 18 ms. At that rate, the DDR dance pad input device looks like a data filled up the screen and rewrote all “standard digital pad.” You can emulate 80 characters over and over, which was that just as easily with this circuit. faster than I could view anything. It This is the first time I’ve jumped turned out to be pretty much useless. into the gaming venue. If you’d like to By monitoring the ATT input and an see more on this subject, or if you additional input from a push button on have any other areas of interest, drop the microcontroller, I paused the display me an e-note. I’m always looking for on one full command of data until I ways to broaden my horizons. I pushed the button. In reality, because there are two data paths, one from the Jeff Bachiochi (pronounced BAH-key-AH- PS2 and one from the controller, I want key) has been writing for Circuit Cellar to collect both at once. This isn’t going since 1988. His background includes to happen with a single SPI. product design and manufacturing. He The circuit has a jumper (JPx) that may be reached through the magazine routes which line (CMD or DATA) gets ([email protected]) or his fed to the SDI input. This way, you can web site (www.imaginethatnow.com). choose to look at either the commands or the responses in the monitor mode. PROJECT FILES Because the real-time data overruns the To download code, go to ftp://ftp.circuit LCD, an alternative approach would be cellar.com/pub/Circuit_Cellar/2008/214. to ship the data out using the microcon- troller’s UART and observe the CMD or RESOURCES DATA communications using HyperTer- minal. If we receive 9 bytes at a poten- Hardware Book, www.hardwarebook.info. tial 60 times per second, and if we need Lynxmotion, Inc., www.lynxmotion.com to send a format of at least 3 bytes /images/files/ps2cmd01.txt. (two hexadecimal ASCII characters and a space) for each byte received, that is 1,620 bps (i.e., 9 × 60 × 3), or a data rate SOURCE of 16,200 bps (i.e., 1,620 × 10 bits). PIC16F737 Microcontroller The UART’s next largest standard Microchip Technology, Inc. value would be 19.2 kbps. Of course, www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 75 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 76

SILICON UPDATE by Tom Cantrell

Designer’s Best Friend The roots of Altera’s MAX II go back about 30 years to the programmable array logic (PAL) device. This month, Tom covers the history of programmable logic chips and introduces you to MAX II technology. Say hello to his little friend.

In this the twentieth year of Circuit them, like all things silicon, program- Programmable logic chips cover a Cellar magazine, I find myself con- mable logic chips have marched to the huge spectrum from $1 to thousands templating new developments in the tune of Moore’s Law. They’ve lagged of dollars. Towards the high end, the context of history. Like they say, you behind the parade a bit compared to implications for designers are clear. can’t know where you are if you don’t more generic parts like DRAMs and The situation is pretty much summed know where you started. MCUs; but nevertheless, they’re light up with the phrase “ASIC refugees.” If This month, let’s look at a chip years ahead of the original PALs. you’ve been designing ASICs, chances whose roots go back three decades to a But what matters to designers isn’t are at some point (if not already) chip called the programmable array whether a particular chip delivers you’ll be switching to FPGAs. logic (PAL). The PAL wasn’t the first more for less over time. That just At the low end, the situation is less programmable logic chip per se, but means everything gets cheaper, but it clear, which inspires this month’s following a bit of a rocky start, it doesn’t necessarily change a designer’s contemplation. Can programmable became the first to make a big splash perspective in terms of what chips to logic chips penetrate mass-market in mainstream applications.[1] use for what applications. applications by supplementing or even These days, program- mable logic chips go by different names, such as EPM240/ EPM570/ EPM1270/ EPM2210/ EPM240Z EPM570Z EPM240G EPM570G EPM1270G EPM2210G CPLD or FPGA; but ulti- mately, the benefit Logic elements (LEs) 240 570 1270 2210 240 570 proposition is basically Typical equivalent macrocells 192 440 980 1700 192 440 the same as it was way Equivalent macrocell range 128 to 240 240 to 570 570 to 1270 1270 to 2210 128 to 240 240 to 570 back when—to wit, the User flash memory (UFM) – bits 8,192 8,192 8,192 8,192 8,192 8,192 opportunity to roll your own chip. Maximum user I/O pins 80 160 212 272 80 160 [1] I say we bring back the Propagation delay (tPD1,ns ) 4.7 5.4 6.2 7 7.5 9 [2] PAL moniker. I mean, Frequency (fCNT, MHz ) 304 304 304 304 152 152 CPLD and FPGA don’t Input set up time (tSU, ns) 1.7 1.2 1.2 1.2 2.3 2.2 exactly roll off the Output delay time (t , ns) 4.3 4.5 4.6 4.6 6.5 6.7 tongue, do they? And CO Notes: what could be better [1] tPD1 represents a pin-to-pin delay for the worst-case I/O placement with a full diagonal path across the device and combinational from a warm and fuzzy logic implemented in a single LUT and LAB that is adjacent to the output pin. branding perspective? [2] The maximum frequency is limited by the I/O standard on the clock input pin. The 16-bit counter critical delay will run faster than Let’s hear it system this number. designers, who’s your Table 1—The Altera MAX II family tree has three lines. Regular MAX II parts run off a 2.5- to 3.3-V supply thanks to an on-chip 1.8-V voltage buddy? regulator. The MAX IIG dispenses with the regulator to run off a 1.8-V supply directly, reducing dynamic power consumption. The MAX IIZ Whatever you call goes further by reducing standby power, albeit with a performance hit.

76 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 77

I/O Bank 2 differences are power related. That’s important, because historically, pro- grammable logic hasn’t been known for being especially “green” or suit- able for battery-powered applications. The entire line-up is based on a 1.8-V Also supports the 3.3-V PCI internal core supply, but the regular All I/O banks support I/O standard MAX II parts offer the convenience of 3.3-V LVTTL/LVCMOS an on-chip voltage regulator to run off 2.5-V LVTTL/LVCMOS an external 3.3- or 2.5-V supply. The 1.8-V LVTTL/LVCMOS 1.5-V LVCMOS MAX IIG just dispenses with the regu- I/O Bank 1 I/O Bank 3 lator to run from a 1.8-V supply directly, which significantly reduces power consumption. Same for the MAX IIZ, which also has a special provision for “zero power” applica- tions, as we’ll see later. Note that the “Z” option is only offered for the two smaller parts (’240 and ’570) and comes with a performance hit (clock rate and propagation delay). I/O Bank 4 I/O wise, all of the parts are versa- tile, supporting the usual I/O suspects, Figure 1—Multiple independently powered I/O banks (four on the larger parts, two on the smaller) that each support multiple interfaces make the MAX II an obvious candidate for power management in multi-voltage designs. as shown in Figure 1. There are some caveats though. The two larger parts displacing standard chips? To what MAX II is really an FPGA, indeed (’1270 and ’2210) feature four separate degree, how soon, and in what apps? using exactly the same SRAM-based I/O banks versus two banks for the Let’s take a look at a latest and look-up table (LUT) logic fabric as smaller parts. More banks are not only greatest descendent of our old PAL Altera’s Cyclone FPGAs. The “macro- useful to support more different inter- and see just where we stand. cell” count is just an estimate based faces, but they also offer more flexibil- on an empirical FPGA logic element ity in terms of granularity. For exam- YOU SAY TOMATO (LE) to “macrocell equivalent” conver- ple, with four banks, you can run I suppose it’s best to get the buzz- sion factor. MAX II isn’t actually “live three-fourths of the pins at one level words out of the way right up front. at power-up” like the original fuse- and one-fourth of them at another, Altera calls their MAX II a “CPLD,” based PAL, but it’s the next best thing something that isn’t an option with which is presumably deemed to be with on-chip flash eliminating the just two banks. more “complex” than a regular need for an external memory chip to Along the same lines, only the two “PLD.” But depending on how you store the configuration. larger parts offer PCI compatibility look at it, it’s really a “PAL on Altera got their start with PAL-like because the smaller parts don’t have steroids” or an “FPGA in drag.” (i.e., true macrocell architecture) chips enough logic capacity to support that Like the original PAL, the MAX II is and still offers them today (e.g., interface. The implications go further a self-contained, single-chip solution. MAX3000 and MAX7000). But the than just PCI because the PCI I/O Furthermore, it’s pitched for pin-cen- showstopper for the traditional macro- capability provides a means (i.e., tric “control-path” (i.e., high pins/ cell approach is that it doesn’t scale clamp diode) for the larger parts to logic ratio, low pin-to-pin delay) appli- up well. The “everything-to-every- handle 5-V TTL or CMOS I/O with cations just like the PALs of yore. thing” interconnect strategy self- the addition of an external resistor or Cars are still measured by “horse- destructs (more wires, more power, two. The smaller parts might be able power” even though nobody rides a less logic utilization) as macrocell to output to a 5-V TTL chip (presum- horse. Along the same lines, MAX II count climbs into the 100s and ing the MAX II 3.3-V output meets

chips are still ranked in terms of PAL- beyond. In short, the original PAL the TTL chip VIH minimum spec), but era “macrocells,” a combination of architecture has just outgrown its sili- that’s about it. OR and AND gates (sum-of-products) con britches. As for packaging, there are three and some I/O (e.g., flip-flop). Of basic options, including TQFP, “fine course, there are a lot more macrocells VOLTSWAGEN line” BGA (1-mm pitch), and the lat- these days. The original PAL had The MAX II comes in three flavors: est “micro fine line” BGA (0.5-mm eight, while the MAX II line-up runs regular, “G,” and “Z.” Under the pitch). Pin counts range from 68 all from 100s to 1,000s (see Table 1). hood, they’re all basically the same the way to a whopping 324 pins. The irony is that under the hood the (i.e., Cyclone FPGA logic). The main Understandably, not every part is

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 77 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 78

(STAPL) known as “Jam.” During

UFM Block development, the PC and the Altera tools (i.e., Quartus II software and JTAG download cable) handle all of PROGRAM Program RTP_BUSY ERASE erase BUSY the programming details behind the control scenes. But if you want to do in-sys- OSC_ENA OSC ÷ 4 OSC tem configuration, your design needs enough smarts to host its own “Jam Player” (i.e., device programming soft- 9 UFM Sector 1 ware), as well as room to hold the ARCLK UFM Sector 0 MAX II configuration data itself (“Jam Address register Byte Code” aka “JBC”). The Jam Player is written in “C” for 16 16 easy porting, a process that boils down ARSHFT to mapping your hardware connec- tions to the MAX II JTAG pins and ARDin tweaking a delay loop for proper tim- DRDin Data register DRDout ing. But the convenience comes at the DRCLK cost of a sizeable memory footprint. DRSHFT An example port running on a 68000 puts the toll at roughly 96 KB of ROM and 48 KB of RAM.[3] Altera also has Figure 2—Besides the “configuration flash memory” (CFM) that makes the MAX II “live at power-up,” there’s an app note using an 8051 for in-sys- also an 8-Kb (two sectors, 256 × 16 each) “user flash memory” (UFM), which is a handy place to store data. The tem programming, but it isn’t pretty.[4] UFM could even eliminate the need for an external EEPROM chip, but watch out for the limited write endurance Limited memory means the ’51 can (100 cycles). barely handle the smallest MAX II chips, and limited MIPS make for long offered in every package with the and ground planes). (as in many minutes) programming lower pin-count packages naturally times. biased towards the parts with less JAM SESSION Presuming a design has the smarts logic and higher pin counts towards Ignoring the FPGA innards, as to handle in-system programming, the those with more logic. described so far, the MAX II is kind of MAX II deals with the gotchas. For The “micro fine line” packages like a 1970s PAL, just one where every instance, it’s possible to use a “real- stand out by cramming a lot of I/O spec is improved. But that’s only the time ISP” mode that has the flash into a little board space. Make that start. The MAX II not only does every- memory updated in the background “Lot” and “Little” with a capital “L.” thing a PAL did better, but it also does while the existing configuration (i.e., For example, TQFP parts consume a lot of new stuff too. in SRAM) continues to run. The new about 3 mm2 of board area per pin Most of the new capabilities are configuration will be downloaded to while the micro fine line turns that thanks to the onboard flash memory. SRAM at the next power-cycle or the spec on its head by packing about The original PALs were fuse-based and download can be triggered immediate- three pins per mm2. For example, com- thus only one-time programmable in a ly with a JTAG command. Another pare the 144-pin TQFP at 484 mm2 production-line setting. By contrast, option is to use an “I/O clamp” fea- with the 144-pin micro fine line BGA the MAX II configuration is repro- ture that sets and locks the pin state at 49 mm2. That’s a factor of 10 higher grammable, even in-system during during reconfiguration. Note that the density! With 144 pins in a package, normal operation. Better yet, the con- CFM is only accessible via JTAG and barely more than 0.25″ on a side, figuration flash memory (CFM) is sup- has a security bit to keep designs safe make sure you bring a magnifying plemented with an additional 8 Kb of from pirates. glass. user flash memory (UFM), which, as The user flash memory can also be The tiny packages are great for your the name implies, is available size-constrained applications. But how for your own application data. Logic array interface Data width Interface type about the unlucky engineer who gets First, let’s discuss the CFM. I2C 8 bits Serial assigned to do the PCB layout? Flashing the MAX II (i.e., pro- SPI 8 or 16 bits Serial Fortunately, Altera offers a detailed gramming the CFM) is accom- app note on doing just that.[2] More plished by feeding the chip a Parallel 3 to 16 bits Parallel layers to work with no doubt make bitstream through dedicated Native (on-chip) 16 bits Serial the job easier, but the app note does JTAG pins. The scheme relies Table 2—The MAX II “user flash memory” (UFM) is a handy show that it is possible to do a layout on a JEDEC Standard Test and option, one made all the handier by utilizing on-chip logic to using just two signal layers (plus power Programming Language implement standard interfaces such as I2C and SPI.

78 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 79

programmed via a JTAG, but it’s acces- sible by the application (i.e., the MAX II R3 MOSFET logic fabric) as well (see Figure 2). The 1K 2xAA native (clock serial) interface is pretty 1 straightforward and the chip handles 3 the gory details of programming sequence and timing. The beauty of programmable logic is D1 R1 MAX IIZ that you get to have it your way. The 1N914 1K Altera tools include IP megafunctions

that front the MAX II UFM with con- Application ventional interfaces (see Table 2). logic . Indeed, the user flash could help the . . MAX II pay for itself if it can elimi- D2 R2 1N914 1K nate the need for a standalone EEP- R ROM chip. Just keep in mind there are 4.4 MHz ~ ÷ 44 M EN CO some operational differences. For PWR instance, a true EEPROM is byte-eras- DWN able while the MAX II UFM is only sector-erasable. And before you get too excited, note the MAX II flash write Figure 3—The built-in oscillator that handles “self-timed” flash operation is also available for use by the application. endurance spec is a mere 100 cycles. In this example, it implements a timer that powers down the MAX II after a period of inactivity, powering up again The MAX II has an on-chip oscilla- when any of the external switches are pressed. tor used for self-timing the flash oper- ations. Altera had the foresight to But at the same time, there appears to pivotal. Once again, the regular MAX II make the oscillator available to the be little power saving advantage spec is high (12 mA) due to the on-chip logic fabric as well. Yes, it’s not espe- gained by choosing “Z” over “G.” It voltage regulator. Jettisoning the regu- cially accurate (runs anywhere from is all the more true considering that lator, the “G” consumes much less 3.3 to 5.5 MHz) and may not be a big the “Z” performance specs (clock rate standby power (2 mA). But as I men- deal in most applications. But in cer- and propagation delay) are quite a bit tioned earlier, every milliamp matters tain situations, an on-chip clock (even derated. in battery-powered designs. Here’s a sloppy one) can prove very useful.[5] Rather, it’s the standby power spec where the “Z” parts shine with a 60× For example, Figure 3 shows an appli- where the difference between the parts is reduction in standby power (less than cation using the oscillator as the clock source for an automatic power-down timer. EPM240

ZERO HERO (1) Altera Zeros Out Power with New 120.00 MAX IIZ CPLDs for Portable 100.00 (2) Applications “The devices…provide both high 80.00 functionality and zero-power con- Typical power 60.00 [6] consumption (mW) sumption in a single device.” (3) We all know that the silicon era has 40.00 (4) been about, pun intended, “Moore for Less.” But it seems to me that 20.00

“Something for Nothing,” as in “zero- 0.00 power consumption,” is pushing it. 0 50 100 150 Take a look at the MAX II dynamic Frequency (MHz) power consumption graph in Figure 4.

Not surprisingly, the regular MAX II (1) VCCINT = 3.3 V chip burns more power due to voltage (2) VCCINT = 2.5 V (3) VCCINT = 1.8 V (MAX IIG) drop from the external supply (e.g., 3.3 (4) VCCINT = 1.8 V (MAX IIZ) or 2.5 V) across the internal 1.8-V reg- ulator. Running directly off a 1.8-V Figure 4—Voltage regulators waste a lot of power, so not surprisingly, the MAX IIG exhibits much lower dynamic external supply, the MAX IIG and IIZ power consumption than the regular MAX II. While the MAX IIZ dynamic power consumption is only slightly less naturally consume a lot less power. than the MAX IIG, the “Z” has a big advantage when it comes to standby power.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 79 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 80

33 µA typical) compared to the “G” I/O and rebooting the configuration scheme raises a variety of “hot sock- version. That’s up to 60× (and 360× when power stabilizes. With the “Z,” et” concerns. Fortunately, the MAX II compared to the regular MAX II) it’s up to you to guarantee that the does a great job in this regard. The longer battery life in applications that power supply meets spec or otherwise chip can be driven before power-up, spend a lot of time in standby. deal with the possibility of the chip which itself can be any sequence There is one caveat worth noting. freaking out if it gets stuck some- (VCCINT and VCCIOs). Pins are tri- The “Z” cuts standby power by elimi- where between “on” and “off.” stated until the power supplies and nating the on-chip voltage monitor Of course, thanks to the “live at internal configuration stabilize. The (which also explains the slightly lower power-up” capability, simply pulling power supply sections of the chip are dynamic power consumption of “Z” the plug would seem a viable power- isolated to prevent current leakage compared to “G”). The voltage moni- management option. However, in a due to activity on the signal pins of a tor protects the MAX II and IIG during multi-chip system where some chips de-powered (i.e., VCCINT, VCCIO = brownout conditions by tri-stating the are powered and some aren’t, that GND) MAX II. Don’t go overboard with cycling the power as a power management strate- gy. Notably, power consumption dur- ing power-up configuration (i.e., copy from flash memory to SRAM) is a whopping 40 to 55 mA for up to 200 to 450 µs depending on the specific part. Thus, you’ll have to consider the duty cycle of your application (i.e., how long the MAX II can remain pow- ered off) relative to the standby power specs of the particular part (microamps for “Z” and milliamps for the others) to decide if and when the power cycling option works best.

FRIENDS There is no doubt that the MAX II is a vast improvement in every way (price, performance, power, and pack- age) over the PALs of yore. But with everything shrinking into fewer chips, does anyone really need “glue logic” anymore? Maybe designers can go it alone and don’t need to bring a PAL along. My take is that there are still appli- cations for chips like the MAX II, but they’ve grown up along with the sili- con. In larger designs, there remain plenty of chores where a friendly help- ing hand is appreciated. The ability of the MAX II to deal with up to four different I/O voltage levels (banks) is a unique capability. Given the combination of high pin count, high density, and low price (starting at $1.25 in volume), the chips would seem a natural for level translation and monitoring in multi- voltage designs. The MAX II is bulked up with ver- satile I/O, but it’s smart too. For instance, say you’ve got a 3.3-V peripheral chip that needs to work

80 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805003-Cantrell.qxp 4/9/2008 9:22 AM Page 81

with a 1.8-V MCU. The MAX II can Embedded Programming using the Portable Applications: Minimizes handle that. But what if the peripheral 8051 & Jam Byte-Code, 2005,” Power, Space and Cost,” Press uses an I2C interface but the MCU has www.altera.com/literature/an/an111. Release, December 10, 2007, a SPI port? The MAX II can handle pdf. www.altera.com/corporate/news_ that too by using the programmable room/releases/releases_archive/2007/ logic to implement an I2C-to-SPI [5] ———, “Application Note 422: products/nr-maxiiz.html. adapter. Power Management in Portable The MAX II on-chip flash memory Systems Using MAX II CPLDs,” is a bonus that shouldn’t be over- 2006, www.altera.com/literature/an SOURCE looked. Together, the “live at power- /an422.pdf. MAX II, MAX IIG, and MAX IIZ up” and “in-system programming” CPLDs features combine to deliver the best of [6] ———, “Altera Zeros Out Power Altera Corp. both the PAL and FPGA worlds. And With New MAX IIZ CPLDs for www.altera.com although not as robust as a true EEP- ROM (i.e., limited write endurance), the flash memory is a handy place to store “once-in-awhile” updates such as configuration and calibration data. The combination of low-power oper- ation and even lower power standby means it finally makes sense to men- tion “programmable logic” and “bat- tery” in the same sentence. The “hot socket” features come into play by allowing the MAX II to deal with whatever happens, and whenever it happens, power-wise. Sure we’ll never forget our old PALs. But now that we’ve met the MAX II, I think you’ll agree it’s time to move on and make some new friends. I

Tom Cantrell has been working on chip, board, and systems design and marketing for several years. You may reach him by e-mail at tom.cantrell@ circuitcellar.com. ProtoMat® S-Series REFERENCES PCB Milling Machines [1] T. Kidder, The Soul of a New Electrical engineers agree: with a Protomat S-Series Machine, Black Bay Books, Boston, prototyping machine at your side, you’ll arrive at the best solutions, fast. These highly accurate benchtop MA, 2000. PCB milling machines eliminate bread-boarding and [2] Altera, Corp., “Application Note allow you to create real, repeatable test circuits— 114: Designing With High-Density including plated vias—in minutes, not days. BGA Packages for Altera Devices,” • Declare your independence from board houses 2007, www.altera.com/literature/ an/an114.pdf. • Affordable, entry-level price tag • The best milling speed, resolution, and accuracy [3] ———, “Chapter 14: Using Jam in the industry STAPL for ISP via an Embedded Processor,” MAX II Device • Single-sided, double-sided, and multilayered machining without hazardous chemicals For complete details visit: Handbook, Volume 1, MII51015- www.lpkfusa.com 1.7, 2007, www.altera.com/literature/ • Optional vacuum table and autosearch camera or call: hb/max2/max2_mii51015.pdf. for layer alignment 1-800-345-LPKF

[4] ———, “Application Note 111:

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 81 82.qxp 4/10/2008 12:44 PM Page 66 2805013 martin.qxp 4/9/2008 9:22 AM Page 83

LESSONS FROM THE TRENCHES by George Martin Making Changes A Look Into The C Compiler Guess what happened after George recently made a few simple changes to a product for a customer and then recompiled the code? Compiler errors! In this column, he describes how he addressed the problem.

For more about C language and writing code, visit George I started commenting out lines of C code that I thought Martin’s blog, CCI C Programming Design Review, at would free up enough memory. No good. The compiler still http://ccidesignreview.wordpress.com/. Code and additional complained that we were out of room. It was time to open files are also available on the Circuit Cellar FTP site. up the lid on the compiler and see what was going on.

COMPILER OUTPUT In previous articles, I talked about and recommended the While I was reading an article recently, the author IAR Systems compiler for the MSP430. It’s free and com- wrote that he was using assembly language so he would piles code up to 4 KB. It’s a solid compiler at the right have more control over the code. I thought this wasn’t true. price. All compilers have the option to produce a listing The C language should give you all of the control over the output that mixes the C source with the assembly language generated code you would ever want. A short while later, a code produced. I went back to the product’s original base- customer asked me to add some changes to a product to try line code and generated listing outputs for each module. out some new features for a new family of applications. I Actually, this is my default method for compiling. I always had recently written all of the code in C, so it should have keep an eye on the compiler’s output to ensure that none of been fresh in my mind. These changes consisted of new my C code is compiling into a large and complicated operating modes that were based on existing modes. Little assembly language mess. did I know that I was about to explore all of the code a I made a copy of the output listing for the keyboard rou- compiler generates in depth. tine. You can find the complete listing on the Circuit Cellar FTP site. I deleted some of the information to protect the OUT OF SPACE customer and the project. This is a long listing and a good The microcontroller in this project is a Texas Instru- candidate to help you understand what the compiler is ments MSP430, which I have written about before. I’m also doing and learn MSP430 assembly language. That isn’t a using one of the simpler (smaller) versions in the family, typo. We can learn a lot about the assembly language by specifically the MSP430F122IPW (http://focus.ti.com/docs/ studying the compiler output. prod/folders/print/msp430f122.html). It is a simple device In the listing file, lines of C code begin with the line with 4 KB of flash memory, 256 bytes of RAM, and several number of the original C file, while lines of generated other peripherals. assembly language begin with the \ character. Remember I made the changes and recompiled the code. What!?! that this is a listing file. It is meant to be read by a human, Compiler errors. The code was too big. How could that be? not necessarily processed further by a machine. After thrashing about for a while, I realized that in a 16-bit Let’s just look at some of the outputs and comment system (MSP430), the 4 KB is 2,048 words of memory about what’s going on. I’ll start with simple operations: space. And those 2,048 words are located from address 0x0000 to 0x07FF. Yes, the compiler was correct. So, I 127 LEDTimer = 0; // Timer = 0 decided to look for a larger device that would plug right \ 0000BC 8243.... MOV.W #0x0, &LEDTimer into the PCB. No luck. All of the MSP430 devices that have a larger memory are in a different package. The 16-bit variable LEDTimer is set to 0. Note that the Because this change to the code was to experimentally assembly language command moves a word of 0 in value evaluate new operating features, I asked the customer if I directly to the address of the variable LEDTimer. One line could remove some of the existing code to make room. The of C, one line of assembly! The .... is the actual memory customer agreed, so I figured it would be rather easy! Not address for LEDTimer and that will be filled in (resolved) at so fast. link time. Also notice that this is a common operation and

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 83 2805013 martin.qxp 4/9/2008 9:22 AM Page 84

it has dedicated operations code for that purpose. Finally, Listing 1—Compiler output for a simple comparison. someone is listening: 119 if (LEDCounter > 99) { 131 ShortBeep(1); // One Short beep \ 00009E B2906400.... CMP.W #0x64, &LEDCounter \ 0000A4 1C39 JL ??RunLEDStates_1 \ 0000CC 5C43 MOV.B #0x1, R12 120 LEDCounter -= 100; // Let it rollover \ 0000CE B012.... CALL #ShortBeep \ 0000A6 B2509CFF.... ADD.W #0xff9c, &LEDCounter \ 0000AC 3041 RET 121 } The routine ShortBeep is called and passed a parameter value of 1. The assembly language instructions load a 16-bit variable into R12 (register 12) and call the ShortBeep rou- Listing 2—Compiler output for setting several variables.

tine. In the IAR implementation, C parameters are passed 225 SSTimer = 0; // Reset this timer using the registers if there are enough registers. If there are \ 00023E 8243.... MOV.W #0x0, &SSTimer not enough free registers, the parameters are passed using 226 LEDTimer = 0; // Timer = 0 \ 000242 8243.... MOV.W #0x0, &LEDTimer the stack. Depending on the compiler design and the CPU 227 LEDCounter = 0; // Counter = 0 design, this can be a source for slow performance. Imagine \ 000246 8243.... MOV.W #0x0, &LEDCounter 20 parameters to pass to a routine. If I have more than four 228 BeepTimer = 0; // Start from 0; \ 00024A C243.... MOV.B #0x0, &BeepTimer parameters, I make up a structure, save the parameters in 229 BeepTimerCounter = 0; // Start from 0; the structure, and pass a pointer to that structure in the \ 00024E C243.... MOV.B #0x0, &BeepTimerCounter call to a routine. You might say, “Just make all of the parameters global and then there is no need for passing anything.” Well, this works for smaller designs and is the and compiler take to perform this function? What’s the same solution for C or assembly, but it’s just not practical best form of C code to do the job? Can assembly language for larger projects. do it any better? This is a trivial example, but you can imagine a more complicated example that would help you COMPARISONS evaluate microcontrollers and compilers: The C code in Listing 1 is comparing the LEDCounter variable to the value 99. If the variable is larger, then the 233 FanOnOff(ESC_ON); following section of code enclosed in the {} brackets is \ 000262 5C43 MOV.B #0x1, R12 executed. The assembly code compares the 16-bit variable \ 000264 B012.... CALL #FanOnOff located at the address of LEDCounter with the value of 0x64 (100 decimals) and then the JL instruction is execut- Here’s how I turn a fan on and off. I have a routine that ed. I bet the JL instruction is defined as jump if the com- parison results evaluated to “less than.” And the jump des- Listing 3—Compiler output for a more involved comparison. tination bypasses the C code inside the {} brackets. The comparison feature alone is enough of a reason to use C. 479 if (++TriggerSwitchState > ESC_STATE_ACTIVE) { \ 00001A 1F42.... MOV.W &TriggerSwitchState, R15 Every microcontroller has different compare instructions, \ 00001E 1F53 ADD.W #0x1, R15 different flag meanings, and different jump instructions. I \ 000020 824F.... MOV.W R15, &TriggerSwitchState don’t want to spend another minute of my time reading \ 000024 3F906302 CMP.W #0x263, R15 \ 000028 1F38 JL ??OperateKbStates_1 manuals and trying to figure it all out. And neither should you. I didn’t mention that you also need to consider whether the variable is 8, 16, or 32 bits and signed or Listing 4—Compiler output for a simple switch statement. unsigned. OK. I’ll move on. But I hope you got the point. 335 switch (OperMode) { Before we do, notice on line 120 in Listing 1 that adding \ 000006 5E42.... MOV.B &OperMode, R14 \ 00000A 6E83 SUB.B #0x2, R14 0xff9C is the equivalent of subtracting 100. Well, 0xff9C is \ 00000C 0624 JEQ ??IncreaseOperTime_0 16 bit 2’s compliment notation for –100, and LEDCounter is \ 00000E 5E83 SUB.B #0x1, R14 a 16-bit signed variable (see Listing 2). C rocks! \ 000010 0424 JEQ ??IncreaseOperTime_0 \ 000012 5E83 SUB.B #0x1, R14 \ 000014 0224 JEQ ??IncreaseOperTime_0 STATEMENTS & ROUTINES \ 000016 5E83 SUB.B #0x1, R14 Listing 2 shows five C statements that do the same oper- \ 000018 0920 JNE ??IncreaseOperTime_1 336 case MODE_CONT: { ation of zeroing a variable. Notice that some of the vari- 337 // Do nothing ables are 16-bit and some are only 8-bit entities. What if we 338 } break; wrote them as follows: 339 340 case MODE_SOFT_ST: 341 case MODE_HIGH: SSTimer = LEDTimer = LEDCounter = BeepTimer = 342 case MODE_LOW: BeepTimerCounter = 0; 343 case MODE_PULSE: 344 OperTime++; \ ??IncreaseOperTime_0: The IAR compiler and MSP430 did the operation in 20 bytes \ 00001A 9253.... ADD.W #0x1, &OperTime of code. How much code would your favorite microcontroller

84 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805013 martin.qxp 4/9/2008 9:22 AM Page 85

Listing 5—A set of defines to establish simple, consecutive state values. is passed a parameter. If the parameter is equal to on, I turn the fan on and likewise for off. If, however, I have a #define MODE_CONT 1 // Continuous #define MODE_SOFT_ST 2 // SoftStart routine for FanOn and another for FanOff, then there #define MODE_HIGH 3 // High would be no need for parameter passing. And one less word #define MODE_LOW 4 // Low for every time I call those functions. It is probably a good #define MODE_PULSE 5 // Pulse thing to do on this project because I’m cramped for space. And it’s an easy change: Listing 6—Complier output for a more involved switch statement. 239 SSTimer++; 86 switch (LED_State) { \ 000000 1F42.... MOV.W&LED_State, R15 \ 000272 9253.... ADD.W #0x1, &SSTimer \ 000004 3F900E00 CMP.W #0xe, R15 \ 000008 112C JC ??RunLEDStates_0 This code fragment increments a 16-bit variable named \ 00000A 0F5F ADD.W R15, R15 \ 00000C 104F.... BR `?_0`(R15) SSTimer. What if I had written SSTimer = SSTimer +1;? \ `?_0`: Would the compiler load the variable into a register, incre- \ 000010 .... DC16 ??RunLEDStates_0 ment it, and then save that variable? \ 000012 .... DC16 ??RunLEDStates_9 \ 000014 .... DC16 ??RunLEDStates_10 The code generated in Listing 3 loads the 16-bit variable \ 000016 .... DC16 ??RunLEDStates_11 into R15, adds 1 to it, saves that variable, and then uses \ 000018 .... DC16 ??RunLEDStates_12 \ 00001A .... DC16 ??RunLEDStates_13 the copy in R15 for the comparison. Is there a better way? \ 00001C .... DC16 ??RunLEDStates_14 What about this: \ 00001E .... DC16 ??RunLEDStates_15 \ 000020 .... DC16 ??RunLEDStates_16 \ 000022 .... DC16 ??RunLEDStates_17 TriggerSwitchState++; \ 000024 .... DC16 ??RunLEDStates_18 if (TriggerSwitchState > ESC_STATE_ACTIVE) { \ 000026 .... DC16 ??RunLEDStates_19 \ 000028 .... DC16 ??RunLEDStates_20 \ 00002A .... DC16 ??RunLEDStates_21 That would produce the following: 87 default: { 88 LED_State = LED_ST_OFF; \ ??RunLEDStates_0: \ 00001A 9253.... ADD.W #0x1, &TriggerSwitchState \ 00001E B2906302.... CMP.W #0x263, &TriggerSwitchState \ 000024 1F38 JL ??OperateKbStates_1

Listing 7—A set of defines to establish simple but non-consecutive state values. The code size went from eight words to six words, saving #define LED_ST_OFF 1 two words. That is not a lot, but if this type of comparison #define LED_ST_CO_START 2 #define LED_ST_CO_RUN 3 is done frequently, then three words could be saved every #define LED_ST_HI_START 4 time. #define LED_ST_HI_RUN 5 #define LED_ST_LO_START 6 #define LED_ST_LO_RUN 7 SWITCH STATEMENTS #define LED_ST_SS_START 8 Probably the most important concept to take away from #define LED_ST_SS_RAMP 9 #define LED_ST_SS_RUN 10 what we’ve covered so far is that you need to get to know #define LED_ST_PU_START 11 your compiler and microcontroller so you can write C #define LED_ST_PU_HI 12 #define LED_ST_PU_LO 13 statements that will maximize performance. Another area to investigate is how switch statements are handled (see Listing 4). The switch statement jumps to different locations depend- Listing 8—Compiler output for setting a value into an array of structures. ing on the value of OperMode. Note that OperMode’s defined 120 DispQue[LCDQueInPtr].Type = nType; values are listed in Listing 5. If the mode is CONT or a non- \ 000000 5F42.... MOV.B &LCDQueInPtr, R15 \ 000004 8F11 SXT R15 defined mode, nothing is done. If the mode is SoftStart, \ 000006 0F5F RLA.W R15 High, Low, or Pulse, then a timer is incremented. \ 000008 0F5F RLA.W R15 Notice what the compiler generated. The 8-bit variable \ 00000A CF4C.... MOV.B R12, DispQue(R15) OperMode is copied into R14. Then the value 2 is subtract- ed. If the result is 0, then the decrementing path is taken. Listing 9—Compiler output for a comparison including arrays and logic statements. It would be 0 if the OperMode was SoftStart. Look at the other tests the control portion takes to figure out 171 if ((LastLine2Dig[0] != 'B') || which value OperMode was set to. All of that work is done 172 (LastLine2Dig[1] != 'a')) \ ??UpdateLCD_2: in 10 word locations. Also consider the switch statement \ 000046 F2904200.... CMP.B #0x42, &LastLine2Dig at line 399 of the listing file on the Circuit Cellar FTP site. \ 00004C 0420 JNE ??UpdateLCD_3 The case statements are different and slightly different \ 00004E F2906100.... CMP.B #0x61, &LastLine2Dig + 1 \ 000054 ED24 JEQ ??UpdateLCD_4 code is generated. Another complicated switch statement is shown in Listing 6. It is close to the others but different enough to produce

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 85 2805013 martin.qxp 4/9/2008 9:22 AM Page 86

significantly different code. A jump table is produced in Listing 10—Compiler output for the entrance of the UpdateLCD routine. this switch statement. The possible states for LED_State are in Listing 7. 157 void UpdateLCD(void) { \ UpdateLCD: Note that all of the states are in numerical order with no \ 000000 2183 SUB.W #0x2, SP missing states. I made it easy for the compiler to build and use 158 NT8 Digit[2]; a jump table. What if there were missing states? Well, the 221 Digit[0] = Digit[1] = DDC_BLANK_DIGIT; table could be built with the default state inserted for those \ 00017A 7E402000 MOV.B #0x20, R14 missing entries. What if we used a switch statement and we \ 00017E C14E0100 MOV.B R14, 0x1(SP) were switching on a small list of ASCII values? Good question. \ 000182 C14E0000 MOV.B R14, 0x0(SP) Why not put that into your C compiler and microcontroller and see what happens? Not all microcontrollers and compilers Listing 11—Compiler output for a control loop. are created equal. With IAR, you are looking at over 20 years 67 for (i = 0; i < MAX_BEEPS; i++) { of compiler design experience. And with Texas Instruments, \ 00000A 4E43 MOV.B #0x0, R14 I’ve seen their CPUs evolve over the past 30 years. So, in all \ 00000C 073C JMP ??InitBeeperQue_1 68 BeepQue[i].Type = 0; fairness, don’t compare an 8031 or a 6800 to a modern CPU. \ ??InitBeeperQue_0: \ 00000E 4F4E MOV.B R14, R15 ARRAYS \ 000010 8F11 SXT R15 \ 000012 0F5F RLA.W R15 The examples in Listing 8 are not found in the listing \ 000014 0F5F RLA.W R15 posted on the Circuit Cellar FTP site. Arrays are another \ 000016 8F43.... MOV.W #0x0, BeepQue(R15) area to investigate. 69 } \ 00001A 5E53 ADD.B #0x1, R14 DispQue is an array of a structure, and one element in that \ ??InitBeeperQue_1: structure is Type. The C code is saving the local variable \ 00001C 7E900500 CMP.B #0x5, R14 nType (new Type) in the array. So, first the 8-bit variable \ 000020 F63B JL ??InitBeeperQue_0 LCDQueInPtr is loaded into R15, and then that variable is converted to a 16-bit entity by extending the sign. So, 0xFF would become 0xFFFF and 0x01 would become 0x0001. If I the test to see if i is less than MAX_BEEPS. If not, control had defined LCDQueInPtr as an unsigned type, the sign exten- flows to the ??InitBeeperQue_0 location. Notice that sion operation would not be required. Next, R15 is shifted to because i is an 8-bit variable, the SXT instruction is the left once and then once again. This is a left shift by two or required. If I were looking for speed, I would have made i a a multiplication by four. And four is the size, in bytes, of the 16-bit variable and then I would not need to execute that structure. So if LCDQueInPtr were pointing to the 0th element, SXT instruction. The more RAM is used, the less code is then R15 would hold 0x0000. If it were pointing to the fifth used. Isn’t that always the case? element, then R15 would hold 5 × 4 = 20 = 0x0014. The Well, we just scratched the surface of compiler output. I last step is to save the variable in R12 (the new Type) to used the listing outputs to find large areas of code that the DispQue array offset by the contents of R15. This is a could be deleted to make room for the new features. The bit of insight on how arrays and structures compile to customer got his unit on time. Remember we’ve got a code assembly language. Rather slick I must say. review going on from last time. Next time, I’ll talk about Listing 9 is an example of an array operation. The com- an off-grid solar home I recently completed. I piler knows all there is to know about the memory loca- George Martin ([email protected]) began his career tion of LastLine2Dig[0]. It’s at a specific address as is in the aerospace industry in 1969. After five years at a real LastLine2Dig[1]. So the compiler just uses those job, he set out on his own and co-founded a design and addresses. manufacturing firm (www.embeddeddesigner.com). His SAVING SPACE designs typically include servo-motion control, graphical input and output, data acquisition, and remote control Again, if we know the address of an array element, we systems. George is a charter member of the Ciarcia Design get the code in Listing 10. Space is saved for the 8-bit local Works Team. He’s currently working on a mobile commu- (temporary) variables Digit[0] and Digit[1] on the nications system that announces highway info. He is a stack. When the routine is terminated, the contents of this nationally ranked revolver shooter. variable are lost. Because the compiler knows the location of the variable, it’s rather straightforward to save new val- PROJECT FILES ues in that variable. Another example of arrays of structures and for(;;) To download code, go to ftp://ftp.circuit cellar.com/pub/Circuit loops is in Listing 11. In the code, i is a local 8-bit variable _Cellar/2008/214. on the stack. We are attempting to set all the BeepQue[].Type locations to 0. SOURCE Notice the ??InitBeeperQue_0: and ??InitBeeperQue_1: MSP430F122IPW Microcontroller labels. The compiler generated them for destinations of Texas Instruments, Inc. jump instructions. The ??InitBeeperQue_1: location is www.ti.com

86 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-214.qxp 4/9/2008 9:52 AM Page 87 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

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

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

® ARM® 8051 UUSSBB phyCORE® OEMable Single Board Computers ® Add USB to your next XScale: PXA270, PXA255 COLDFIRE project—it’s easier than you ARM: LPC3180 (ARM9); LPC22xx, LPC229x, AT91 (ARM7)

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

www.crossware.com PHYTEC America, LLC I 203 Parfitt Way SW, G100 I Bainbridge Island, WA 98110 USA Tools for Embedded Development Tools CROSSW 360-812-2397 www.phytec.com I (800) 278-9913 I www.phycore.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 87 ib-214.qxp 4/11/2008 5:07 PM Page 88

Hundreds of complete embedded projects.

Start with www.circuitcellar.com/

CC-ad-March-mx.pdf 3/6/08 2:31:36 PM microchip2007

Bargain LCD Scopes! Portable, benchtop 25Mhz 100MS/s 22 2-ch color LCD Scope. Download S50 PD waveforms via USB1.1 to PC. 7.8" 640 x 480 Color LCD 3.5lbs. Volt/Time Automatic Measurement Peak-to-peak Value, Average, RMS, Frequency and Cycle. FREE 1x/10x probes, USB cable. Compare with expensive LCD scopes! PDS5022S $325! 25MHz 100MS/s 2/16ch scope/logic- 022 analyzer 5ns-5s/div with complex O5 MS triggering. 7.8” TFT Color LCD. USB- connected. 4MS buffer. Triggering: Auto/Normal/ Single/Edge/Video/Alt. 16-ch logic analyzer pre-/mid-/re- triggers: bus/state signature, data width + data search. See signals or data on same space-saving instrument! MSO5022 SALE! $799 $899

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

88 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-214.qxp 4/9/2008 10:05 AM Page 89

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

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 89 ib-214.qxp 4/9/2008 10:05 AM Page 90

90 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-214.qxp 4/9/2008 10:05 AM Page 91

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

www.schmartboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 91 ib-214.qxp 4/9/2008 10:05 AM Page 92

92 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 4/14/2008 4:31 PM Page 93

CROSSWORD

1 23

4

5

6

78

9 10

11

12

13 14

15 16

17

18

Across Down 4. To align text with both margins 1. Starlike energy producer 6. Remove magnetism 2. A display on electronic systems 9. A popular network that enables its 3. An instrument for indicating and recording electrical quantities (e.g., users to share software peer-to-peer current and voltage) 11. Program used to download podcasts 5. Episode on a web site 12. C++ filename extension 7. The NASA space shuttle built in 1989 to replace the Challenger 15. 8. .BAT 17. Undisclosed app access 10. Icon for quick access 18. The opposite of apogee 11. Private phone network 13. The British author (b. 1917) who wrote 2001: A Space Odyssey, was knighted in 1998, and died in March 2008 14. A tool that stifles voltage transients 16. Demonstration sample The answers are available at www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 214 May 2008 93 94-advertiser's index.qxp 4/11/2008 10:57 AM Page 94

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

Page Page Page Page 91 AAG Electronica, LLC 87 FDI-Future Designs, Inc. 13 Matrix Orbital 88 Saelig Co.

8 AP Circuits 92 FlexiPanel Ltd. 89 MaxBotix, Inc. 91 Schmartboard

18, 19 All American Semiconductor, Inc. 92 FlyPCB China Co., Ltd. 90, 91 Micro Digital, Inc. 11 SEGGER Microcontroller Systems LLC

92 All Electronics Corp. 9 Front Panel Express LLC 55 Microchip 58 Sensors Expo & Conf.

27 Altium Limited 45 Grid Connect, Inc. 92 microEngineering Labs, Inc. 25 Silicon Laboratories, Inc.

88 Apex Embedded Systems 88 Hagstrom Electronics 63 Mouser Electronics 23 Spark Fun Electronics

7 Atmel 89 HI-TECH Software LLC 88 Mylydia, Inc. 1 Sunstone Circuits

50 Bitscope Designs 72 HobbyLab LLC 87 NKC Electronics 91 Systronix

65 CWAV 2 IMAGEcraft C2 NetBurner 92 TAL Technologies

80 CadSoft Computer, Inc. 91 Intec Automation, Inc. 3 Noritake Co., Inc. C3 Tech Tools

56 Comfile Technology, Inc. 91 Ironwood Electronics 75 Nurve Networks LLC 28, 29 Technologic Systems

87 Crossware Products, Inc. 64, 91 JKmicrosystems, Inc. 21 PCB-Pool 90 Technological Arts

92 Custom Computer Services, Inc. 48 Jameco C4 Parallax, Inc. 89 Tern, Inc.

87 DLP Design 75 Jeffrey Kerr LLC 87 Phytec America LLC 49 Tibbo Technology, Inc.

72 Decade Engineering 40 Keil Software 87 Picofab, Inc. 89 Tin Can Tools, LLC

72 Designnotes 81 LPFK Laser & Electronics 92 Pioneer Hill Software 90 Trace Systems, Inc.

66 Display Week 75 Lakeview Research 73 Pololu Corp. 90 Triangle Research Int’l, Inc.

45 EMAC, Inc. 88 Lawicel AB 91 Pulsar, Inc. 47 Wiznet

89 Earth Computer Technologies 15 Lemos International 8, 89 Rabbit, A Digi International Brand 90 Zanthic Technologies, Inc.

57 Embedded Developer 9 Linx Technologies 95 Rabbit, A Digi International Brand

39 ExpressPCB 88 Loadstar Sensors, Inc. 89 Reach Technology, Inc. nd 15 ezPCB 89 MCC (Micro Computer Control) 5 Renesas Technology n Preview of June Issue 215 ATTENTION ADVERTISERS Theme: Communications July Issue 216 Targets Message Acquisition: Ring Signal Detection And Interpretation Deadlines

Pump Control: Build A Variable Speed Induction Motor Controller Space Close: May 12 Material Close: May 23 Sound Effects Processing

FPGA Ray Tracer Theme: THE DARKER SIDE Let’s Be Crystal Clear Internet & Connectivity ABOVE THE GROUND PLANE Resistance Soldering Call Shannon Barraclough FROM THE BENCH Self-Destructive Behavior: Processor Action Requires Power now to reserve your space! Supply Removal 860.875.2199 e-mail: [email protected] SILICON UPDATE Touch Me: An Exploration Of New Touch Sensors

94 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com 73.qxp 12/4/2007 11:49 AM Page 1

CC_RCM4300_Jan_FP_08019.indd 1 11/29/07 4:04:43 PM steve_edit_214_v1.qxp 4/11/2008 10:52 AM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director Who Said Variety Is Good?

When English poet William Cowper wrote, “Variety’s the very spice of life/That gives it all its flavor,” he certainly wasn’t trying to buy a com- puter! I’m an engineer familiar with the technology and the players, but I have to admit that after four days of intense research on selecting a new computer, it is one of the ultimate frustrations in life. In fact, I think the less you know, the better. Sanity prevails only for those people blissfully ignorant enough to walk into a Circuit City or Best Buy and purchase a computer strictly based on the color of the case. Choices have always been part of the computer buying process, but in the past, they seemed to have been more limited and logical. Five years ago, when I bought my 17″ WXGA Toshiba laptop, the choice was P4 and nothing.Yes, there might have been a couple of different clock speeds to choose from, but options were all about peripheral choices rather than the elemental ingredients of the processor architecture. Given the range of CPU choices and software at that time, even a naive purchaser usually couldn’t screw it up even if they did select by case color only. Today, the preponderance of bloatware powered by processors that can range in performance from a turtle to an Indy racecar brings the process of choosing a new computer to a whole new dimension of price and performance issues. Today we no longer have just a few versions of the P4 and whatever generation Athlon. Instead, we have so many Intel processors that you need a road map: Celeron, Pentium D, Pentium Dual- Core, Pentium Duo, Pentium Core 2 Duo, Pentium Core 2 Quad, Pentium Core 2 Extreme, etc., etc. AMD is just as bad with Semipron, Athlon X2, Athlon 64, Athlon X2, etc., etc. To confuse things further, Intel and AMD use names like Conroe, Penryn, Santa Rosa, Windsor, and Agena to describe technologies we’re all supposed to care about too. Arrrgh! Ultimately, I had to come to grips with the fact that whether we like it or not Microsoft controls the planet. Even though I intend to continue using XP Pro for as long as possible, I will eventually be forced to switch to Vista. Because my new computer has to run Vista at some point, it is essential that I know the relative performance of the 100 or more Intel and AMD processors so I know if I will have enough horsepower when I do switch. For example, is the X7900 in a Dell laptop faster than a T7700 in an ASUS? A little bit of research led me to www.cpubenchmark.net. I rec- ognize that there are dozens of benchmark tests, but this site has some really great graphs comparing hundreds of processors. The PassMark scores provide a relative comparison between computers that I wouldn’t otherwise have. As a baseline, I started by checking my 2.4-GHz P4 17″ Toshiba I was replacing. It scored a 354. By comparison, the Dell with an X7900 is 1,518, and the ASUS with a T7700 is 1,284. Obviously, how much of this horsepower you get to use depends on the speed of the peripherals attached to the processor and the efficien- cy of the software. Both Vista and XP Pro can use multi-core processors as long as they are executing multi-threaded software. OK, I know that probably none of the software I presently use benefits from dual cores, but the immediate benefit of using XP on a new platform (albeit even at the same processor clock speed) is that it should run a lot faster simply because the RAM, disk access, CPU caches, and graphics processing are a whole lot faster on a new system. When it comes to making a final choice on a laptop, I have to admit that I’m my own worst enemy. I know too much about the good and bad points of all this stuff and it just complicates alternatives. In the end, the only rational solution for me is to approach this the same way I typically solve everything else—complete overkill. The requirement to install XP Pro instead of Vista eliminated all of the usual consumer brands and left me in the world of “gaming computers” where they are used to customized solutions. I toyed with the idea of an Apple laptop but even that wasn’t enough. After a bit more research, I found the biggest and baddest laptop at XoticPC.com where I ordered a Sager NP9262. It has a Q6600 Core 2 Quad processor (2.4-GHz 8-MB L2 Cache—1,066 FSB), 4-GB DDR2 800 dual-channel memory, 2× 160-GB 7,200-rpm SATA-II 300 HDD, an nVidia GeForce 8800 GTX 512-MB video card, and XP Pro! For reference, the PassMark score on the Q6600 is 2,711, not bad for a laptop and still plenty of gas for dealing with Vista or, heaven forbid, a computer game. Ultimately, the alternatives among XP, Vista, and processor selection end up being the way I buy cars. Like single-thread soft- ware limits the Q6600’s potential, the Connecticut state police pretty much define my driving style. However, plug in some multi-threaded software and give me a German autobahn and you’d better move out of the way.

Read Steve’s follow-up comments at www.circuitcellar.com/archives/priorityinterrupt/214.html.

[email protected]

96 Issue 214 May 2008 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 3/30/2007 1:38 PM Page 1 C4.qxp 4/10/2008 9:27 AM Page 1