cover1.qxp 11/2/2006 9:13 AM Page 1

#197 December 2006 w w w . i r c u i t c

e CIRCUIT® l l a r . c o m

CELLARTHE MAGAZINE FOR COMPUTER APPLICATIONS ANALOG TECHNIQUES Analog Oscilloscope Companion Digital Instrument Panel Design Build a Modular Security System PortableWWW.GiURUMELE.Hi2.RO Lightning Detection

12>

7925274 75349 $4.95 U.S. ($5.95 Canada) C2.qxp 11/1/2006 10:32 AM Page 1

WWW.GiURUMELE.Hi2.RO 1.qxp 9/5/2006 2:33 PM Page 1

WWW.GiURUMELE.Hi2.RO 39.qxp 10/2/2006 8:41 AM Page 1

CONTROL MADE EASY

Need to monitor or control the small sensors and actuators in your control network? Or make your machine more reliable, easy to assemble and remotely accessed? Use the Pyxos™ platform, the embedded control networking solution that installs with push-button simplicity. Pyxos chips are small enough for nearly any sensor or actuator, and includes a digital I/O and SPI port to use with existing . It extends the power of LONWORKS® control networks to the smallest of devices, plays well with others—host proces- sors and PLCs—and has the development tools and reference designs to reduce your development time.

 Deterministic TDMA protocol  Bit rate: 312.5kbps  Scan time for 32 devices: <25ms  Wire type: 16AWG (1.3mm) to 24AWG cat5 (0.5mm)  24VAC or DC power and data on two wires  Application power delivered to each device: [email protected]  Built-in unique MAC ID  Plug-and-play or preconfigured self-installation WWW.GiURUMELE.Hi2.RO 20MLF (5mm x 5mm) RoHS-compliant IC package

Discover the technology that millions of devices worldwide already use. Call 1 - 408 - 938 - 5200 or visit us online at www.echelon.com/easycontrol.

© 2006 Echelon. Echelon, LONWORKS, and the Echelon logo are registered trademarks of Echelon Corporation registered in the United States and other countries. Pyxos is a trademark of Echelon Corporation. 3.qxp 8/14/2006 11:04 AM Page 1

WWW.GiURUMELE.Hi2.RO 197_masthead.qxp 11/2/2006 9:16 AM Page 4

TASK MANAGER

st The 21 -Century Designer FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia He’s a 29-year-old hardware designer tweaking a snippet of code as he MANAGING EDITOR MEDIA CONSULTANT waits for a bus in downtown Bangalore. She’s a 38-year-old conservationist C.J. Abate Dan Rodrigues sitting at a Tokyo sushi bar and editing a hardcopy of a low-power lighting WEST COAST EDITOR CUSTOMER SERVICE system. He’s a 30-year-old, London-based professor listening to Thom Yorke Tom Cantrell Debbie Lavoie on his MP3 player while soldering a new circuit. He’s a 65-year-old retiree fin- CONTRIBUTING EDITORS CONTROLLER Jeff Bachiochi Jeff Yanco gering through the part bins at a Radio Shack in Palo Alto while his grand- Ingo Cyliax son toys with a new satellite radio receiver in the front of the store. Fred Eady ART DIRECTOR KC Prescott What do all of these seemingly different people have in common? They’re George Martin Ed Nisley all contemporary embedded designers, and they’re all part of the Circuit GRAPHIC DESIGNER Mary Turek Cellar community. NEW PRODUCTS EDITOR John Gorsky Since the initial development of the silicon chip, the face, habits, and work STAFF ENGINEER John Gorsky ethic of the embedded engineer have changed. The community is no longer PROJECT EDITORS Steve Bedford populated by a select group of middle-class, culturally homogenous, univer- Ken Davidson sity-trained, predominantly male, electrical engineers. Today, young coders David Tweed are branching out into the field of embedded design, and retired hardware designers are starting second careers as software gurus who blog about code languages in their spare time. This trend knows no borders. It’s hap- pening in North America, Europe, and beyond. ADVERTISING This excites us. Not only does it make for a more diverse magazine that 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise features compelling articles written by an interesting group of designers, but PUBLISHER it also bodes well for the future of our increasingly interconnected global com- Sean Donnelly munity. Can anyone deny that we’re on the verge of some major break- Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] throughs in the fields of microcomputing, wireless communication, and robot- ADVERTISING REPRESENTATIVE Shannon Barraclough ics design? Picture thousands of enthusiastic designers from culturally Direct: 860.872.3064, E-mail: [email protected] diverse backgrounds developing the groundbreaking technologies of tomor- ADVERTISING COORDINATOR row. If that’s not exciting, I don’t know what is. Valerie Luster Nowhere are the skills of contemporary embedded designers displayed E-mail: [email protected] more prominently than in our magazine and on our web site. Read through our articles and study the hundreds of designs posted on our various con- Cover photography by Chris Rakoczy—Rakoczy Photography test sites. If after doing so you come to only one conclusion, it should be www.rakoczyphoto.com this: there’s a heck of a lot of high-level designing going on. PRINTED IN THE UNITED STATES Circuit Cellar magazine is always a great place to start your search for CONTACTS information about new projects. This month, Greg Cloutier describes how he SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] a built a handy analog oscilloscope companion (p. 14). The LPC2138-based Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, system ensures the precise calibration of his oscilloscope. Hanover, NH 03755-5650 Address Changes/Problems: E-mail: [email protected] On page 22, Samir Lohani walks you through the process of designing a GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] digital instrument panel for a diesel engine. The system enables you to view Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] essential engine-related data on your PC or any portable Bluetooth-enabled New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION system. 860.875.2199, E-mail: [email protected] Do you want to know what it takes to build a modular security system? Take AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article. a look at the PIC18F4580-based multitiered design developed by the team of Camosun College students on page 32. It’s an innovative upgrade for any basic WWW.GiURUMELE.Hi2.ROCIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar home or office monitoring system. 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- I know that after reading this issue you’ll still be hungry for more, so you 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 should also check out the amazing systems developed by the winners of the and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call Atmel AVR 2006 design contest (www.circuitcellar.com/avr2006/). It’s won- 800.269.6301. derful to see the wide variety of cutting-edge systems from such a diverse Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. group of designers. 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 Do you have what it takes to design, build, and run a system? If you’re from plans, descriptions, or information published by Circuit Cellar®. looking to put your skills to the test, check out our newest contest sponsored 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. by Luminary Micro (www.circuitcellar.com/designstellaris2006/). The reader assumes any risk of infringement liability for constructing or operating such devices. Entire contents copyright © 2006 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 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 5.qxp 10/26/2006 11:22 AM Page 1

PC Oscilloscopes & Analyzers

DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

DSO 2.0

4 Channel BitScope 2 Channel BitScope Pocket Analyzer

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

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

Networking Flexible network connectivity supporting  multi-scope operation, remote monitoring and data acquisition. Data Export Export data with DSO using portable CSV files or www.bitscope.com  use libraries to build custom BitScope solutions. 197_toc.qxp 11/2/2006 9:17 AM Page 6

December 2006: Analog Techniques FEATURES

14 ARM Scope 44 Visual Basic 2005 and the Serial Port Build an Analog Oscilloscope Companion Aubrey Kagan Greg Cloutier 54 Third Overtone Crystal Clock Oscillator 22 Digital Instrument Panel Alan Bate A Simple Panel for Diesel Engines Samir Lohani

32 Multitiered Security System Kyle Cameron, Jeremy Warren, Shane Reierson, Chris Rittaler, & Nick Brady

Analog Oscilloscope Companion (p. 14) Simple Digital Panel (p. 22) Multitiered Security (p. 32 )

COLUMNS

38 ABOVE THE GROUND PLANE Filter Figures Ed Nisley Ethernet Development (p. 66) Lightning Detector (p. 74) 66 APPLIED PCs Ethernet on a Chip Fred Eady Etherne

74 FROM THE BENCH Portable Lightning Detector Jeff Bachiochi

80 SILICON UPDATE Ferro-51 Tom Cantrell DEPARTMENTSWWW.GiURUMELE.Hi2.RO

4 TASK MANAGER 94 INDEX OF ADVERTISERS The 21st-Century Designer January Preview C.J. Abate 96 PRIORITY INTERRUPT 8 NEW PRODUCT NEWS Going for the Brass Ring edited by John Gorsky Steve Ciarcia 93 CROSSWORD

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

Dream of Darkness, Wasteman!

WWW.GiURUMELE.Hi2.RO

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

NEW PRODUCT NEWS Edited by John Gorsky LOW-COST DEVELOPMENT TOOL FOR AVR MCUs The AVR Dragon is a new low-cost development tool for USB cable and can also source an external target with up AVR microcontrollers. By providing a complete on-chip to 300 mA for programming or debugging. If the target is debugging and for more than 30 differ- already powered by an external power source, the AVR ent AVR flash memory microcontrollers, the AVR Dragon Dragon will adapt and level convert all signals between the is the industry’s most comprehensive low-cost develop- target and the AVR Dragon. ment tool. The AVR Dragon uses the free Atmel AVR Studio IDE. The AVR Dragon supports all programming modes for AVR Studio—which includes a simulator, assembler, and C all AVR microcontrollers and on- —is the software front end chip debugging for AVR microcon- for all Atmel AVR debugging and trollers with up to 32 KB of flash programming tools. A flexible and program memory. At just a fraction secure firmware upgrade feature of the price usually required for allows AVR Studio to easily such a full-featured tool, the AVR upgrade the AVR Dragon to sup- Dragon will fulfill all of your pro- port new devices for free. gramming and debugging needs. The AVR Dragon is available The AVR Dragon can be used with from all of Atmel’s franchised dis- an external target board as well as tributors at a suggested retail price an onboard prototype area, allowing of $49. programming and debugging with- out any additional hardware. Atmel Corp. The AVR Dragon is powered by a www.atmel.com

OP-AMP OFFERS LOW NOISE OVER A WIDE 4-mm LINEAR SERVOMOTOR VOLTAGE RANGE The 4-mm Linear Shaft Motor is Nippon Pulse Ameri- The AD8599 dual op-amp is designed for medical, ca’s smallest linear servomotor. The 4-mm shaft diame- instrumentation, automated test equipment, and other ter, a small forcer size (10 mm × 10 mm), a total weight industrial applications that require low noise without sac- of 9 g, and strokes as long as 40 mm make the motor a rificing precision. The AD8599 is the industry’s only dual suitable replacement in piezo-type applications. op-amp to specify 1-nV/rootHz voltage noise at 1 kHz over a wide operating voltage range up to 36 V. It lowers voltage noise by 80% as compared to standard amplifiers. The low noise and small footprint make the AD8599 easy to use. It is ideal for closed loop gain, error amplifier configurations and transimpedance applications, such as microphone preamps, buffers for precision DACs, and photodiode amplifiers. The AD8599 comes in an eight- lead SOIC package, reducing board space requirements. It also reduces the cost of external components by including a compensation capacitor for unity gain stability. The op-amp is designed using the proprietary iPolar The 4-mm motor is quiet due to the absence of friction high-voltage process technology, which provides best-in- because the only mechanical contact section is the linear class precision and gain stability. The device also offers guide. Its coreless construction totally eliminates cog- 3.5-pA/rootHz current ging. The motor’s high motor stiffness allows it to be noise and less than used in high-precision positioning applications where a 0.001% distortion, both resolution of 0.09 nm is achievable. With the Linear Shaft of which are required to Motor, you will find that you have virtually no fluctua- maintain theWWW.GiURUMELE.Hi2.RO highest tion in speed. Durable construction makes it possible to levels of precision for operate the Linear Shaft Motor in harsh conditions, circuits that require high including a vacuum situation and underwater. Compared closed-loop gain and sta- to other linear motors on the market, it is compact and bility. lightweight. Due to its design, the Linear Shaft Motor has The AD8599 costs no backlash. $4.25 in 1,000-piece The S040D-20, which features double coils and a 2-mm quantities. stroke, costs $236.98.

Analog Devices, Inc. Nippon Pulse America www.analog.com www.nipponpulse.com

8 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com npn.qxp 11/1/2006 12:01 PM Page 9

NEW PRODUCT NEWS PRECISION SINGLE-CHANNEL DIGITAL FILTER The new QF1D512 simple and versatile FIR engine (Sav- the Quickfilter Pro software. Developed specifically for FIRe) precision digital filter enables system designers to the QF1D512, this software version uses the same filter quickly and easily add precision digital filtering to an design engine as earlier versions and adds a more intuitive application. The chip can be easily added between an user interface for configuring the chip itself. The develop- existing ADC and the host controller (, ment hardware allows this configuration to be downloaded microprocessor, digital signal into the chip to verify filter performance. processor, or field programmable The board features an on-board ADC to gate array), or it can be connected allow operation “out of the box.” It also as a coprocessor device for con- provides the option for users to add their trollers with embedded ADCs. own preferred ADCs to match their end Whereas the previously introduced application. This type of flexibility is fur- four-channel QF4A512 imple- ther extended to allow the development ments a complete analog interface, board to be connected to the user’s own the QF1D512 offers a simple host microcontroller, thereby allowing upgrade path for existing systems. system development to proceed without The companion development kit the need for custom hardware. (QF1D512-DK) allows the device The QF1D512 is packaged in a 3 mm × to be configured to work with 3 mm QFN package and is characterized almost any ADC up to 24 bits, and over the industrial temperature range. It’s a variety of precision filters can be priced at $2.98 in 1,000-piece quantities. quickly designed without the need to write code. The development Quickfilter Technologies, Inc. kit includes the latest version of www.quickfiltertech.com FLOATING-POINT COPROCESSOR CONNECTOR COMBINES PINS, CONTACTS, The uM-FPU V3 floating-point coprocessor chip inter- BLADES, AND COMPONENTS faces to virtually any microcontroller using a SPI or I2C The MultiWise Connector is an industry-advancing interface, making it ideal for microcontroller applications connector technology that combines pins, contacts, and requiring floating-point math, including sensor readings, blades on a single platform, giving engineers the power to robotic control, GPS, data transformations, and other design greater conductivity and functionality into small- embedded control applications. footprint devices. As the first significant alternative to The uM-FPU V3 chip supports 32-bit IEEE 754-compati- discrete pin or blade configurations, the MultiWise Con- ble floating-point and 32-bit integer operations. The new nector provides a new dynamic to satisfy the need for chip is 10 to 20 times faster than previous versions for all increased power density in small spaces. Configurations instructions and up to 70 times faster for advanced instruc- using both pins, contacts, and blades allow greater sim- tions. New instructions provide support for faster data plicity and flexibility in designs by offering engineers transfer, matrix operations, multiply and accumulate, Fast more options for lowering contact resistance while main- Fourier Transform operation, unit conversions, and string taining the necessary power/signal mix. handling. Two 12-bit A/ channels are provided that can OEM design engineers once restricted to packaging mul- be triggered manually by external input or from a built-in tiple connectors and circuitry together in an assembly can timer. A/D values can be read as raw values or automati- now combine the required connector features and circuit- cally scaled to floating-point values. Local data storage has ry together on one MultiWise Connector. With the intro- been expanded to include 128 general-purpose registers, duction of blade pins, designers can now take advantage of eight temporary registers, 256 EEPROM registers, and a greater conductivity available in more rugged copper and 256-byte instruction pipeline. brass alloy blades. Because these materials carry more cur- An IDE makes it easy to create, debug, and test floating- rent, the MultiWise Connector frees up precious space for point code. The IDE code generator takes traditional math additional components. Moreover, the manufacturing expressions andWWW.GiURUMELE.Hi2.RO automatically produces uM-FPU V3 code processes can place SMT devices like decoupling capacitors, targeted for any one of the many microcontrollers and com- resistors, and ICs pilers supported. The IDE also supports code debugging and directly on the programming user-defined functions. connector. The chip is available in an 18-pin Prices begin at DIP, SOIC-18, or QFN-44 pack- $3 in quantities age. The single unit price is of 1,000 or more $19.95 with volume discounts for the configu- available. ration as shown.

Micromega Corp. Onanon, Inc. www.micromegacorp.com www.onanon.com

www.circuitcellar.com ® CIRCUIT CELLAR Issue 197 December 2006 9 npn.qxp 11/1/2006 12:01 PM Page 10

NEW PRODUCT NEWS FANLESS 1-GHz ULTRA-LOW-POWER INDUSTRIAL SBC The EBC-855-G is an EBX-compati- SDRAM, up to 8 GB of Compact- disk drives. The EBC-855-G offers a ble 1-GHz ultra-low-power Flash, and support for hard and floppy full set of I/O interfaces including a Celeron (Dothan core) SBC that 10/100BaseT Ethernet port (with operates over an industrial tem- remote boot capability). It also perature range of –40° to 70°C. offers a VGA and dual-channel Target applications include LVDS flat panel video, a miniP- MIL/COTS, industrial automa- CI connector that supports an tion, medical/diagnostic equip- optional 802.11 wireless net- ment, communications, securi- working module, four USB 2.0 ty, test and measurement, and ports, four serial COM ports, outdoor transaction terminals. AC97 audio (5.1 codec), LPT, The EBC-855-G is a full-fea- and a PS/2 port for a keyboard tured SBC with a variety of and mouse. An onboard, soft- onboard peripherals that elimi- ware-programmable, 48-line dig- nate the need for additional ital I/O controller provides standard I/O peripheral cards. input, output, or output with It’s based on the Intel’s popular read back for each I/O line. The 855GME chipset with the ICH4 board also is populated with communications controller and both PC/104 and PC/104-Plus integrated Extreme Graphics 2 interface connectors for support video 3-D controller. Both the of additional off-the-shelf or user- CPU and system controller are designed specialty I/O modules. supplied from Intel’s Embedded The EBC-855-G board costs Architecture Division for long- $595. term availability. It supports a maximum of 1 GB WinSystems of industry-standard PC2700 www.winsystems.com

Create your Future at Camosun College

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

www.elex.camosun.bc.ca [email protected] 10 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com npn.qxp 11/1/2006 12:01 PM Page 11

NEW PRODUCT NEWS FEATURE-RICH, HAND-HELD DIGITAL MULTIMETERS The U1250A is a new series of affordable hand- basic accuracy of held digital multimeters. Engineers and techni- up to 0.025%, cians in today’s electronics industry face an offering simultane- increasing need for high-performance portable ous and accurate instruments in service and maintenance measurements and applications. These new meters address providing the flexibility these market needs, allowing users to per- to perform either quick form tests in-plant and off-site without validation or tolerance compromising performance. checks and marginal failure Built to ease electronic trou- troubleshooting. In addition bleshooting and validation, the high- to the basic measurement performance, portable U1250A functions, these models come series enables engineers and tech- with capabilities such as automat- nicians to complete their day- ed datalogging with the optional PC to-day tasks without being interface cable, a 20-MHz frequency confined to the bench. The counter, and a programmable square initial entry in this series wave generator and temperature meas- comprises two feature- urement. The meters are rated at CAT III packed models, the U1251A 1000 V. Both models come in a robust and the U1252A, which are package with shock-absorbing over-mold. designed for the cost-sensi- They operate within their rated specification tive test and measurement from –20° up to 55°C. market. The U1250A series starts at $399. The meters provide 4.5-digit resolution with 50,000 count Agilent Technologies, Inc. full-scale on dual display and www.agilent.com

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 11 npn.qxp 11/1/2006 12:01 PM Page 12

Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. 8-BIT MCUs WITH INTEGRATED ETHERNET A new family of the world’s smallest eight-bit microcon- troller family are available starting at $4.24 each in 10,000- trollers with an integrated IEEE 802.3-compliant Ethernet unit quantities. communications peripheral is now available. The PIC18F97J60 family is optimized for embedded applica- , Inc. tions. It has an on-chip medium access controller (MAC) www.microchip.com and physical layer device (PHY). By integrating a 10Base-T Ethernet controller onto a 10-MIPS PIC18 microcon- troller with up to 128 KB of flash program memory, Microchip is providing embedded systems designers with a single-chip remote-communication solution for a wide range of applications. Embedded engineers have long wanted to add remote monitoring and communication to their embedded designs, but previous solutions were expensive and complex. Due to the integration of the PIC18 8-bit microcontroller with a complete Eth- ernet controller, designers can now have network connectivity in 64- to 100-pin packages that is one of the most cost effective and easy-to-use Ethernet solutions. A free TCP/IP software stack to reduce development time is also available. Key features for all nine members of the family include seamless migration from previous PIC18 designs, IEEE 802.3 compliance, and a dedicated 8-KB Ethernet buffer. The family also features 128 KB of flash memory and 4 KB of SRAM. This memory accommodates the TCP/IP stack with web server and leaves ample space for user application code. All nine members of the PIC18F97J60 microcon-

1.6-V HIGH-PRECISION OP-AMPS The new LT6003 family of ultra-low-power op-amps that input offset voltage of 500 µV maximum at 25°C set a new standard for precision low-voltage operation and and a maximum drift of 5 µV/°C, the LT6003 tiny footprint is now available. The LT6003 (single), LT6004 family is the most precise low-voltage, ultra-low (dual), and LT6005 (quad) amplifiers draw less op-amp. A tiny 2 mm × 2 mm DFN package than 1 µA and operate from 1.6 makes the footprint of the LT6003 the smallest to 16 V. With in this class and inputs and outputs feature rail-to-rail operation. The LT6003 family is ideal for battery-operated, hand-held instru- mentation due to the combination of low sup- ply current, a 1.6- to 16-V operating range, and tiny packages. Both leaded and leadless DFN packages are available with fully guaranteed specifi- cations over commercial (0 to 70°C), indus- WWW.GiURUMELE.Hi2.ROtrial (–40° to 85°C), and automotive (–40 to 125°C) temperature ranges. The LT6003 family is available now with 1000-piece prices of $0.72, $1.10, and $1.75 for the single LT6003, dual LT6004, and quad LT6005, respectively.

Linear Technology Corp. www.linear.com

12 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2.qxp 10/5/2006 9:06 AM Page 1

DESIGN STELLARIS 2006

Challenge yourself against other top • No purchase necessary to enter. embedded engineers around the world in • $10,000 in cash prizes! DesignStellaris2006, proudly sponsored by • Entry deadline is February 7, 2007. Luminary Micro, Keil, and Circuit Cellar. • Winners will be announced at the Embedded Systems show... Silicon Valley 2007. Use any microcontroller in Luminary Micro’s Stellaris™ family of ARM® Cortex™- M3 controllers with the • Submit your design today! ARM RealView® Microcontroller Development Kit FOR COMPLETE DETAILS, VISIT (MDK-ARM) to create your design contest entry, www.LuminaryMicro.com/ and see how far your design will take you! DesignStellaris2006

LUMINARY MICRO LM3S811 EVALUATION KIT WWW.GiURUMELE.Hi2.ROVisit our website for more information! DESIGN STELLARIS 2006] THE LM3S811 EVALUATION KIT includes the Stellaris LM3S811 Evaluation Board, an evalua- [ tion copy of MDK-ARM, USB cable, documentation, and programming examples. www.LuminaryMicro.com/DesignStellaris2006 2612015cloutier.qxp 11/2/2006 9:27 AM Page 14

FEATURE ARTICLE by Greg Cloutier ARM Scope Build an Analog Oscilloscope Companion Greg’s ARM Scope improves upon ordinary analog oscilloscopes that don’t provide suitable results at low speeds. The LPC2138-based system features a timed PWM output for the more precise calibration of the oscilloscope as well as an analog input and an analog output with a graphical display. As a result, the displayed signal is more accurate at high or low speeds.

At work, I have access to a host of functionality (see Photo 1). The ARM be able to source an arbitrary analog high-end instrumentation. Having Scope does not duplicate what the old signal. This can be used to test a filter access to such equipment spoiled me analog oscilloscope does well. It sim- or drive a sensor. Signal generation is after a while, and I felt like something ply adds some functionality where it’s also useful for test and measurement was missing when I was working on needed most. applications. projects at my house. Although my The companion requires three func- digital multimeter worked well for tions to make a nice addition. The HARDWARE OVERVIEW most projects, I really wanted to be first function is a pulse-width modula- I have played around with many dif- able to see signals as well. I couldn’t tor (PWM) source that can be used to ferent microcontrollers and develop- justify spending a lot of money on calibrate or verify the oscilloscope’s ment environments. Until I started new test equipment, so it looked like I timebase throughout its entire range. this project, all my experience with would need to settle for an older ana- The second function is a low-speed microcontrollers had been with either log oscilloscope. After spending some capture and display that enables me to 8- or 16-bit varieties, and none of the time searching the Internet for an visualize the slower signals that the microcontrollers I had used could run affordable system, I ended up with the oscilloscope can’t retain. While I was fast enough for my desired PWM rate. winning bid on an auction site for a at it, I decided that it would be nice to Most of them didn’t have a DAC or Hewlett-Packard HP1742A oscillo- scope. Spending $40 on a 100-MHz oscilloscope was worth it for me. The oscilloscope worked out great and has been a welcome addition to the small lab in my house. Once I had the oscilloscope hooked up, I thought that the void was filled. But a problem with an old analog oscilloscope is that it can’t provide much useful information at low speed. The display is not retained, and you are left guessing at what the signal looked like. AnotherWWW.GiURUMELE.Hi2.RO problem is that I am never too sure about the calibra- tion throughout the timebase range. The on-board calibration pin is for voltage, while the frequency is not spec- ified. Even if the frequency were speci- fied, it wouldn’t necessarily be useful throughout the full timebase range. Recognizing these issues, I designed an analog oscilloscope companion to Photo 1—Based on the user interface’s setting, the processor generates a signal that is being read back in and help the system achieve complete displayed. At the same time, the PWM signal is generated and used to verify my analog oscilloscope timebase.

14 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612015cloutier.qxp 11/2/2006 9:27 AM Page 15

enough RAM. I hadn’t ever time delays. Given that a used an ARM processor Computer with clock rate of 60 MHz will LabVIEW user before, but I tried one in this interface count from zero to 60 mil- design. lion in 1 s, you can calcu- The companion features a late what you need to count Keil MCB2130 evaluation to for a desired delay. When

board, which made it easy to Keyspan USB-to- it matches a value that you experiment with and explore RS-232 adapter provide, an interrupt is trig- the capabilities of the NXP gered. This interrupt is used (founded by Philips) LPC2138, to pace the system. The which is a superset of the Timer0 interrupt can reset LPC213x Tiny 32-bit the counter to zero and start Keil MCB2130 Analog input Analog output ARM7TDMI-S processor evaluation board counting all over again. This family. This series of proces- way repetitive tasks (e.g., col- sors appears to be extremely lecting data at a certain rate) popular. Without providing occur on their own. Even hard data, the family’s cost is running at 60 MHz with no Analog surprisingly competitive oscilloscope prescaler, a 32-bit counter with most 8- or 16-bit offer- can range from a count of ings. The processor’s peripher- one (about 17 ns) to a count als matched what I needed for Figure 1—Take a look at how the equipment is linked together. The Keil evaluation of 4,294,967,296 (about 71.5 s). board is at the heart of the system. All of the data and signals flow through it. my oscilloscope companion. The time delay is to be set on The MCB2130 evaluation the fly by command. board enabled easy access to route sig- processor then multiplies up to 60 MHz The ADC peripheral is used to cap- nals in and out. I didn’t need to create via its PLL function. This is how the ture analog voltage signals and convert a custom circuit board to accomplish project achieved the speed I desired. them into a binary number. All but my goals. Many of the evaluation I used the PWM peripheral to output the lowest-end LPC213x ARM proces- board’s features (e.g., push buttons, the timebase calibration source, which sors contain two 10-bit ADCs. The LEDs, a potentiometer, and a speaker) was my first functional requirement. lower end devices contain just one. came in handy while I was learning to The PWM is its own peripheral and This isn’t as limiting as it sounds. program the ARM processor. It also does not link to (but is based on) the Each ADC is multiplexed among up to includes a JTAG port, which is useful system counter/timers. A programma- eight input pins. The ADC conversion if you happen to have a JTAG debug- ble 32-bit prescaler can slow down the takes place in 2.44 µs. This means you ger. (I don’t have one, so I didn’t use PWM, which contains its own 32-bit could gather full 10-bit readings from the port.) Power is supplied through a timer/counter. The PWM can drive up a pin at a rate of just higher than USB plug so that your PC sources 5 V to six pins for various uses. I decided 400,000 samples per second. You to the board. Best of all, there are two that two PWM signals would be a nice could even go a bit faster if you are fully functional RS-232 ports complete fit. One pin is configured to output a willing to accept a lower resolution. with level converters. One of the RS- pulse that is one division wide on the This 10-bit result represents a range of 232 ports is used to download your oscilloscope display. The other pin is 0 to 3.3 V. A voltage of zero will be program into the ARM processor’s configured to output a pulse that is given a value of zero. A voltage of 3.3 flash memory. Both can be used for eight divisions wide. This provided will be given a value of 1,023. Every communicating with a PC. After enough flexibility to verify my oscillo- thing in between is scaled accordingly. learning about all of these features, I scope’s calibration all the way from 2 s Timer0 is used to pace the system, knew the project would become the per division to 0.05 µs per division. so each ADC conversion happens ARM Scope (see Figure 1). The period and duty cycle are set on within the timer interrupt. I chose to Being a superset for the series, 512-KB the fly by command. Refer to Table 1 use only the top 8 bits of the result of flash memoryWWW.GiURUMELE.Hi2.RO was nice to see, but to see how I associated the PWM tim- (256 possible values rather than 1,024). well beyond what I needed for this ing with the oscilloscope timebases. I didn’t do this because I wanted to application. The included 32 KB of The Timer0 peripheral is set up to increase my collection rate. What I RAM was also more than I required. pace the A/D input and the D/A out- really wanted was to increase the rate That being said, have you ever heard put. As with the PWM, this also con- at which I could transfer data to my of anyone complaining about having tains a 32-bit timer/counter and can PC. To send an 8-bit result, I can do it too much RAM? Most of the micro- be slowed down by a programmable in 1 byte. Sending a 10-bit result controllers I’ve used had less total 32-bit prescaler. In this case, however, would require 2 bytes that would slow flash memory than this ARM contains it’s used to time or count events. The down the display rate by a factor of for RAM. The evaluation board is events that it counts in my applica- two. An 8-bit result looks just fine on clocked by a 12-MHz crystal, which the tion are clock cycles. I use it to create my PC’s display, especially because

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 15 2612015cloutier.qxp 11/2/2006 9:27 AM Page 16

I’m most interested in the shape or used for sending and receiving the ana- tion board, the kit included Keil’s DK- appearance of the signal. log data. It is also used for receiving ARM software package. The software The DAC peripheral is used to out- and responding to commands from the package included Keil’s µVISION 3 put an analog voltage by converting a user interface. The port’s speed is con- IDE and Keil’s ARM compiler. The binary number to the desired voltage. figured to send or receive data at IDE handles everything including proj- Unlike the ADC, the DAC is not mul- 57,600 bps. This data rate is the true ect management, code editing, calling tiplexed, and it outputs only a voltage limiting factor in my design. Because I up the flash memory programming through one pin. All but the lowest- send the analog data as I capture it (in application, simulation, and handling end LPC213x ARM processors contain the Timer0 interrupt), I don’t capture the compiler. If I had a JTAG debug- a single 10-bit DAC. The lower-end data any faster than it can be sent to ger, it would handle that as well. device doesn’t contain a DAC. Given the the PC. Of course, this is fast enough You have a choice of using Keil’s opposite functionality of the ADC, you to meet my functional goals. The ARM compiler or the included GNU supply a value and are rewarded with an UART’s input and output both contain compiler. The Keil compiler is limited analog voltage in 1 µs. You could update a 16-byte hardware buffer. When a byte to producing 16 KB or less of code (as is this voltage up to 1,000,000 times per arrives at the UART, a polling loop the simulator/), while the second. To output 0 V, you would pro- calls a function to handle the data. GNU compiler can produce code of any vide a value of zero. To output 3.3 V, you size (although the simulator/debugger would provide a value of 1,023. EMBEDDED CODE is still limited). I knew my code would I am not passing this data continuous- Along with the MCB2130 evalua- fit under the 16 KB limit, so I used the ly across from the PC, so the resolution will remain at its full 10 bits. The analog output sig- Time tick Maximum ticks Maximum int (signed) nal is contained in a 1,000-byte 16.67 ns (no prescale) 2,147,483,648 4,294,967,296 array (500 data points). Within the Timer0 interrupt, I incre- PWM timing at 60 MHz ment the data array index and Scale (s) Divisor Seconds per Seconds per 60-MHz Counts per Refresh rate (Hz) send the value to the DAC. division sweep sweep Because both the ADC and 1 2 1 2 20 1,200,000,000 0.05 DAC’s functionality are paced 2 1 1 1 10 600,000,000 0.1 by the same timer interrupt, 3 0.5 1 0.5 5 300,000,000 0.2 these signals are synchronized. 4 0.2 1 0.2 2 120,000,000 0.5 The data buffer, which is filled by command, can contain any 5 0.1 1 0.1 1 60,000,000 1 arbitrary signal or pattern. 6 0.05 1 0.05 0.5 30,000,000 2 I used the two UART 7 0.02 1 0.02 0.2 12,000,000 5 peripherals. UART0 was used 8 0.01 1 0.01 0.1 6,000,000 10 to program the on-board flash Scale (ms) memory with my program. 9 5 1,000 0.005 0.05 3,000,000 20 The LPC213x ARM processor 10 2 1,000 0.002 0.02 1,200,000 50 series contains an on-board 11 1 1,000 0.001 0.01 600,000 100 bootloader. At reset, the boot- 12 0.5 1,000 0.0005 0.005 300,000 200 loader looks to UART0 to see if a new program needs to be 13 0.2 1,000 0.0002 0.002 120,000 500 loaded. This is great because 14 0.1 1,000 0.0001 0.001 60,000 1,000 you don’t need to buy or build 15 0.05 1,000 0.00005 0.0005 30,000 2,000 a special device . 16 0.02 1,000 0.00002 0.0002 12,000 5,000 On the PC side,WWW.GiURUMELE.Hi2.RO once you 17 0.01 1,000 0.00001 0.0001 6,000 10,000 have created a program, you Scale (µs) can use the NXP application 18 5 1,000,000 0.000005 0.00005 3,000 20,000 dedicated to programming the 19 2 1,000,000 0.000002 0.00002 1,200 50,000 ARM. The LPC2000 Flash 20 1 1,000,000 0.000001 0.00001 600 100,000 Utility communicates with 21 0.5 1,000,000 0.0000005 0.000005 300 200,000 the bootloader to get things 22 0.2 1,000,000 0.0000002 0.000002 120 500,000 done with no intervention from the developer. The other 23 0.1 1,000,000 0.0000001 0.000001 60 1,000,000 UART is used for communi- 24 0.05 1,000,000 0.00000005 0.0000005 30 2,000,000 cating with the PC over an Table 1—For each timebase on my oscilloscope, I was able to calculate an appropriate PWM value that would be useful for RS-232 interface. This port is timebase verification.

16 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 17-renesas.qxp 11/2/2006 11:54 AM Page 1

WWW.GiURUMELE.Hi2.RO 2612015cloutier.qxp 11/2/2006 9:27 AM Page 18

Keil compiler. I assumed that it was Listing 1—This is a sample of what happens in the command handler. First, the command is determined and fully integrated into the IDE and that then the appropriate case handles the data or parameters. it would get me up and running quick- ly. The user-friendly environment void processCommand(void) { worked without fail. It is also nice to int tempInt; know that it can be set up to not only char tempChar; develop code for the LPC213x series, int readBufferIndex; but also for nearly every brand and //int aoBufferIndex; tempChar = *readBuffer; //get fist char from global read buffer model of ARM processor in produc- tempChar = toupper(tempChar); //ensure upper case for switch statement tion today. tempInt = atoi(readBuffer + 1); //read integer value if command has one I knew that communicating with switch(tempChar) my PC would be essential, so I imme- { case ‘A’: //set up pwm values and run the pwm diately began studying the examples { included with the evaluation kit. Sam- PWMTCR = 0x0000002; //counter reset ples of UART functionality were PWMMR0 = tempInt; //set period found in two of the three examples. PWMMR2 = (tempInt / 10); //set PWM2 (P0.7) duty to 10% PWMMR5 = ((tempInt / 10) * 8); //set PWM5 (P0.21) duty to 80% Along with the datasheet and NXP’s PWMTCR = 0x00000009; //Enable counter and PWM 2 “UART/SPI/I C Code Examples,” I IOSET1 |= 0x00020000; //P1.17 LED ON (PWM enabled) was able to create my routines to break; communicate with the PC. } case ‘B’: //disable pwm The straightforward output routine { typically just sends the ADC data to PWMTCR = 0x0000002; //counter reset (disable PWM outputs) the PC via the UART as the data is IOCLR1 |= 0x00020000; //P1.17 LED OFF (PWM disabled) acquired within the Timer0 interrupt. break; } The printf() command sends the data. I send the 8-bit piece of data and a \n character. The application on the PC adds each piece of data it receives to mands must be agreed upon between and updated based on this value as the display. The data sent from the PC the processor code and the application well. Command B stops the PWM out- and received by the ARM processor is running on the PC. In this case, there put. Command C updates the Timer0 handled in a slightly different way. A are eight command represented by the counter match limit, which updates typical transfer in this direction usually uppercase letters A through H. the rate at which the ADC data is read includes a command and some data or Command A sets the PWM period. in and the DAC data is output. Com- parameters. This was implemented in The output duty cycles are calculated mand D sets a flag that enables the such a way that the processor doesn’t stop while waiting for data to come in. The main loop is set up to poll the Listing 2—This is the entire interrupt routine. It’s really the heartbeat of the program. It performs all the ADC UART for data in a continuous man- and DAC operations while pacing the program. ner. Not much goes on in the main void tc0 (void) __irq loop, and there is a 16-byte buffer, so { it’s unlikely that any data will be unsigned int val; missed. An alternative would be to set if(aiFlag == AI_ENABLE) //capture and send analog input value if up a UART receive interrupt. Within //flag is set the polling routine, the received data is { transferred into a receive buffer array. val = ai(); This is done because it is not necessary printf(“%c\n”,val); } to act on a commandWWW.GiURUMELE.Hi2.RO until all the data or parameters are received as well. It is if(aoFlag == AI_ENABLE) //output and increment analog output determined that the reception is com- //buffer if flag is set plete when a \r character is received. { DACR = aoBuffer[aoBufferIndex]; Once the reception is complete, a func- aoBufferIndex++; tion is called to process the command. if(aoBufferIndex >= 500) This function determines which com- aoBufferIndex = 0; mand has been sent and then acts } accordingly on the data or parameters. T0IR = 1; // Clear interrupt flag I left the command structure fairly VICVectAddr = 0; simple because there were not too } many commands to implement. Com-

18 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612015cloutier.qxp 11/2/2006 9:27 AM Page 19

Photo 2—Take a look at the ARM Scope’s GUI. The virtual oscilloscope displays the incoming analog data and enables point-and-click control over the operation of the processor.

ADC operation within the Timer0 through the datasheet and set up mul- interrupt. Command E clears a flag tiple registers, the configuration utili- that disables the ADC operation with- ty enables you just check or uncheck in the Timer0 interrupt. boxes and type in values as needed. I Command F fills the analog output used this utility to set up the PLL to data buffer with 500 values. These val- provide the 60-MHz clock rate. ues are sent as ASCII text representa- Most of the work is done within the tion that gets converted into 10-bit Timer0 interrupt. Some designers binary representation for storage in would argue that the interrupt routine the data array. Command G sets a flag should just set a flag and get back to that enables the DAC operation with- the main routine as quickly as possi- in the Timer0 interrupt. ble. There is not much going on in the Command H clears a flag that disables main loop, so I felt that running the the DAC operation within the Timer0 code in the interrupt would be fine. interrupt. The LED indicators on the Maybe next time I’ll do it the other evaluation board are also set and cleared way just for the sake of functional to provide operational status. More com- upgrades over time. The ADC opera- mands could easily be appended to the tion comes first. If the flag that allows list as needed. A sample of the com- this operation is set, the voltage on mand handler is shown in Listing 1. the pin is read and then sent to the PC The main() function starts by call- via the UART. The data is appended ing all set-up and initialization func- with a \n termination character so tions. These include the UART, PWM, that the receiving application knows DAC, ADC, andWWW.GiURUMELE.Hi2.RO Timer0. It also lights that the data has been sent. an LED that let’s me know when the The DAC operation comes next. If the processor has initialized and is ready flag that allows this operation is set, the for operation. Following this, the main analog data array index is incremented loop does nothing but poll for data to the next piece of data, which is sent arriving via the UART and calls the through the DAC and then out the pin command processing function if the as a voltage. Listing 2 shows what the command is ready to be processed. interrupt routine looks like. A nice thing about the Keil µVISION 3 IDE is the start-up config- USER INTERFACE uration utility. Rather than sort I developed the user interface with

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 19 2612015cloutier.qxp 11/2/2006 9:27 AM Page 20

the structure. Debugging is also very easy. Lab- VIEW lets you watch data flow through the wires in slow motion. You can also set break points and create probes (watch windows). The other thing that LabVIEW is famous for is its connectivity to hard- ware and other applica- tions. National Instru- ments sells hardware such as data acquisition devices with prebuilt VIs to access the functionali- ty with little or no pro- gramming. Many equip- ment vendors such as Agilent provide LabVIEW drivers for their products. LabVIEW can also handle ActiveX and .NET code, Internet protocols, and Photo 3—This is where all the graphical code is developed. Note that there are two main sections of code that run in separate threads. much more with ease. The hardware that National Instruments’s LabVIEW (see code is called the block diagram. The interested me was my RS-232 serial Photo 2). LabVIEW is a graphical pro- view used to create the user interface port. I needed only four functions to gramming language meant for engi- is called the front panel. To create the handle the serial port in Windows XP: neers to easily acquire and display user interface, all of the controls, indi- Open, Read, Write, and Close. It just data. Unlike a text-based language, cators, and graphs are also logically doesn’t get any easier than that. Lab- code is created using graphical virtual grouped in their own palette so you VIEW also produces a multithreaded instruments (VIs), which are the can drag and drop them. When you application by simply drawing sepa- equivalent of functions. You can cre- drop a control on the user interface, it rate sections of code on the same block ate a function and then save it as an gets a representative icon on the block diagram. It can also handle some event- icon. Then multiple functions can be diagram as a source of data. When you driven programming that responds to used by a larger function, again repre- drop an indicator on the user inter- button clicks on the front panel. sented as an icon. Hieratical code is face, it gets a representative icon on The user interface was created to easy to build, and it’s easy to reuse the block diagram as a sink for data. look like an oscilloscope screen. The functions. In the block diagram, data is repre- drag-and-drop graph is set up to dis- LabVIEW is a data flow language, sented by wires similar to those you’d play 500 points at a time. Clicking in which means the flow of data has full see in a schematic capture package a display list sets the timebase for the control over the order of events. Each (see Photo 3). Arrays of data appear as oscilloscope. The analog inputs and of the inputs and outputs of a VI are thicker wires. As dimensions are outputs are enabled or disabled by click- represented as terminals on the icon. added to the array, the wires appear ing on appropriately labeled buttons. To pass data from VI to VI, you must even thicker. Also, like in the C lan- The amplitude of the analog output is draw wires fromWWW.GiURUMELE.Hi2.RO the output terminal guage where structures are used to set by a slider control, while the shape of one to the input terminal of anoth- create custom data types that contain of the wave is selected from a dropdown er. Built-in functions are found on a multiple types of data, LabVIEW uses box. The PWM output is set by clicking graphical palette rather than within .h something called a cluster. For loops in a list that displays all of the available files. Functions are logically grouped and while loops are just drawn around times bases on my analog oscilloscope. and are as easy as drag and drop. Code the code that you want to iterate on. can be executed immediately. If there Local data is sent around the loop via FUNCTIONAL CODE is something that will prevent it from shift registers. LabVIEW handles alter- I developed two separate pieces of running, the environment is very clear nate code execution by way of case functional code for the AVR Scope. as to where the problem lies. structures. For every anticipated case Both attach to the same serial port for The view used to create the program (and a default), you draw code within talking to the ARM processor.

20 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612015cloutier.qxp 11/2/2006 9:27 AM Page 21

+++ NO ROYALTIES +++

PIN Function by the user interface or in the processor code. LabVIEW embeddedsoftware Pin 7 PWM Output (duty cycle = one oscilloscope division) also has some powerful built- Pin 21 PWM Output (duty cycle = eight oscilloscope divisions) solutions in math and DSP functions, Pin 28 Analog input (0 to 3.3 V) so I could analyze the data in Eval versions Pin 25 Analog output (0 to 3.3 V) various ways. available COM0 Used to program the device via built-in bootloader Note that I did not include COM1 Set to communicate with computer at 57,600 bps any analog circuits. This ® project was meant to get ana- embOS (RTOS) Table 2—Instead of providing a schematic for the evaluation board, I +++ 8/16/32 bits +++ log data into and out of a decided to show you the pins used for inputs and outputs. Remem- Preemptive multitasking ber that the signals need to be scaled appropriately outside the processor. The way I scale Zero interrupt latency scope of this project. the signal from a sensor to Easy to use start project included match the 0 to 3.3 V range Profiling support included The first piece of code continually would be another project altogether. Object/source code available collects the analog data and displays it There was no one-size-fits-all solution on the graph. The second piece of code for this, so I left it to be application is linked to everything you can click specific. If you add some control cir- on the front panel. When you click a cuitry, there will be plenty of pins left button or list, the event handler sends over and the processor will have plen- an appropriate command along with ty of horsepower left. its data or parameters to the ARM By the way, I didn’t even make a processor. Each of these functions runs dent in the amount of flash memory. I in its own thread. The event handler stayed well under the limits of the thread remains asleep most of the time compiler as well, so there is plenty of emWin ® until a button is pressed. The analog room to grow the code as needed. The (GUI) +++ 8/16/32 bits +++ receive and display loop is paced by the pins I used for inputs and outputs are ANSI "C" source code, no C++ required incoming data. It will sit and wait for shown in Table 2. I Supports b/w, grayscale and color data to be received at the serial port. 2D graphic library included Greg Cloutier ([email protected]) Variety of fonts included SYSTEM DEVELOPMENT PC simulation included works as a test and measurement Window Manager/Widgets (opt) The ARM Scope system met all engineer for JDS Uniphase Corp., three of my goals. It can output a which develops and manufactures PWM signal for verifying my old ana- fiber optic communications compo- log oscilloscope’s timebase through its nents. He first became interested in entire range. It can capture and let me microcontrollers at work and now visualize analog signals at a slower works with them in his spare time. emFile rate than my oscilloscope can. And it (File system) +++ 8/16/32 bits +++ can output any analog waveform that PROJECT FILES ANSI "C" source code can be generated and sent to the data MS-DOS/MS-Windows compatible buffer. I set up my graph display so To download the code, go to ftp://ftp. FAT12, FAT16 and FAT32 support that it had 10 divisions just like a real circuitcellar.com/pub/Circuit_Cellar/ Multiple media support oscilloscope. As it is, the timebase for 2006/197. Non FAT file system available the analog input and output functions can be set to a range from 2 s per divi- RESOURCE sion to 0.02 s per division. NXP Semiconductors (founded by I’m considering a few upgrades for Philips), “UART/SPI/I2C Code Exam- the code. Of course, both the processor ples,” rev. 01, AN10369, 2005. code and the userWWW.GiURUMELE.Hi2.RO interface code need to be updated as a matched set if func- For ARM Chips: tionality is added. I know that the SOURCES JTAG debug solution ADC is capable of reading much with flash programming MCB2130 Evaluation board faster. I can see filling a buffer up Keil quickly and sending the data for dis- www.keil.com play at a much more relaxed rate. For that matter, collecting extra data LPC2138 Microcontroller could be useful for triggering a signal NXP Semiconductors (founded by phone: 978-874-0299 or zooming in on the data. I would Philips) www.segger.com have to decide if this would be done www.nxp.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 21 2612014lohani.qxp 11/2/2006 9:50 AM Page 22

FEATURE ARTICLE by Samir Lohani Digital Instrument Panel A Simple Panel for Diesel Engines With Samir’s digital panel for diesel engines, you can view critical engine-related data on a PC, HMI console, or Bluetooth-enabled portable device. You can use the panel as a stand- alone device or as a diesel engine’s preprocessor in a PLC-based system.

I recently designed a system to serve system on its own or as a diesel engine advance without operator intervention. as a “black box” that interfaces with a preprocessor in a PLC-based system. However, fitting PLC-compatible sen- diesel engine’s pressure, temperature, sors and instrumentation would have and RPM sensors. The design gener- SMALL BLACK BOX been a nuisance. I wanted a black box ates serial packet data for a digital I have often wondered why the for the existing instrumentation. instrument panel that can be viewed instrument panels for industrial diesel I decided to build a separate unit to on a PC, on a human machine inter- engines, gensets, and medium-power connect to the PLC via a serial link in face (HMI) console, or via a Bluetooth machinery are so monotonous and order to handle all of the interfacing link on a mobile device. dull. Contrast such panels with the requirements for diesel engine sensors. I designed the system for medium- colors, chrome rings, and rich accents A parallel Bluetooth link was included capacity diesel engines on railroad on modern automobile dashboards! for wireless connectivity. vehicles and gensets (environments Aesthetics aside, maintenance engi- I used a Renesas Technology subjected to heavy switching where neers must be able to keep a record of M16C/62P SKP microcontroller board EMI/EMS noise considerations are an engine’s parameters and monitor its in view of the superior EMI/EMS spec- important). It’s also been used to sim- performance. ifications demanded by these environ- plify the design of PLC-controlled test I took a close look at the conven- ments. The generous amount of flash beds for engines. The system can inter- tional engine panels while I was set- memory and its in-built DAC prompt- face with existing industrial-grade sen- ting up a PLC-controlled test bed for ed me to include an audio interface for sors fitted on an engine, which may be diesel engines in a maintenance unit. intuitive alarm annunciations. This nonlinear. It also includes intuitive Interfacing the existing analog instru- offers interesting possibilities for con- alarm annunciations that are based on ment panel would have enabled the veying alarm messages through a com- recorded messages. You can use this PLC to detect abnormal conditions in mon VHF channel on walkie-talkies.

a) b)

c) WWW.GiURUMELE.Hi2.RO

Photo 1—I’m interested in several gauges and sensors: analog gauges with pressure and temperature senders (a), an RPM gauge with a magnetic pick-up sensor (b), and multipurpose digital pressure gauges with 5-V analog output (c).

22 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612014lohani.qxp 11/2/2006 9:50 AM Page 23

Now the operator is no longer con- also provide a 1- to 5-V analog output. sure gauges with 5-V analog output. The strained to stay close (or within limited I found them to be extremely useful four remaining channels (AN4–AN7) are Bluetooth range) to the instrumentation. and reliable. Their analog output also for measuring voltages across analog The data sent by the unit consists of makes interfacing them a breeze! gauges. (The measuring span is kept at ASCII packets, which can be processed 16 V to cover all common P/T gauge- by the PLC or viewed on a PC or a CIRCUITRY sensor pairs in 24-V systems.) mobile device. Incorporating the sen- I designed the circuit for the system The D/A section is used to imple- sor interfacing and processing func- as an extension to the M16C/62P SKP ment the speech interface. Output tions in a single unit also simplifies microcontroller board. As you can see DA1 is connected to a low-pass sec- the ladder programming and improves in Figure 1, it is divided into several ond-order active Butterworth filter for the scan response of the PLC. The end functional blocks. The circuitry is antialiasing. The components are result is a black box that’s small shown in Figure 2 (p. 24). selected for passing speech while ade- enough to fit inside existing instru- The UART0 and UART2 interfaces quately rejecting the sampling frequen- ment panels for a well deserved and provide two independent serial ports cy of 11.025 kHz and its harmonics. painless instrumentation upgrade. for connections to a PLC/PC and a The resulting output is fed to an audio serial Bluetooth dongle, respectively. I amplifier designed around an LM386 GAUGES & SENSORS provided a 5-V supply for the Blue- IC. The audio output can be connected Industrial diesel engines typically tooth dongle port. The Bluetooth don- to a walkie-talkie VHF unit’s micro- use electrical resistive sensors called gle port is wired as DTE, whereas the phone input (through an attenuator) for senders to sense fluid temperatures PC/PLC port is wired as DCE. communicating alarm messages. Most and pressures. These are used along To measure rotational speed, signal- VHF units that support hands-free with corresponding analog electrical shaping stages are provided for mag- headsets will then automatically gauges so information can be dis- netic pick-up RPM sensors. These switch to Transmit mode through played on a panel. To sense engine work over a wide range of sensor input their internal voice-activated circuitry. speed (RPM), magnetic pick-up sensors voltages from 0.5 V to beyond 50 V. The power supply has been designed are mounted close to the crankshaft gear These stages have been designed with to operate from 9 to 40 VDC so that teeth. Revolutions of the crankshaft gear high HF noise rejection to ensure that the circuit can be powered from both cause the change of magnetic flux across clean digital signals are generated for 12- and 24-V systems (automotive gear teeth. This in turn causes an AC feeding to TimerA input lines. /industrial supply). Note that 6.5 V is voltage to be generated by the sensor The analog gauges are read via the used for the audio subsection, whereas a whose frequency is directly proportion- microcontroller’s A/D port lines 5-V digital logic supply is for the al to engine RPM. Analog or digital through voltage divider networks. HF M16C/62P SKP microcontroller board RPM gauges provide the readout. bypass capacitors at signal inputs and logic circuits. Adequate heat sinking Conventional sensors are robust and shunt noise transients. Schottky diode must be provided for the LM317 regula- designed to work in an engine’s oper- clamps provide protection against tor. You can use an SMPS converter in ating environment. The magnetic overvoltage/reversed connections. place of the LM317 linear regulator for pick-up sensors also work reliably in Channel AN2 is used for measuring better conversion efficiency. the oil-splashing environment of the the supply voltage (12/24 V) required If your circuit is going to be used in crankcase. However, senders are non- for ratiometric measurements. Chan- an automotive or electrically noisy linear and designed to be used only nel AN3 is configured as a 0- to 5-V environment, you must observe with matching panel meters. The out- input to directly connect to digital pres- EMI/EMS design issues. The electronics put voltage of magnetic pick- must withstand load-dump con- up sensors also varies with the ditions, surges that result from TXD0 rate of change of magnetic flux UART0 To PLC/PC the switching of inductive loads, (i.e., RPM) and their air gap RXD0 Interface and other disturbances on the

with the gear teeth. TXD2 UART2 To serial Bluetooth electrical lines. Although it Multipurpose digital pressure RXD2 Interface dongle greatly helps to use the gauges (e.g., theWWW.GiURUMELE.Hi2.RO Keyence AP-30 TA1IN M16C/62P microcontroller with Signal Magnetic pickup series) mark a new develop- TA2IN shaping (RPM) sensors (2) superior EMI/EMS specifica- ment in pneumatic pressure tions, suppressing noise and its Analog gauges (4) AN2-7 A/D Voltage

sensors (see Photo 1). These M16C/62P SKP Board (0–5 V) input (1) coupling to other stages is best (P10) dividers, gauges provide a direct digital protection Control voltage (1) carried out close to the input readout of positive or negative itself during board design. DA1 Amplifier air pressure, which can be very Low-pass filter Speaker Design the PCB with a gener- useful for determining, say, ous ground plane, good power- 5 V (Logic) Power supply Supply clogging in a filter element or 6.5 V (Audio) voltage supply decoupling, and low- the turbocharger boost pres- impedance noise bypass capaci- sure. For remote sensing, they Figure 1—I neatly broke up the system into distinct blocks. tors where the signals enter the

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 23 2612014lohani.qxp 11/2/2006 9:50 AM Page 24

PCB. I used shielded cables for con- ulator to optimize the critical stages where switching currents of several necting to the sensors and a balanced for high noise immunity (see Photo 2). hundred amperes are common! transient suppression filter at the I have successfully used the circuit power supply input. I also used Linear interfaced to a PLC-based monitoring CONSTRUCTION Technology’s LTSpice/SwCAD III sim- system in a railroad environment, Building the prototype was fairly

a) Analog section

b) Digital section

WWW.GiURUMELE.Hi2.RO

Figure 2a—The analog subsections comprise voltage divider networks, a low-pass active filter/amplifier, and a power supply. b—The digital subsections comprise two inde- pendent serial ports and signal-shaping stages for magnetic pickup (RPM) sensors.

24 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612014lohani.qxp 11/2/2006 9:50 AM Page 25

Bluetooth profile. Its Bluetooth radio is rated for Class 2, with a communi- cation range up to 25 m. The power requirements are 5 V at 150 mA. I chose the dongle for its simplicity. The defaults for its communication parameters are factory set, and it does- n’t require any configuration com- mands. Pressing the Blue button on the dongle enables nearby Bluetooth devices to perform device and service discovery and pair up with it. A single multicolor LED indicates its status. Once paired, it appears to the micro- controller as a simple serial device.

MCU SOFTWARE The software for the M16C/62P microcontroller was written in C lan- guage so it could be compiled with the Renesas HEW IDE. The program has two main sections: the sensor acquisi- Photo 2—I tested for noise rejection. The output signal of the magnetic pick-up signal-shaping stage remains clean tion mode loop and the calibration despite an input signal of only 0.7-VPEAK with superimposed noise. mode loop. In the former, a number of tasks are performed sequentially. First, simple (see Photo 3, p. 26). I made the header. I used a Kingene BT210S serial the engine’s speed is measured. Two connection to the SKP board through Bluetooth dongle for wireless connec- channels for simultaneous measure- ribbon cables soldered to a 2 × 25 pin tivity. This dongle provides the SPP ment are provided (RPM1 and RPM2).

New Catalog!

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 25 2612014lohani.qxp 11/2/2006 9:50 AM Page 26

The TA1IN and TA2IN connect to Supply, input lines that receive Ground, and Sensor, the processed speed-sen- respectively. The read- sor signals are configured ings shown by the gauge in Event Counter mode. are a function of the sen- A 100-µs clock-tick accu- sor voltage and the sup- mulator (ticks_100us) ply voltage (i.e., a ratio- controls the gating period. metric reading). Thus, The timer interrupt of the program processes TA0 updates this accu- the ratio of voltage mulator every 100 µs. across the sensor to the Following this, the analog supply voltage to com- measurements are carried pensate for variations in out. The ADC operates in the supply voltage. This Single Sweep mode. is then converted to the Other than the two chan- gauge reading using a nels used internally in transfer function. The the M16C/62P SKP board, program can cater to any the six remaining analog sensor whose transfer channels of P10 are used Photo 3—The Bluetooth link is used to connect to a laptop via the Kingene BT210S serial function can be repre- to measure external ana- Bluetooth dongle. The second serial link hooks up to a PLC. The sensors are connected sented by a mathemati- log signals. through the screw terminal blocks. Also note the small speaker for playing WAV files at cal equation. The trans- In automotive and rail- 11.025 kHz. fer function for an exist- road environments, the ing sensor can be deter- nominal battery voltage may vary con- therefore measure a reference current mined using Calibration mode and a siderably depending on the battery’s in addition to the current through the spreadsheet program. state of charge and the switching of sensor. The industrial pressure/tem- The RPM values and the calculated heavy loads. The electrical gauges perature gauges have three pins that gauge readings are then converted to

WWW.GiURUMELE.Hi2.RO

26 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612014lohani.qxp 11/2/2006 9:50 AM Page 27

delimited by STX and ETX characters. This makes it fairly easy to pass on the data to any PLC capable of receiv- ing block text data in its data memo- ries. A BREAK signal is also sent on UART0 before the first data packet to initialize the communication buffer and data rate setting of the PLC. This protocol was used to interface with a Keyence KV-16 PLC. Small changes may be required for a PLC having a proprietary protocol. The specifics are usually detailed in the PLC’s manual. Finally, the resources in the M16C/62P make it fairly easy to implement alarm annunciations based on recorded speech messages. This is implemented by the wavplay() func- tion in main(). For the prototype, I kept the programming simple for min- imal speech feedback. If any alarm Photo 4—I used Microsoft Excel to determine trend-line equations for calibration. condition has been recorded in queue, the yellow LED on the M16C/62P SKP board lights up. If you press the corre- an ASCII data packet. The data packet nels (000–999) in the following order: sponding S2 switch, the system plays is a fixed-length string containing back the necessary sequence of WAV ASCII data for the two RPM channels . The data packet files to build the error annunciation (0000–9999) and the six analog chan- is sent through UART0 and UART2 message. Pressing the S3 switch clears

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 27 2612014lohani.qxp 11/2/2006 9:50 AM Page 28

the error queue. Listing 1—These are transfer functions of the channels pasted in the code. The program enters Calibration mode when you press and hold S1. In switch (scanloop) the Calibration mode loop, the value { case 0: of the analog channels read is dis- // Process Gauge across AN4 played in decimal form. Pressing S2 // Cooling Water Temperature gauge cycles through the channels AN2 ratio_accu = ad4_value * 1023.0; through AN7. The absolute values are ratio_val = (unsigned int)(ratio_accu / ad2_value); gauge_read = (unsigned int)(0.0002*ratio_val*ratio_val - displayed for voltage measurement 0.3383*ratio_val + 158.19); channels AN2 and AN3. Ratiometric // Suppress Error readings if no sensor is connected values are displayed for channels AN4 if (gauge_read > 150) // obviously absurd! through AN7, which are used to con- gauge_read = 0; if (gauge_read >= LIM_WATERTEMP) nect to gauges. You can exit Calibra- err_watertemp = TRUE; tion mode by pressing the RESET break; switch. case 2: // Process Gauge across AN6 SPEECH SUPPORT // Lubricating Oil Pressure gauge The simplest speech files to deal ratio_accu = ad6_value * 1023.0; with are in WAV format, and they ratio_val = (unsigned int)(ratio_accu / ad2_value); consist of uncompressed audio data eq_value = (0.0004*ratio_val*ratio_val + 0.0772*ratio_val - 4.7464); // This equation can yield negative value with no sensor after a header block. To use WAV files // Check and then assign value in the HEW environment, I concluded if (eq_value > 0) (after an extensive search on the Inter- gauge_read = (unsigned int)(eq_value); net) that it would be best to include else gauge_read = 0; the WAV file audio data as a data array if (gauge_read >= LIM_HIGHOILPR) of constants in a separate C source err_highoilpr = TRUE; file. In a 2002 Freescale Semiconduc- // Lubricant pressure is checked once engine has at-least idle RPM tor application note entitled “Audio if (tim_rpm >= IDLE_RPM) { if (gauge_read <= LIM_LOWOILPR) Reproduction on HCS12 Microcon- err_lowoilpr = TRUE; trollers,” Grant More describes using } this approach for HCS12 microcon- break; trollers. The note is accompanied by // code for other case conditions has been removed in this snippet } essential software that includes a DOS executable file for conversion. To ensure the clear and correct pro- nunciation of words, I downloaded the be stored for playback. ed to the system. At different bath required WAV files from Merriam- temperatures (measure with an accu- Webster’s web site (www.m-w.com). I CALIBRATING THE UNIT rate mercury thermometer), the read- then opened the files in Windows In comparison to existing analog ings shown on the M16C/62P SKP’s Sound Recorder and resampled in the gauges (whose needles can get stuck LCD are noted. (The system must be format PCM 11025 Hz, 8-bit, Mono so and are also affected by vibration), the in Calibration mode.) The readings that the Freescale utility could process readings for a properly calibrated sys- and corresponding temperature are them. Freescale’s utility neatly tem can be relied upon for repeatabili- used to plot a graph in a spreadsheet extracted the audio data producing C ty and accuracy. A calibration proce- program such as Microsoft Excel (see data array files. I edited the C source dure must be followed once to cali- Photo 4. Select the Display Trend-Line files created by renaming the array brate the analog inputs. The analog option and an appropriate curve fit and removing the #pragma directive channels must be connected to the such as second-degree polynomial. from the top ofWWW.GiURUMELE.Hi2.RO the file. In this way, I required gauge inputs. The system Excel will then display the relation included 12 WAV files (in C source voltage (12 or 24 V) must also be con- between temperature and reading as a format) in the source code. nected. There is no need to disturb the mathematical equation. This equation I was very impressed with the existing analog panel circuitry. Just is the transfer function for the channel quality of the WAV files played back “tap” the required signals from the that should be pasted in the source by the M16C/62P even though all of panel! code (see Listing 1). the files had an 11.025-kHz sampling As an example, assume that the frequency. This helps in giving a very temperature gauge channel is to be PC USER INTERFACE professional user interface to the calibrated. The temperature sensor The PC user interface was written project. The M16C/62P’s large flash must be kept in an oil bath and heated in Visual Basic. The normal Visual memory enables many more files to while remaining electrically connect- Basic runtime files must be present on

28 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612014lohani.qxp 11/2/2006 9:50 AM Page 29

tory. You can open this file directly in Microsoft Excel for analysis. Even without hardware, the Visual Basic terminal program can be run in Local Simulation mode. Feel free to experiment with the scrollbars and data logging capabilities to get used to the user interface. The display is opti- mized for 1,024 × 768 mode. The meter faces may be replaced with images of meters present in the existing analog panel to give a realistic feel. I chose the meters accordingly and edited the digital camera photo- graphs of the meters in Adobe Photo- shop to remove the needle. Then I smoothened out the images using the Photo 5—Take a look at the PC user interface. Several of the gauges shown in Photo 1 are recreated here as virtu- Gaussian blur transformation and con- al gauges in an intuitive instrument panel. verted the images to GIF files with a transparent background. I have also the PC or can be downloaded from ed on the Circuit Cellar FTP site. included these GIF files so that you Microsoft’s web site. The program The program displays the readings can create similar files for other meter uses a free third-party lightweight in analog type meters, which are easy faces. The resulting interface is shown LED control (akLED). The control files to read. It works with serial cable or a in Photo 5. must be in the current directory. Bluetooth SPP emulation port. The Alternately, run the akLED.exe con- program also has data-logging capabili- GOING MOBILE trol installation program. The exe- ties and writes the data log to the Bluetooth connectivity greatly cutable and source code files are post- DIPlog.csv file in the current direc- extends the range of devices that can

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 29 2612014lohani.qxp 11/2/2006 9:50 AM Page 30

provide the user interface for the digi- and access to the phone’s memory tal instrument panel. I was particular- stick and SD card. You’re limited only ly excited about using my new Sony by your imagination when producing Ericsson W800i mobile phone for this an intelligent, sophisticated display. purpose. In fact, any mobile phone Bluetooth consumes a fraction of that has Bluetooth and J2ME support energy as compared to Wi-Fi (IEEE (MIDP 2.0) can be programmed with a 802.11 b/g) while having a respectable Java MIDlet to provide the functional- data rate, high immunity to interfer- ity of the user interface while retain- ence, and a typical working range of ing its normal functions. MIDP 2.0 approximately 10 m. This makes it also includes a rich API set for high- ideal for battery-powered mobile appli- Photo 6—The user interface on my Sony Ericsson resolution graphics, multimedia, con- cations. On the software side, the W800i phone is Bluetooth-enabled. nectivity via SMS, MMS, or the ’Net, standard SPP profile provides serial port emulation. This simplifies the software considerably. As far as the circuit hardware is concerned, I kept everything simple by using a Blue- tooth dongle, which appears to the cir- cuit as a serial port device while its internal hardware and firmware encap- sulates the Bluetooth stack and radio implementation. To demonstrate the concept, I wrote a small Java MIDlet. A minimal MIDlet is required for performing Bluetooth device and service discov- ery, reading and parsing the ASCII packet data received from its SPP peer, and implementing a Canvas to display the panel data. Java can then add other bells and whistles such as data logging, SMS/MMS support (and, of course, graphical panel meters in a similar way to what I described for the Visual Basic application). Sony Ericsson’s 2005 article entitled “Connecting to a GPS receiver using Bluetooth (JSR 82)” includes bundled Java source code for such an applica- tion. This was what I was looking for. It includes code for discovering and connecting to a Bluetooth SPP device, and then parsing and displaying the data. However, it is customized for a GPS unit that generates NMEA data packets. In my case, the fixed length ASCII delimited data packets are WWW.GiURUMELE.Hi2.ROmuch easier to parse. The J2ME source consists of five well-organized Java modules. It is only necessary to rewrite two of these modules: the one responsible for data parsing (GPSReader.java) and the one that provides a canvas to display the acquired data (GPSCanvas.java). It took me just a few hours to write my customized modules. I compiled the source to Java binaries using Sun’s free

30 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612014lohani.qxp 11/2/2006 9:50 AM Page 31

Java Wireless Toolkit and then down- Tricks, and Code” section.) Kingene Technology Corp. loaded it to my mobile phone. The www.csr.com/comps/kingene.htm program worked flawlessly! SOURCES LTSpice/SwCAD III Simulator Linear Technology, Inc. APPLICATION DEVELOPMENT akLED Control www.linear.com The Java source code for the mod- akTools ules that I wrote, as well as instruc- http://www.rentmaster.co.nz/aktools/ M16C/62P Microcontroller tions for compiling the code, are avail- akled.htm Renesas Technology Corp. able on the Circuit Cellar FTP site. AP-30 Self-contained pressure sensors www.renesas.com These should help you develop a Keyence Corp. working J2ME application on your Java Wireless Toolkit www.keyence.com mobile phone for personal use. Note Sun Microsystems, Inc. that Sony Ericsson’s software license BT210S Serial Bluetooth dongle http://java.sun.com/javame/downloads/ prohibits me from reproducing part of the source code that’s available on its web site (so as to make a complete project) or to include the Java binaries. The Bluetooth mobile phone inter- face implemented in this project pro- vides a new generation of sleek and intelligent displays to any microcon- troller with a UART (see Photo 6). Working with a 24-bit color LCD and the connectivity resources in my mobile phone, I wondered why I had been spending money on graphical LCDs and keypads for my projects when I could have achieved better results by running a small Java MIDlet on my mobile phone. Welcome to the world of embedded programming on mobile phones! I

Samir Lohani ([email protected]) is a mechanical engineer working for Indian Railways. Control systems and shop floor automation are among his areas of interest. In his spare time, Samir works on electronics and embedded programming projects.

PROJECT FILES To download code and additional files, go to ftp://ftp.circuitcellar.com/pub /Circuit_Cellar/2006/197.WWW.GiURUMELE.Hi2.RO

RESOURCES G. M. More, “Audio Reproduction on HCS12 Microcontrollers,” AN2250/D, Freescale Semiconductors, 2002. Sony Ericsson, “Connecting to a GPS receiver using Bluetooth (JSR 82),” 2005, http://developer.sonyericsson. com. (Refer to the “Java ME—Tips,

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 31 2612018Warren.qxp 11/2/2006 9:59 AM Page 32

FEATURE ARTICLE by Kyle Cameron, Jeremy Warren, Shane Reierson, Chris Rittaler, & Nick Brady Multitiered Security System Use this multitiered PIC18F4580-based security system to bump up the security in your home or office.You can switch the system back to normal mode with only a few clicks of your mouse.

Advancements in modern technology plate) and voice passwords. Communi- In a demonstration at Camosun College, demand expandability. Take your PC for cating through an Ethernet controller, for example, we used a pulse-modulated example. Anyone with any kind of com- the server provides all of the modules solenoid that pulled a bar out of a lock- puter knowledge would be more inclined connected to it with the information ing mechanism when a user was granted to buy a PC with empty slots over a needed to determine whether you access. The bar was pushed back in once similar system that was jammed full. should be granted access. At the same the user moved through the door. Now, when that graphics card time, it provides a responsive GUI to In the following sections, we’ll comes out using PCI Express, you can interact with the server administrator. explain how our system is interfaced pop it right in there. When Windows Once you’re granted access at a given to the PC and how it’s set up for Vista comes out, you can run it no access point, you will be allowed to expandability. We’ll also provide you problem! Need more speed? Throw in enter (a door is unlocked, an alarm is with information about some very pop- some more RAM. OK, we got a little disabled, or some kind of other lock is ular new technologies and show you excited there. What we’re trying to say disabled). This is where some of the cus- how easy they are to add to your design. is you will have this PC a lot longer, tomizable functionality comes in. We you’ll spend less money, and you won’t set aside digital I/O for the purpose of MODULAR DESIGN have to buy an entirely new system driving a solenoid or electronic lock that Each individual module consists of every time you want to add an option. can be chosen to fit specific applications. two to four PCBs (called submodules) We designed a modular (hardware and firmware) security system that offers comparable freedom (see Photo 1). In this article, we’ll describe how we did it.

SYSTEM OVERVIEW Our security system incorporates a “multitiered” design that includes mod- ules with radio frequency identification (RFID), fingerprint authentication, and voice recognized password authentica- tion. Wow, that was a mouthful. To put it simply: you swipe your RFID card (or keychain, finger ring, or even an implant in your hand!), and you’re identified using a 4-byte (hex) code. After the sys- tem identifies you,WWW.GiURUMELE.Hi2.RO it can either authen- ticate your identity using a fingerprint or a voice-spoken password or just simply grant you access. Every time you are granted access, you will be logged in a database located on the central server. The central server is the brains of the operation. In its database, it con- tains all of the 4-byte codes used to Photo 1—Take a look at our complete display module. Looking at the top left image, the voice recognition board is identify users and optionally the users’ on the bottom left. The RFID receiver board with the antenna attached is in the middle. The fingerprint board is on the fingerprint information (called a tem- bottom right. The Bioscrypt fingerprint module is shown inside our display case. The main board is on the top right.

32 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612018Warren.qxp 11/2/2006 9:59 AM Page 33

that all connect together to form a best part is that it’s so cool and so complete system. These PCB boards easy to implement into your design! include a main board, an RFID board, a IB Technology’s MicroRWD trans- fingerprint board, and a voice recogni- ceiver works with tags in a number of tion board. Every embedded module con- different forms. This receiver module tains at least a main board and an RFID has an extremely simple serial inter- board and optionally a fingerprint and face, and development kits are avail- voice recognition board (see Photo 1). able for around $220! Using this devel- Now, why not just have all of this Photo 2—We used an eight-pin header to make a pro- opment kit, we had RFID working in on one board? The most important gramming cable that included an RJ-11 connector for our project in about 4 h! Great choice! in-circuit programming and a DE9 connector for access reasons are expandability and easy Our RFID board consisted of power to the USART on the PIC18F4580. maintenance. Think of the PC analo- supply filtering and a spot to insert gy we used earlier. Wouldn’t you like the RFID receiver. That’s it! a security system that will enable you For the sometimes feared task of pro- to add new, more secure technologies gramming our microcontroller after it VOICE RECOGNITION BOARD to in the future? Furthermore, would was on the PCB, we composed a simple To add to our project’s cool factor, you rather replace a main board or the cable that implemented an RJ11 connec- we included voice-recognizable pass- entire module if something were to go tor and a DE9 connector (see Photo 2). word technology instead of an old-fash- wrong? Doing this enabled us to program a boot- ioned keypad. To do this, we needed This is a very important concept in loader onto the PIC18F4580 (using an in- some form of speech recognition to con- any design. Just like all of our teachers circuit debugger) and then simply use vert the spoken password into a num- here at Camosun College have taught the DE9 connector to bootload our code. ber that we could use in our code. us time and time again: keep your We were already dealing with designs modular! Doing so makes it FINGERPRINT BOARD Microchip parts, so we decided to easy to add new options in the future, As you may already know, finger- check out what was offered in this reuse designs, troubleshoot problems print sensing and authentication is not field and found exactly what we were quickly, and replace failed parts at a exactly an easy task. It takes very looking for. We decided to go with minimal cost! Shall we go on? complicated algorithms and lots of Microchip’s speech recognition processing power. We had only three firmware for use on the dsPIC series of MAIN BOARD months to design and build this system, microcontrollers. More specifically, Our main board includes a Microchip so we decided to go with something that we used the dsPIC30F6014A digital Technology PIC18F4580 microcon- could perform all of the sensing and signal controller for our system troller, a Microship ENC28J60 Ethernet authenticating on its own. However, if because a development kit featuring controller, and connectors for extra I/O you take the time to try and find some- this chip was available at Camosun and a programming cable (see Figure 1, thing like this that can be implemented College where we study. p. 35). The PIC18F4580 controls com- into an embedded system, good luck! Like the fingerprint module, we munication to all of the peripherals After several days of researching, made the choice to dedicate the (the Ethernet controller, the fingerprint emailing, and making numerous long- dsPIC30F6014A to voice recognition sensor, the RFID Module, and the voice distance phone calls, we came across and interface it with the PIC18F4580 recognition board) and grants or denies Bioscrypt, an Ontario-based provider microcontroller, thus saving our micro- access based on the security level. of finger scan technology. Write this controller’s precious RAM and process- The ENC28J60 Ethernet controller down: Bioscrypt offers complete ing power for future developments. is a handy little chip with a SPI, on- embedded systems that incorporate Once the code was developed and board CRC checking, and various Texas Instruments DSPs and can talk working, we simply designed a PCB to receive filters to kick out all of those to your microcontroller through a sim- host the dsPIC and audio codec, there- annoying broadcasts such as ARPs and ple RS-232 interface! by creating the voice recognition board. ICMPs generated by a PC, as well as We used a Bioscrypt MV1210 finger- any packets thatWWW.GiURUMELE.Hi2.RO aren’t destined for print module in our system. All we STATE MACHINE the MAC of a particular module. The needed for our fingerprint submodule We’ve warmed you up on the hard- SPI greatly reduces the I/O needed for was an RS-232 level translation chip and ware, but now you’re probably won- such a chip and simplifies its imple- a connector into which we could plug dering how we control all of this. mentation. All we needed to do was the sensor module. How easy was that? Remember when we said that you send it commands using the should make your designs modular? Microchip C18 compiler’s SPI func- RFID BOARD Modularity is essential when it comes tions (through four wires and power Radio frequency identification is to coding, especially when you’re and ground) and we were up and run- becoming more and more popular. You working with a team of designers. ning. We were sending packets after probably saw the guy in the news that How else are you going to divide up only a few days of playing around! had a tag implanted in his hand! The the work? How will you (or someone

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 33 95.qxp 8/9/2006 2:12 PM Page 1

#include

er(c)) putc unsigned pp ha su r (i (‘ f U i ’) ; , k u a + e + r ;

b i f

)

(

i

F f

i

; (

i s

+ n,u,l,d,p; s

p +

l

O

u d

o ,

n

)

c

E

w

#

t

(

( c

r

e

)

=

) a

r

h =

(

c

t c

c u ) (

)

We make f i

p

;

u

)

(

t

r

c main() { a h

h a

c

t r

( e ; if (isdigit(c)) p

l

#include g ’

)

p

u ) ’ t c ? ‘ h ( a chips think r ,

l =

+

c

+

,

p } { +

}

+ ; ; + n +

i

n

)

t 1

(

c e ; l i h

HI-TECH Software delivers w the industry’s most reliable embedded software development tools and for over 12 different 8-bit, 16-bit, 32-bit, and DSP chip architectures!

As one of the top five compiler vendors with the largest variety of supported chip architectures, HI-TECH Software’s product range is renowned for delivering cutting-edge technology and robust results for development teams worldwide.

With over two decades of industry HI-TECH PICC™ Enterprise Edition HI-TECH C® for HOLTEK MCU experience, our long-term HI-TECH PICC™ HI-TECH C® for ARClite™ relationships with leading chip manufacturers ensure that our HI-TECH PICC-18™ HI-TECH C® for XA products are tightly attuned to new HI-TECH dsPICC™ HI-TECH C® for Z80 technological releases. HI-TECH C® for ARM® HI-TECH C® for H8/300 Whichever processor family you HI-TECH C® for 8051 HI-TECH C® for 68HC11 are targeting, HI-TECH Software’s C compilers can help you write better HI-TECH C® for MSP430 code and bringWWW.GiURUMELE.Hi2.RO it to market faster.

To see how our compilers can improve your productivity, download a demo now at www.htsoft.com/downloads/demos.php.

HI-TECH C® is a registered trademark of HI-TECH Software. HI-TECH PICC™, HI-TECH PICC-18™ and HI-TECH dsPICC™ are licensed exclusively to HI-TECH Software by Microchip Technology Inc. All other trademarks and registered trademarks are the property of their respective owners.

HI-TECH Software LLC 6600 Silacci Way Gilroy, CA 95020 USA Ph: 800 735 5715 Web: http://www.htsoft.com/ SOFTWARE 2612018Warren.qxp 11/2/2006 9:59 AM Page 35

else) add code later on down the road? waits for either a command from the built the state machine. Other team Think about this before you start typing! server or an RFID tag to enter the members worked with a peripheral Let’s take a look at the code for each field. Once something happens, it until it functioned properly and then implementation file. Doing so should determines how to deal with that submitted their code to the state help you understand how we broke event and then goes into a state that machine builder for implementation. everything up. takes action. This way any addition to Our firmware consisted of a main the system will simply require an FINGERPRINT FIRMWARE state machine used to control all of implementation file (with the neces- Most of the complex code for the the different events in the embedded sary functions) to make it work and a fingerprint module was already done module. We used external files that new state to take action. for us in the MV1210, so implement- were included in our main file for Compared to using if and else ing this thing was rather simple. The each peripheral. Our main state statements, state machines are very implementation file consisted of a machine simply had to call functions good examples of modular code when series of functions to serially talk to from other files to tell the Ethernet it comes to a control system. This is the fingerprint board according to the controller to send packets or to because they are easier to understand, serial protocol discussed in the docu- request verifications from the submod- and they facilitate code additions ments provided with the SDK. ules. As you can see in Figure 2 (p. 36), almost seamlessly (if coded properly). We were able to send the fingerprint the state machine just sits around and We divided up the work. One person board commands to enroll and transfer

WWW.GiURUMELE.Hi2.RO

Figure 1—The main board’s power supplies are at the top. The Ethernet connectivity is shown on the left side. The main processor and I/O connections are on the right.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 35 2612018Warren.qxp 11/2/2006 9:59 AM Page 36

and to verify users. This represents the backbone of our enables us to scan a user’s fin- Start-up security system. To do this, we ger and save the template in a No tag in RF field needed a method of providing No command to recieve buffer on the PIC18F4580 responsive interaction with the

(enroll and transfer). This tem- Command received user and at the same time reli- plate can then be sent to the from PC? RFID Tag in RF field? able communication with server in a single UDP packet every module connected to it. and saved in the database. Command received Tag in field Once we had a template to INTRO TO THREADING work with, we used the verify Process user, Get UID from A daunting task for any Process validating voice and RFID transponder command to ask the MV1210 command fingerprint if necssary and send to server embedded developer is creat- to scan the finger and then ing a GUI that can interact compare the scanned image Enable access with the embedded portion of to security control Y Did user pass? with the template we provid- point and reset a design. When developing a ed. This hardly even touched all data buffers GUI to support your embed- N the MV1210’s capabilities, but ded application, it is impor- Display error/denial message to it did exactly what we needed LCD and reset all buffers tant that your communica- it to do. The main functions tion does not crash your GUI used by our state machine Figure 2—An RFID tag in the field starts the authentication process. At the same (or you’re ). included these two functions time, the server can send commands to lock down and reset the embedded module. A handy way to do this is to and a function to ask the fin- use multiple threads. gerprint board if it was ready to talk word library builder (and some code to Multitasking systems use time slic- (or if it was busy). interface the dsPIC30F6014A to the ing to appear to run more than one PIC18F4580). process at a time. Today’s processors RFID FIRMWARE Communication from the PIC18F4580 are fast enough that any human (with Probably the simplest of all imple- to the dsPIC30F6014A was achieved the exception of the man) can’t mentation files, the RFID modules we using a simple protocol that we devel- tell. This gives you a powerful tool for used required wieldy 1-byte com- oped. The PIC18F4580 first acquires the building a responsive GUI that can mands. Our implementation file 4-byte password from the server, sends it maintain communication with your included one function used by the state to the dsPIC30F6014A, and then pulls an embedded devices. machine to get the ID from the tag. ENABLE line low. As soon as the Most operating systems offer devel- The RFID receiver module indicates dsPIC30F6014A sees the ENABLE line opment frameworks supported by that there is an RFID tag in the field go low, it attempts to acquire the 4-byte SDKs, thousands of classes, and a by pulling the CTS line low. Our main voice password from you. If successful, strong online support network. state machine polls this pin to see if the dsPIC30F6014A compares these Microsoft’s newest framework (.NET there is a tag in the field and waits for bytes with the ones received from the 2.0) is an example. a packet from the server at the same PIC18F4580 and then returns a pass or The first step in developing a multi- time. If there is a tag present in the a failure. If unsuccessful, the threaded GUI is to define a front end field, the GetUID() function is called. dsPIC30F6014A will time out and send and a back end. The simplest way to GetUID() sends a command to the an error byte back to the PIC18F4580. do this is to make all user interaction RFID receiver requesting it to send All we needed in terms of an imple- the front end and everything else the back the contents of its memory loca- mentation file was a function to back end. If you think of these two tion containing the unique ID from request a voice verification from the ends as your threads, you could say the RFID tag in the field. The state dsPIC30F6014A with the password to that your back end thread listens for machine then deals with this ID by compare with as a parameter. This information from your embedded sending it to the server and requesting function then returned pass or failure application, while your front end the information associated with the based on the result of the verification. thread interacts with the user. user who ownsWWW.GiURUMELE.Hi2.RO that 4-byte number. You’re probably thinking: “OK, I see SOFTWARE the genius behind these words, but VOICE RECOGNITION FIRMWARE By now, you’ve heard a lot about the what about when the two threads need The dsPIC30F6014A had to be pro- server and what it does. But how to communicate?” Not only is this a grammed with our customized exactly does it handle so many things common issue in threading, but it’s also firmware, so we needed to write the at once without crashing? To say the our second step: thread synchronization. program and get it working before we least, it’s a UDP-sending-and-receiv- Thread synchronization can be done could make an implementation file. ing, database-creating security in many ways, so it’s important to iden- The code we developed for use with machine! Using Microsoft Visual C# (on tify which type of cross thread commu- the dsPIC30F6014A was formed using the .NET framework) in all its glory, we nication is needed. Some examples a word library built with Microchip’s were able to create this machine which would have one thread wait for another,

36 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612018Warren.qxp 11/2/2006 9:59 AM Page 37

pass data from one thread to another, or you expand the back-end thread idea finds embedded systems and program- stop a thread based on data from anoth- into many threads that handle com- ming fascinating and enjoyable. er. All of these thread synchronization munication with each module in need applications are valid; however, what’s of information from the server, you Jeremy Warren (jeremywarren@ often used in embedded control GUIs is can begin to see how such a simple shawlink.ca) is an electronics engi- the need to block (pause) one thread process can be expanded to solve com- neering technologist who received his until another thread completes or a plex problems. Each back-end thread certification from Camosun College. certain amount of time passes. either waits for a response from the He is a volunteer member of the Take an RFID scan. You may have a module in question or times out. This Canadian Coast Guard Auxiliary and button in your GUI that tells your RFID will not affect the main thread. It will spends his spare time playing with scanner to return the RFID of a card in result in a very responsive GUI. home control and automation. its field. When you press the button, The server GUI is written in C# Shane Reierson (reiersonshane@shaw. your GUI will send the command and with Visual Studio .NET. We choose ca) is a graduate of Camosun College’s wait for a response. Your options are to both C# and Visual Studio .NET computer engineering technology pro- block your GUI for a certain period of because we were under a tight three- gram. He is currently working toward a time or until the back end thread month deadline. It is often true that degree in computer engineering. His returns the data. This is an example of you can write a tighter GUI (or any professional interests include automa- event synchronization, where one thread code for that matter) using C or even tion, security, and system control. waits for the other to raise an event. C++ if you have the time. But when In the front-end thread, you must you’re on a tight schedule, it’s hard to Chris Rittaler (chris_rittaler@hotmail. declare a thread signal: ignore a visual editor, the support of com) completed the electronics engi- thousands of classes, and online devel- neering technology program at Camo- EventWaitHandle frontEndSignal; oper support. sun College. He is currently enrolled The .NET framework provides easy- in the electronics engineering bridge The following is for the back end thread: to-use functionality for handling con- program at Camosun College. His nectivity and data transfer over the technical interests include microcon- EventWaitHandle backEndSignal; ’Net. Standard support for UDP, TCP, troller circuits and vacuum tube cir- and FTP is all there! But standardized cuits (guitar amplifiers). A signal can be thought of as a state support is a double-edged blade. And machine with three basic states: Set, although it’s easy to use and quick to Nick Brady, an electronics engineering Reset, and Wait. Set enables the own- implement (we had the server sending technologist, graduated from Camo- ing thread to run. Reset blocks the and receiving UDP packets in about sun College in 2006. He lives with his owning thread. Wait blocks until 30 min.), you may not find it when wife in Port McNeill, British Colum- another thread signals it to continue you need a lower level of control. bia. His technical interests include or a period of time has passed. embedded systems, trouble-shooting Now back to our example! Our user FUTURE DEVELOPMENTS hardware, and things with flashing has requested an RFID, and we are The design we’ve used for our board lights. You may contact him at willing to wait 5 s for someone to scan layouts and state machine enables us [email protected]. a RFID card. to add new features to our system eas- ily in both hardware and software. PROJECT FILES frontEndSignal.WaitOne(5000, false); Future additions may include things To download the code, go to ftp://ftp. like facial recognition, a digital cam- circuitcellar.com/pub/Circuit_Cellar/ The 5000 is in milliseconds, and the era for monitoring access points, and 2006/197. false is a default. Prior to telling the triggers for indicating special events. thread to wait, we would have sent We still have error conditions to be the command. Now, in the back end exercised and real-world testing to take SOURCES thread, we send our command and place before we have a finished prod- MV1210 Fingerprint module either receive theWWW.GiURUMELE.Hi2.RO RFID or not. If we uct. We hope this article will help you Bioscrypt, Inc. receive the data successfully, we run: start designing your own security sys- www.bioscrypt.com tem. There are some very cool tech- MicroRWD Transceiver backEndSignal.Set(); nologies out there that are getting easi- IB Technology er and easier to implement! I www.ibtechnology.co.uk Our main thread can display the RFID. Or, after 5 s, a timer will expire and Kyle Cameron ([email protected]) dsPIC30F6014A Digital signal con- display an error message. completed his electronics engineering troller, ENC28J60 Ethernet controller, This threading concept is the basis technologist diploma at Camosun Col- and PIC18F4580 microcontroller for how our server handles talking to lege. He is currently studying for a Microchip Technology, Inc. the various modules connected to it. If degree in electrical engineering. He www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 37 2612004-nisley.qxp 11/2/2006 10:09 AM Page 38

ABOVE THE GROUND PLANE by Ed Nisley

Filter Figures Ed revisits a filter design he worked on back in 2003, but this time around, he has better instruments. Read on for information about filter shapes, flatness, and trade-offs with skirt steepness. He also describes the effect a wider filter has on the output in the application.

The power-line frequency monitor lives on a separate board. filter’s components and produces the project I presented in my December That 15-MHz filter has the frequen- purple curve in Figure 1, which match- 2003 column (“Multiplying, Dividing, cy response shown by the blue curve es up nicely with the actual hardware and Filtering,” Circuit Cellar 161) in Figure 1: a 0.6-MHz bandwidth cen- response, apart from a constant magni- derived a stable 11.25-MHz microcon- tered at 15.3 MHz (p. 40). Although tude offset. The phase response, which troller clock from a GPS-locked 10-MHz the design frequency was 15 MHz, I isn’t shown, matches just as well. sine wave. The clock frequency is nine- built and tweaked those filters using a The double-tuned filter in Figure 2 is eighths of the input, with divisors of tedious manual process, and it’s not essentially two tank circuits (L1-C3 and 12 and 60 to suit both the microcon- surprising the final result is off by a L2-C5) linked by C4, a small “gimmick” troller and the 60-Hz power line. The bit. Since then, I’ve acquired an HP capacitor made from a short length of circuitry in Photo 1 includes two fil- 8591E spectrum analyzer and a RG-174 coaxial cable. Each tank pro- ters that isolate the third harmonic of TAPR/Ten-Tec Vector Network Ana- duces a sharp resonant peak with an two square waves, thus multiplying lyzer (VNA), both of which agree on abrupt phase change and, in the filter I the input frequency by a factor of nine. the filter’s characteristics. The HP box built, two identical tanks combine to Tom Napier, a long-time Circuit reports that the signal source I used is produce a single peak. Starting from that Cellar reader and feature writer, point- off by about 0.1 MHz, which would circuit, some empirical fiddling retuned ed out that tight band-pass filters explain a big chunk of the error. the tanks to slightly different frequen- introduce an interesting problem: The green trace in Figure 1 shows cies, producing the double-peaked mechanical changes can cause phase that the filter’s phase response passes response shown in red in Figure 1. modulation. This wasn’t an issue in through –180° at the middle of the Tom pointed out the relatively gen- my project, but if you’re designing peak. Although the phase changes tle slope in the middle of the phase precise hardware that must work smoothly from about 0° through response reduces the effect of mechan- despite thermal, aging, and shock –380°, the VNA wraps its output val- ical changes, at least for a single-fre- stresses, it’s worth considering. ues to remain within ±180°. The verti- quency signal. The inevitable trade-off In this column, I’ll take a look at how cal discontinuity is thus an artifact, appears in the reduced attenuation on the actual hardware behaved and then not a physical event. either side of the passband: about 25 dB examine how broad filters can solve one I don’t have room to list the VNA’s less. Investigating that effect led to problem while introducing another. output file, but the numbers show that some different filter models. the phase changes by 1° per 3.8 kHz SOLDER & SOFTWARE around the –180° point. Put different- FILTER FLATNESS The circuitry in Photo 1 performs ly, if the filter’s center frequency The double-tuned filter design equa- the 10- to 11.25-MHzWWW.GiURUMELE.Hi2.RO frequency con- changes by 3.8 kHz, the signal’s phase tions produce a flat-topped Butterworth version. The 10-MHz input passes changes by 1°. A 3.8 kHz change rep- response across the desired bandwidth, through a digital divider to become a resents a mere 0.025% frequency shift so my tweakage was obviously subopti- 5-MHz square wave with a precise at the filter’s center frequency, so the mal. I decided to switch to a standard 50% duty cycle. A band-pass filter (in phase can vary dramatically based on Butterworth filter topology so that I the red ellipse) extracts the 15-MHz very small physical changes. could easily change the filter’s order. third harmonic. Subsequent circuits Although I enjoy building hardware Figure 3 (p. 41) shows a third-order divide the frequency to 7.5 MHz, as much as anyone, it’s easier to explore Butterworth band-pass filter with a 10- triple it to 22.5 MHz, and then divide circuit options with mathematical MHz bandwidth centered at 15 MHz. For it again to create an 11.25-MHz square models. The schematic in Figure 2 (p. a band-pass filter, the “order” is half the wave for the microcontroller, which 40) includes measured values for the number of poles, which corresponds to

38 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612004-nisley.qxp 11/2/2006 10:09 AM Page 39

the number of capacitors and 15 106 Hz inductors. A first-order filter Q = 25 = × 06. 106 Hz with two poles consists of just × L1-C1. A second-order filter Increasing the bandwidth to adds L2-C2 to get four poles. 2 MHz lowers the Q to 7.5, A band-pass filter’s order and going to 4 MHz reduces it determines how rapidly the to 3.75. attenuation increases outside High-Q filters require close the passband. For reasons well attention to detail during design beyond the scope of this col- and construction. The frequency umn, the attenuation increases error in my original filter shows by 6 dB per octave times the that better test equipment filter’s order, at least for fre- makes sense, too. Fortunately, quencies more than an octave isolating a third harmonic beyond the band-pass edges. depends more on attenuation Figure 4 (p. 41) shows the than passband tolerances. close-in response so you can Photo 1—The red oval highlights the 15-MHz double-tuned filter that extracts the third harmonic of a stable 5-MHz square wave. see the details, but it’s obvious HARMONIC EFFECTS the third-order filter (red) is dropping the center, without the kink found in Representing a square wave in the much more steeply than the second- my tweaked double-humped model. frequency domain combines an infi- order filter (purple), even though both A band-pass filter’s Q is the ratio of nite number of sine waves, as shown have a 4-MHz bandwidth. its center frequency to its bandwidth, by the familiar Fourier transform of a The green trace represents a third- a standard parameter in filter design unit-height square wave of period T:

order 2-MHz bandwidth filter, which equations. It’s unrelated to the filter’s 412∞ nt ft = sin π  is much broader than the original dou- order, which determines the attenua- () ∑ n  T  π n=135, , ,...   ble-tuned filter shown in blue. Notice tion behavior outside the passband. that the phase changes almost linearly The original double-tuned filter has Ignoring the 4/p scaling factor, the across the passband, reaching –360° at a reasonably large Q of 25: fundamental frequency component

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 39 2612004-nisley.qxp 11/2/2006 10:09 AM Page 40

extrapolation of the with a 5-MHz component at –35 dB double-tuned filter’s and a 25-MHz component at –30 dB. response (blue) shows In fact, even the 35-MHz seventh har- that it attenuates the monic would be at –47 dB. Consider- fundamental by about ing that –35 dB represents about 2% 70 dB and the fifth distortion, the result might look odd. harmonic by 50 dB. Figure 6 (p. 43) shows the time- Passing a square domain output of those two filters, both wave through that fil- fed with a 5-MHz square wave. The dark ter would produce a blue trace, from the double-tuned filter, signal with a –60-dB has no visible artifacts. The light blue 5-MHz component trace from the 10-MHz wide filter, how- and a –54-dB 25-MHz ever, has obvious problems: the peaks Figure 1—The measured (blue) and modeled (purple) magnitude behaviors component, relative repeat in a regular three-cycle pattern. match up almost exactly.The measured phase (green) passes through –180 at to the 15-MHz sig- The frequency-multiplying circuitry the filter’s peak response. The phase of a modified double-tuned filter (red) can be flatter in the middle, but the magnitude response shows two distinct humps. nal at 0 dB. For com- converts the filter output into a parison, has an amplitude of 1, the third harmon- a golden-ears audio ampli- ic 1/3, the fifth 1/5, and so on. Expressed fier might have 0.1% dis- in decibels relative to the fundamen- tortion: –60 dB. Obviously, tal, that’s 0, –9.5, –14, and so on. the filter produces a The horizontal scale in Figure 5 (p. 42) rather pure sine wave. ranges from the 5-MHz fundamental on The purple curve in the left to the 35-MHz seventh harmon- Figure 5 comes from the ic on the right. The TAPR/Ten-Tec 10-MHz bandwidth filter Figure 2—This Spice model approximates the double-tuned filter as I VNA’s dynamic range is about 70 dB and shown in Figure 3. A built it, with measured capacitor and inductor values, but excluding stray capacitance, wiring inductance, and other imponderables. The filter has the measurements at 5 and 25 MHz square wave would 500-W input and output impedances, rather than the usual 50 W , to bet- were obviously invalid, but eyeball emerge from that filter ter match the capabilities of the surrounding circuitry.

Connecting the World of Electronic Design FREE Exhibition Pass A $75 Value

January 29 – February 1, 2007 Santa Clara Convention Center Santa Clara, California

Bring this pass to the Santa Clara Convention Center to gain FREE access to the following and be entered to win one of many WWW.GiURUMELE.Hi2.ROfabulous high-tech prizes! • 125+ Exhibitors • Keynote Addresses • Plenary and Technical Panels • TecPreviews • Technology Pavilions • Networking Receptions

International Engineering Consortium www.iec.org www.designcon.com/2007

40 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612004-nisley.qxp 11/2/2006 10:10 AM Page 41

when the mechanical parts set- stable phase characteristics, even at tle down, the overall frequency the expense of amplitude variations. will be the same. To show how that works, the two In a different application, filters in Figure 6 have an obvious however, small phase changes phase difference resulting from the can be catastrophic. Video fil- same 5-MHz square wave. The double- ters come to mind, where the tuned filter has the as-built 15.3-MHz color displayed on the screen center frequency you’ve seen before. I Figure 3—A third-order Butterworth filter resembles the double-tuned depends on the phase relation designed the 10-MHz bandwidth filter filter, but with a 10-MHz bandwidth and standard 50-W impedances. between the signal and the with –3 dB points at 10 and 20 MHz, color subcarrier. In that situa- so the center frequency is the har- square wave using a high-speed com- tion, you must design filters with very monic mean of those two values: parator triggered at what should be the zero crossings. Amplitude differences move the average value away from the Figure 4—Butter- midpoint, so the comparator triggers at worth filters have a different phase on each cycle. A smooth passbands and relatively broad three-cycle distortion has a particularly skirts. The filter nasty effect, as the next circuit divides phase varies the frequency by two: successive smoothly across cycles will have different periods. the passband. In contrast, a smooth phase change caused by mechanical variations will have little overall effect, because the gadget’s purpose is to compare the power line frequency with the 10-MHz reference. Changing the phase does require changing the frequency, but

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 41 2612004-nisley.qxp 11/2/2006 10:10 AM Page 42

odic dip every F0 = 14. 4= 102× 0 MHz 8.33 ms. Bingo! Homework: determine the actual When I origi- phase difference for both signals at nally built the 15.0 MHz and then decide if what you gadget, I used a see in Figure 6 makes sense. “6 VAC” wall wart that actual- POWER PROBLEMS AHEAD ly produced I had unsoldered the filter’s input about 8 VAC and output connection to attach the under the mini- VNA through calibrated coaxial cables. mal load this When I was all done, I restored the gadget applied. connections, reassembled the box, That was close plugged it in…and it didn’t work. The to the lower display’s LED backlight lit up, but no limit for the digits appeared. LM317 regula- Because the whole point of the filter tor’s input volt- Figure 5—The 10-MHz bandwidth filter in Figure 3 has relatively poor attenuation at 5 was to generate the microcontroller age, but I figured and 25 MHz, exactly where the 5-MHz square wave input has high energy. clock, I figured I’d probably shorted a that reducing the PC trace and, indeed, I had. That’s power dissipation in the regulator was I swapped in a 12-VAC wart, put a easy to fix, but before rereassembling a Good Thing and just ran with it. heatsink on the LM317, and the line- the box, I plugged it in and…and it I’m writing this in the middle of a frequency monitor works fine again. still didn’t work. 100°F mid-summer heat wave, with I’d prefer a lower voltage wart, but A bit of probing showed that the filter extremely high power demand, and there aren’t any in my collection. was working, the clock was running, the AC line voltage is now 117 on one Obviously, I neither designed nor and everything seemed fine. Then I leg and 107 on the other, rather than the tested my “product” for low-line con- probed the microcontroller’s RESET usual 120+ V. Guess which leg feeds the ditions. That’s mostly a function of pin and found it was high with a peri- outlets at my electronics workbench? knowing my customer base: me. If

CIRCUIT CELLAR Designer's Notification Network

Circuit Cellar design contest entrants have received thousands of valuable development tools and product samples. Because of their contest participation, these engineers receive advance e-mail notice from Circuit Cellar as soon as new samples become available. Now you too can benefit from this early notification.

WelcomeWWW.GiURUMELE.Hi2.RO to the Designer's Notifica- tion Network. Print subscribers are invited to join the Network for advance notice about our new sample distribution programs. Find out more at www.circuitcellar.com/network.

@® 42 Issue 197 December 2006 CIRCUIT CELLAR www.circuitcellar.com 2612004-nisley.qxp 11/2/2006 10:10 AM Page 43

February, Issue #199 Wireless Communications Space Close: Dec. 11 BONUS DISTRIBUTIONS: IPC Printed Circuits Expo, APEX, Designers Summit, & APEC

March, Issue #200 Robotics Space Close: Jan. 12 BONUS DISTRIBUTIONS: CTIA Wireless & Trinity College Robotics Contest Call:Call: ShannonShannon BarracloughBarraclough (860)(860) 872-3064872-3064 [email protected]@circuitcellar.com

Figure 6—The 15-MHz third harmonic appears distorted by the fundamental and fifth harmonic leaking through the skirts of the 10-MHz BW filter (light blue).The as-built DT filter (dark blue) produces much better results, but with a sig- nificant phase difference at 15 MHz.

(when!) a gizmo fails, I simply tear it apart, figure out what happened, and PROJECT FILES perhaps tell you the story. To download the SwCAD Spice However, the more important mes- models, graphs, and Gnuplot scripts, sage is that the nominal “120 V ±5%” go to ftp://ftp.circuitcellar.com/pub/ design point for North American Circuit_Cellar/2006/197. equipment may need some revision in the years ahead. The national power distribution system has run out of RESOURCES headroom, ensuring that we’ll have Fourier Series: Square Wave, Wolfram more overloads, brownouts, and MathWorld, http://mathworld.wolfram. rolling blackouts. That’s not even con- com/FourierSeriesSquareWave.html. sidering the lack of generating capacity, Gnuplot, http://gnuplot.info/. but I won’t get into that subject at all. Perhaps I should build a power-line W. Hayward, R. Campbell, and B. voltage monitor, too? Larkin, Experimental Methods in RF Design, ARRL, Newington, CT, 2003. CONTACT RELEASE LC Filter Design, http://www-users. I created the graphs in this column cs.york.ac.uk/~fisher/lcfilter/. by exporting the VNA measurements and SwCAD simulation data to text Power line information,http://en. files, then usingWWW.GiURUMELE.Hi2.RO Gnuplot. This is much wikipedia.org/wiki/Mains_electricity. easier than fiddling with screenshots, even if the results don’t have quite the same hands-on-the-knobs appearance. I SOURCES CAD III Spice simulator Linear Technology Corp. Ed Nisley is an EE and author in www.linear.com/company/software.jsp Poughkeepsie, NY. Contact him at [email protected] with “Circuit TAPR Vector network analyzer Cellar” in the subject to avoid spam Ten-Tec, Inc. filters. http://radio.tentec.com/Amateur/vna

CIRCUIT CELLAR® Issue 197 December 2006 43 2612016.qxp 11/2/2006 10:06 AM Page 44

FEATURE ARTICLE by Aubrey Kagan Visual Basic 2005 and the Serial Port

The capabilities of Visual Basic 2005’s serial port model may seem limited, but if you know what you’re doing, you can definitely use it for numerous projects. Aubrey recently got cre- ative with Visual Basic 2005. Now you can too.

Pity the serial port on the PC. It no and what I need to know is too great Unfortunately, we are shown very lit- longer gets the respect it deserves. As to bridge. I may be at that point tle. Few examples, reference to exam- a result of its simplicity and reliabili- already. The books for beginners ples that are not there, and obfusca- ty, it still forms a major part of ignore the fact that they are simply tion with difficult concepts are all embedded computer communications. recycled ideas for those of us familiar part of the problem. In addition, some of Microsoft’s belief in the superiority of with earlier versions of Visual Basic. the examples work only under certain the USB bus has led to the hardware Either from boredom or disinterest in circumstances (and worst of all, some- being excised from our computers. Yet the applications, I haven’t learned times they’re wrong). The available sup- there must be a feeling of remorse much from them. The more advanced port comes from the user forums. somewhere in the Visual Basic lan- books and the Visual Basic 2005 This article is for all of you fellow guage development teams because the (VB2005) Help files are far more diffi- Missourians at heart. If you aren’t from latest release still has a serial port cult. I understand most of the words North America, please note that Mis- facility. Apparently, the feelings were and some of the sentences. From what souri is known as the “Show-Me” state. not too intense because precious little I understand at the end of the para- information about it appears in the graph, however, it seems to be written DEFINITIONS Help files and other publications. in a foreign language. You intuitively know what a physi- There are also some problems, So why not resort to some other cal object is. This concept is extended although you will see that the serial implementation of Basic? Well, I am into software by analyzing the compo- port is still usable. sure the newer versions of VBA used nents that make up an object. You can In earlier iterations of Visual Basic, in Excel and Word will evolve into a create boundaries around the concept, you had access to MSCOMM32 (pro- .net approach. In addition, Microsoft is attach a name, describe things that vided you had the Enterprise or Profes- giving away not only VB2005, but also can happen to it (events), define differ- sional editions of the language). It was the entire Visual Studio (with some ent components that affect or show its also possible to enable this in other restrictions, obviously). These versions behavior (properties), and ascribe cer- versions including the macro language are referred to as the Express edition.[2] tain actions that it can do (methods). of Microsoft’s applications: Visual Although it appears to be possible to Put the events, methods, and proper- Basic for Applications (VBA). In many use MSCOMM32, VB2005 includes a ties together, and they are called the cases, however, there were problems serial port class in the Express object members. An object can be gen- with getting the control to appear in edition.[3, 4] As a result, I thought I eralized into a class. You can use the Visual Basic.[1] Visual Basic was always could use it to learn about the OOP class as a prototype to generate several event driven, but with the introduc- approach to programming. Talk about identical objects. tion of VB.net, WWW.GiURUMELE.Hi2.ROMicrosoft decided to jumping in at the deep end. I know the Sometimes the object is not quite enhance the language by including a old saw that a bad workman blames what you want and you need addition- far more object-oriented programming his tools. I don’t doubt that an ele- al members. Under such circum- (OOP) approach. ment of the difficulty I was experienc- stances, you can create a class that I write code in Visual Basic about ing had to do with my lack of under- uses (inherits) the members of the once every 18 months. Typically, all I standing, but I feel as though the Help founding class and adds the additional want is a simple interface that I don’t files and other documentation are members. The serial port is a class. have to relearn each time I use the wanting. I have never been anywhere When you use it to create an instance, language. The problem with this near Missouri, but it seems to me that it becomes an object with all of the approach is that the time will come I have an affinity for Missourian phi- members of that class. Later, I’ll when the gap between what I know losophy when it comes to learning. describe two serial port objects created

44 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612016.qxp 11/2/2006 10:06 AM Page 45

from the same class.

EVENTS There are four possible events listed in the Help files: Data Received, Error Received, Pin Changed, and Disposed. The first three are self-explanatory, and the last is a mystery of no conse- quence. Events are asynchronous. One of the problems associated with the VB2005 implementation is that you can’t associate an error detected with a particular data byte received. Recep- tion and Error Detection are two sepa- rate events, and you can’t guarantee the order in which they will occur and their relative timing. It is possible to use the serial port without using the events, but there are certain things that you can’t do as a result of the Photo 1—All the options are built into the software.You can’t enter any data.You can select only from the options class model’s shortcomings. For by clicking in each list box. instance, you can’t read the error sta- tus in any way. You can detect if an error has occurred only if the event is can find them in the VB2005’s Help Help file description of the property triggered. files. The different Read methods load states that any value below 4,096 is You deal with events through pieces data into a buffer that is sized accord- rounded up to 4,096. I have been of code called Event Handlers, which I ing to the property ReadBufferSize. unable to judge which is correct. The will cover soon enough. Just a word of Unfortunately, this is a buffer of only ReceivedBytesThreshold property caution though: if you have an event received data. No information like determines how many bytes are handler in your code and that event parity is stored with the data, and it’s received before the Receive event occurs, then the code will be executed. impossible to correlate an error with occurs. There is no way to disable this as you the particular byte that caused the would disable an interrupt in hard- error. You could try to reduce the SERIAL PORT CONTROL ware. If the code is not there, nothing buffer size to one or two to isolate the Perhaps the first hint that there are will happen and everything will con- byte. I have seen reports that this has shortcomings with the serial port con- tinue as planned. This is not normally been done, but in contradiction the trol (in VB2005) happens right after a problem because a project normally takes a particular approach and stays with it. When an event occurs, data are passed to it by way of arguments, which can be processed even further depending on the event. For instance, when an error occurs, the error that caused the event (e.g., parity error) is passed as an argument.

METHODS & WWW.GiURUMELE.Hi2.ROPROPERTIES There are many possible methods that exist for the serial port that can be investigated in the VB2005 Help files. I will describe only a few of them. Unfortunately, some of the methods don’t always work (or work exactly as advertised). I will mention them at a more appropriate time. A plethora of properties are avail- able in the serial port class. Again, you Photo 2—The user interface triggers transmission and reception for the different approaches in the Serial1 project.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 45 2612016.qxp 11/2/2006 10:06 AM Page 46

you drag the Serial Port Control from Listing 1—In the Help files concerning the topic of serialport.write, there is something about hav- the toolbox and drop it on the Form. ing to convert from ASCIIencoding to UTF8Encoding because any character above ASCII 127 is converted to When you investigate the events asso- a question mark. Ignore this comment. If you format the data that is being transmitted as a byte, all bits will be ciated with the control, you will dis- transmitted as expected. cover that there is only one event Private Sub btnSendBytes_Click(ByVal sender As System.Object, _ imported. There are, however, several. ByVal e As System.EventArgs) Handles btnSendBytes.Click A closer look shows that the proper- Dim bytSequence() As Byte = {&H83, &H45, &H33, &H88} ties (unimportant things like the data SendBytes(bytSequence) End Sub rate!) don’t seem to affect the port’s operation at all. Public Sub SendBytes(ByVal data() As Byte) VB2005 has early and late binding SerialPort1.Write(data, 0, data.Length) options. In most modern software, End Sub when writing code that accesses an object, you start with the object and then place a period and add a member Serial1_Load procedure in the proj- Port(“com4”, 19200,_IO.Ports.Parity. possibly followed by additional periods ect. This code runs every time the Even, 8, IO.Ports.StopBits.One) and detail. For instance, you could have application starts. The entries for each IO.Ports.SerialError.RXParity as list box are loaded in the form load Unfortunately, in using this approach, a particular property that becomes event using the Add method. The some methods like DiscardInBuffer accessible through an event within the default selection is achieved by chang- won’t work at run time and will serial port object. ing the SelectedIndex property. Note return an error message. I recommend Early binding means that Visual that a space followed by an underscore using the second method (Serial- Basic has foreknowledge of the object (as seen in the actual sub declaration) Port.Open), which is seen in the proj- and prompts you with all of the avail- indicates a line continuation. ect as the OpenPorts procedure. It able choices each time you type a peri- In order to use a serial port, you implements the serial port parameters od. This is a very handy feature. It is need to Open it. There are two ways that appear under the user interface’s not necessary to place the Serial Port to do this. The first is the OpenSeri- Setup tab. Control because you won’t be using it alPort method (written as a single You can open the port anywhere, directly. But placing it does allow for line in the code): but because you are only going to early binding, so I recommend that transmit from within the Run tab, I you do it. Late binding means that the Using SerialPort1 As IO.Ports.Serial placed the OpenPorts procedure in compiler doesn’t consider the validity Port = My.Computer.Ports.OpenSerial the tab select event tabRun_Enter so of the elements used in the object until the project is compiled. An error is generated only at that time (only if Listing 2—All I am doing is acquiring the bytes and displaying them on the screen. Again, you need to click on the Transmit a Series of Bytes (A) button. After that, click on the Receive a Series of Bytes (A) button (see there is one, of course). Photo 2). If you are writing a program and you know your exact hardware configura- Public Sub ReceiveBytes() tion, you can configure the ports ‘ receives it on serial port2 Dim bytReceived(20) As Byte directly. However, you may want to ‘dim includes the 0 case generalize so that you list all of the ‘must be dimensioned or you will get a run time serial ports that are available on the ‘error with the “bytReceived(iI) = SerialPort2.ReadByte” PC. It would also be prudent to allow ‘below- this will be generalized Dim iI As Integer = 0 a change in data rate, parity, and other settings. I created a tabbed user inter- While SerialPort2.BytesToRead > 0 Or iI = 0 face as the Serial1 example, which is ‘note that if we are waiting for a message posted on the Circuit Cellar FTP site. ‘the >0 will show as false immediately, WWW.GiURUMELE.Hi2.RO‘so the iI=0 condition is added The Setup tab has controls for two bytReceived(iI) = SerialPort2.ReadByte serial ports. I worked with two so that iI = iI + 1 I could transmit from one to the other End While just to make sure the software was MsgBox(“Number of bytes received- “ & Str(iI) & vbCrLf & _ BitConverter.ToString(bytReceived), _ working. Photo 1 shows the Port MsgBoxStyle.OkOnly, “Message Received”) Setup screen in operation. End Sub In addition to placing and sizing the controls, some code is required to Private Sub btnReceiveByte_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReceiveByte.Click make all of this happen. Article size ReceiveBytes() restrictions prevent repeating all of End Sub the listings here, so please refer to the

46 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612016.qxp 11/2/2006 10:06 AM Page 47

that it runs every time you click the Run tab. You can’t open a port if it’s already open, and it should always be We Listen. Think. And Create. closed when it becomes available for the rest of the system. The safest place to put this is in the FormClos- Serial ing event. (Once again, this is in the Distributed Digital Industrial HMI I/O I/O I/O Computing project listing.)

LINE VS. BYTE TRANSMISSION SeaLINK Ethernet Serial Servers Offer: SeaLINK Ethernet serial The serial port class enables two • 1, 2, 4, 8, and 16-Port Models forms of data communication: a line servers are the fastest, • RS-232, RS-422, RS-485, and Optically or a byte. With the line approach, most reliable way to Isolated Versions everything is treated as 7-bit ASCII • Included Software Enables Virtual COM Port Operation text, so the most significant bit of the connect serial devices • Easy Installation and Confi guration data is always zero. The communica- to your network. • DIN Rail or Table Mount Design tion also has a line termination char- • Extended Temperature Option Available acter so that the end of the line can be detected. Although the end-of-line FCUS On Success uses the C standard of 00HEX, it can be modified by changing the Newline property. I’m sure you will be involved with 8 bits of data, so I won’t spend a lot of time on the line communication. There are a number of buttons with descriptive names under the Run tab (see Photo 2). Clicking on one of the buttons will trigger the associated event, which in turn will call one of the routines.

LINE TRANSMISSION Data transmission is extremely easy in Visual Basic. It requires no more than the following instruction:

SendLine(“Sending a line of data”)

You can also use a string variable as the parameter passed to the SendLine procedure. The Visual Basic designers decided that everything should be event driv- en. You will see later how data recep- tion, errors, control line change, and several other occurrences are treated as events. I find it ironic that the transmission sequenceWWW.GiURUMELE.Hi2.RO is not. The processor will not emerge from the SendLine until the last character is being shifted out.

BYTE TRANSMISSION Transmitting bytes is not that differ- ent than line transmission (see Listing 1). You can achieve 8-bit transmission, and there is no termination character. A user-selected communications pro-

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 47 2612016.qxp 11/2/2006 10:06 AM Page 48

tocol determines how the receiving of bytes in the message. It could use a end will detect an end of message. reserved character or a sequence of This protocol could be a fixed message characters for message synchroniza- length or it could embed the number tion. It could also add error detection

PC/104 Multitech Socket Module Carrier Board Listing 3—Here you see byte reception with a timeout. The message is returned. As in previous examples, you need to click on the Transmit a Series of Bytes (B) button and then click on the Receive a Series of Bytes (B) button. Clicking on the Receive button alone will force the timeout error.

Public Function bytReceiveBytes() As Array Dim iRx(254) As Byte ‘dimension as the largest possible number of bytes

FLEXCOM104 Dim iI As Integer = 0 Dim iNumberOfBytes = 255 ‘initiate timer- message must be received within 1 second Two serial ports (RS-232/RS-422) Timeup2.boolExpired = False Connects either serial port to ethier Timer2.Interval = 1000 ‘1 sec delay Universal Socket in Standalone mode Timer2.Start() Allows bridging of the modules iRx(0) = 0 ‘prepare flag for pass PC/104 interface to high speed quad UART ‘wait for all the bytes to be received, or a timeout occurs While (iI < iNumberOfBytes) And (Timeup2.boolExpired = False) ‘so don’t overflow buffer, 100Mhz PC/104 Module Application.DoEvents() ‘this allows Windows to “multitask” ‘the timer interrupt will not happpen without this line If SerialPort2.BytesToRead > 0 Then ‘there is a byte or more in the buffer iRx(iI + 1) = SerialPort2.ReadByte ‘offsetting by 1 to allow for iRx(0) to be used for status ‘now checking on the numebr of bytes If iI = 1 Then MZ104 ‘this is the 2nd byte iNumberOfBytes = iRx(iI + 1)

Featuring the new edition ZFx86 ‘if fixed length message then can ignore this if clause FailSafe® Embedded PC-on-a-Chip End If Dual watchdog timers, Phoenix iI = iI + 1 ‘bump to read next byte BIOS and FAILSAFE Boot ROM End If Extended temperature -40°C to 85°C End While If (Timeup2.boolExpired = True) Then iRx(0) = 1 ‘set iI = 0 End If 168 Watt High Efficiency Power Supply ReDim Preserve iRx(iI) ‘should be iI+1, because increment within ‘while loop, but iRx(0) has been inserted bytReceiveBytes = iRx ‘set up return values End Function

Private Sub btnSendBytesB_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSendBytesB.Click Dim bytSequence() As Byte = {&H83, &H5, &H33, &H88, &H99} HPS3512 ‘5 bytes embedded as 2nd byte SendBytes(bytSequence) Total Power: 168 Watt with ATX Interface End Sub +3.3V, +5V, 12V output 6V to 40V DC input range Private Sub btnReceiveBytesB_Click(ByVal sender As System.Object, _ WWW.GiURUMELE.Hi2.ROO O Extended temperature: -40 C to +85 C ByVal e As System.EventArgs) Handles btnReceiveBytesB.Click RS232 serial port / Optocoupled inputs Dim bytBytes() As Byte bytBytes = bytReceiveBytes() If bytBytes(0) <> 0 Then ‘error detected- only timeout at the moment www.tri-m.com [email protected] MsgBox(“Timeout detected”) Else 1.800.665.5600 MsgBox(“Return Code + Bytes received- “ & _ HEAD OFFICE: VANCOUVER BitConverter.ToString(bytBytes), _ MsgBoxStyle.OkOnly, “Message Received”) tel: 604.945.9565 fax: 604.945.9566 End If End Sub

48 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 5.qxp 10/27/2006 2:37 PM Page 1

WWW.GiURUMELE.Hi2.RO 50.qxp 10/26/2006 11:09 AM Page 1

ZigBee™/ IEEE 802.15.4 Transciever 2.4 GHz ZigBee™ Embedded OEM Modules

The CC2420 from Chipcon was the industry's These IP-Link modules simplify wireless integration first single-chip 2.4 GHz IEEE 802.15.4 and reduce development cycles by six months or more. compliant and ZigBee-ready RF transceiver. Each module includes an IEEE 802.15.4-compliant radio, Chipcon's goal is to become the leading a Silicon Laboratories 8051 microcontroller, provider of this technology. programmable I/O, flexible antenna and range solutions, as well as ZigBee-ready IP-Net networking software.

mouser.com/chipcon/a mouser.com/helicomm/a

2.4 GHz ZigBee™ Development Kit

Turn to Mouser for All Your Everything you need to immediately begin ZigBee™ Product Needs! developing star, cluster-tree, and mesh networks. Each of the six development boards included in the kit contains a high-performance C8051F121 MCU, an IEEE 802.15.4 compliant RF transceiver, the MAC firmware, and the Helicomm ZigBee Protocol stack.

mouser.com/silabs/a

PICDEM™ Z Demonstration Kit

This kit is an easy-to-use ZigBee™ Technology wireless communication protocol development and demonstration platform.The kit includes the ZigBee protocol stack and two PICDEM Z boards, each with an RF daughter card.The demonstration board is also equipped with a 6-pin modular connector to interface directly with Microchip Technologies' MPLAB® ICD 2 in-circuit debugger (DV164005).

mouser.com/microchip/a

Mouser delivers the newest products and the latest technologies, including ZigBee -- the hottest wireless technology protocol in the ZigBee™ marketplace today. Evaluation Kits Based on the IEEE 802.15.4, ZigBee is an open standard for reliable, cost-effective, low- Short range, low power wireless applications. And it's a standard power, 2.4 GHz ISM that works globallyWWW.GiURUMELE.Hi2.RO and can be configured for band transceiver. star, peer-to-peer, and mesh networks. Contains complete Experience Mouser’s time-to-market 802.15.4 PHY/MAC, advantage! Our vast selection of the NEWEST ZigBee protocol stack supporting star, and mesh products, NEWEST technologies, new catalog The Newest Products networking.The MC13193 can be a stand-alone every 90 days, no minimums, and same-day For Your Newest Designs transceiver or part of the Freescale ZigBee-ready shipping on most orders, gets you to market platform when combined with an appropriate faster. We make it easy to do business with microcontroller. Mouser! mouser.com (800) 346-6873 mouser.com/freescale/a

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

Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners. 2612016.qxp 11/2/2006 10:06 AM Page 51

Listing 4—Properties can be simple variables or they can actually do some work. In this example, the incom- munication is just covered in passing.) ing series of bytes is written to the ReceivedMessage property.When this is done, the process sets a Because the receiver “knows” when flag that signifies that there is in fact a message and it’s stored in the object. It also analyzes the data. In this the end-of-line occurs, it’s possible to case, it looks at the received message and checks to see that the first byte is A5hex (a make-believe header in detect a timeout failure, as you will this instance). If it is, then a HeaderSeen property is set. As you can see, two objects are instantiated. see in the Try..Catch construction, so that an error is detected when a Public Class ProcessHandshake Public ErrorDetected As Boolean timeout occurs. It is easy enough to Public HeaderSeen As Boolean test. Just click on the Receive a Line Public MessageArrived As Boolean button without clicking on the Trans- Private Received_Message As Array mit a Line button (see Photo 2). You Public Property ReceivedMessage() As Array Get can also force an error by clicking on ReceivedMessage = Received_Message the Transmit a Series of Bytes button. End Get Set(ByVal value As Array) Received_Message = value BYTE RECEPTION ‘store the message According to the Help files, the MessageArrived = True Read method should return with all of ‘indicate there is something in the buffer the bytes in the message. I could never If Received_Message(0) = &HA5 Then get it to return more than a single ‘must be 0xff in header for correct message (for example) ‘this flag is used indicate that it recognizes the information character. At any rate, I prefer reading HeaderSeen = True byte by byte because it gives me a Else greater feeling of control. Listing 2 HeaderSeen = False shows the first stab at receiving bytes End If End Set on SerialPort2. End Property Real-world applications can fall foul End Class of the simple approach presented here. It could result in an endless loop. Public Class Serial2 What if the bytes are not received as a Dim IF1 As New ProcessHandshake spurt but are separated by a varying Dim IF2 As New ProcessHandshake period of time? How do you know that . the message is complete? Did an error . . occur? Let me expand slowly. I could implement a timeout using the ReadTimeout property of the serial port object (as seen in line reception techniques or comply with a pub- line reception is trivial, as you will see description), but this implementation lished standard. in the project in the ReceiveLine pro- appears to have some limitations. It does cedure. It is invoked when you click on not appear possible to stop the timer, LINE RECEPTION the Receive a Line button and trigger and it is unclear whether writing to the In order to demonstrate reception, I the btnReceiveLine_Click event. property restarts the timer. In many connected SerialPort1 to Serial- How do you detect an error in trans- applications, I would like to restart the Port2. The OpenPorts procedure and mission or missed transmission? I will timer between each byte received. You FormClosing event are modified to deal with detailed error detection need to introduce an external timer. To include the extra port. In basic form, later. (Remember that the line com- do this, you need to add a timer control to the project form in the same way that you added the serial ports. Listing 5—This code is added to the OpenPorts procedure, although it can just as easily be omitted. I When the timer reaches its termina- don’t know if this is a flaw in Visual Basic or if it’s merely intended to enable you to have several handlers of dif- tion count, it generates an event. You ferent names and WWW.GiURUMELE.Hi2.ROswitch between them by giving them different handler names. Including them, however, helps then need to know how to communi- documentation in detailing what is expected to happen. cate the results of this to some other AddHandler SerialPort2.ErrorReceived, _ process. The simplest way to inter- AddressOf SerialPort2_ErrorReceived communicate between them is to use ‘must appear after port is opened external variables, and you can cer- ‘the name SerialPort2_ErrorReceived is arbitrary, tainly do that. If you’re like me, you ‘but must match the handler name come from a world where many vari- AddHandler SerialPort2.DataReceived, _ ables, if not all, are global. Despite AddressOf SerialPort2_DataReceived that, I get the distinct feeling that ‘the name SerialPort2_DataReceived is arbitrary, global variables are frowned upon in ‘but must match the handler name today’s software community. I decided

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 51 2612016.qxp 11/2/2006 10:06 AM Page 52

to create an object that had properties Listing 6—This is an example of the DataReceived and ErrorReceived events. Be sure your code needed to indicate the status of the is more robust than the simple case presented here, especially when deciding when a full message has been timer to any code. received. Before you create an object, you Public Sub SerialPort2_ErrorReceived( _ need to create a class (a prototype of ByVal sender As Object, _ the object). After you have the class, ByVal e As System.IO.Ports.SerialErrorReceivedEventArgs) _ you can instantiate it to create one or Handles SerialPort2.ErrorReceived many objects. The benefit is that you ‘NOTE: _ is a line continuation Dim iI As Integer deal with them in the same manner. iI = SerialPort2.BytesToRead All that changes is the name. As an ‘read the number of bytes received to help with understanding example, look at how you treat the ‘the failure of discard in buffer to work. indicate error serial port. The only difference is IF2.ErrorDetected = True ‘it is conceivable that the reception event will not fire, whether you are dealing with Seri- ‘so set that flag as well alPort1 or SerialPort2. IF2.MessageArrived = True The class definition lives outside If e.EventType = IO.Ports.SerialError.RXParity Then the Form class in the program code. I ‘you could look for all the errors e.Event is a passed parameter MsgBox(“Parity Error”, MsgBoxStyle.OkOnly, “Transmission error”) am not going to get into why the Form SerialPort2.DiscardInBuffer() is a class and there isn’t an instance of ‘beware of the style you use to open the serial port it. Philosophy is not my strong suit. If ‘My.Computer.Ports.OpenSerialPort method will generate a fault you look at the project, you will see ‘condition here stating the the port is not open. End If how the Timeup class is created (at End Sub the end of the project) and how it is Public Sub SerialPort2_DataReceived( _ instantiated as an object using the dim ByVal sender As Object, _ instruction before any procedures or ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _ Handles SerialPort2.DataReceived functions that may use it. Dim bytReceived(5 - 1) As Byte As I mentioned before, in any proto- ‘dim includes the 0 case col, the length of the message is fixed, Dim iJ As Integer implied, or somehow embedded in the Timer2.Interval = 1000 ‘500mS Timer2.Start() message. For the sake of this example, ‘inititae timeout assume that the second byte received Timeup2.boolExpired = False contains the number of bytes. If you iJ = 0 have a fixed byte length protocol, then While SerialPort2.BytesToRead > 0 And Timeup2.boolExpired = False Application.DoEvents() the check that reads this byte need bytReceived(iJ) = SerialPort2.ReadByte not be done. In addition, you can iJ = iJ + 1 change the procedure to a function so End While that the read message can be returned If Timeup2.boolExpired = False Then IF2.MessageArrived = True for processing in the calling procedure. IF2.ReceivedMessage = bytReceived The function will return an array. I SerialPort2.DiscardInBuffer() can reserve the first byte (array mem- Else ber (0)) of the array as a status byte. If SerialPort2.DiscardInBuffer() ‘because of the asynchronous nature the events this clear may it is zero, then the message is valid. A ‘only have cleared the bytes to date, not all of them nonzero indicates a fault, and it can End If have different numeric values associat- ‘now and error could have occurred. Because of the ed with different faults like checksum ‘asynchronous nature the events it may not be detected for a ‘while start a delay and after that check if an error was detected error and timeout. I use only a timeout Timer2.Interval = 500 ‘500mS code with a value of one. The incoming Timer2.Start() message starts at array member (1). ‘inititae timeout Listing 3 showsWWW.GiURUMELE.Hi2.RO how all of this pans Timeup2.boolExpired = False While Timeup2.boolExpired = False out. If the application has a longitudi- Application.DoEvents() nal check on the bytes like a CRC or ‘ensure the timer interrupts happen checksum, and provided the program End While considers for the validity of this If IF2.ErrorDetected = True Then IF2.MessageArrived = False ‘ensure no message is passed check, then this approach will be suf- End If ficient without resorting to the built- If IF2.MessageArrived = True Then in error detection. ‘if there is a message- respond Send2Bytes(IF2.ReceivedMessage) End If EVENT-DRIVEN RECEPTION End Sub It would have been nice to have had

52 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612016.qxp 11/2/2006 10:06 AM Page 53

an external device that communicated isn’t possible to read the error proper- port while doing nothing else. with the PC to help demonstrate the ties directly. Microsoft, if you ever get performance of the serial port within to read this, please make these proper- MODBUS INTERFACE VB2005. I needed a simple device ties accessible. My solution was to add Although the abilities of the serial because if I had had to explain its a delay after the message was received port model in VB2005 are severely limit- operation, it would have been a dis- to allow the error (if it has been detect- ed, you can still use it for many different traction. In the end, I decided to ed) to be processed. Hardly elegant! applications. This article stands on its extend the concept that I have used to own, but I have used VB2005 and this date. Using both serial ports, Serial- BREAK DETECTION implementation of the serial port to cre- Port1 would be the master that initi- It’s possible to change the value of ate a Modbus interface. In an upcoming ated the communications, and Seri- the RS-232 control outputs and read article, I will describe Modbus and a alPort2 would be a virtual remote the RS-232 control inputs directly via VB2005 interface to Microsoft Excel. I device. SerialPort2’s function is to the associated properties. The same is merely take the received message true of break detection and generation. Aubrey Kagan is a professional engi- received and return the bytes over the It’s possible to have the change of any neer with a B.S.E.E. from the Tech- serial communication lines. If any of the control inputs or the break nion—Israel Institute of Technology error is detected, SerialPort2 sends detection to generate a PinChanged and an M.B.A. from the University of no return message. The “protocol” is event. The ring indicator (RI) can also the Witwatersrand. He works at simply a five-byte message. The first generate an event, although it isn’t a Emphatec, a Toronto-based design

byte is A5HEX. SerialPort1 uses the property of the serial port object. house for industrial control interfaces techniques I have used until now. You can find an example of how to and switch-mode power supplies. In SerialPort2 is event driven. approach this in the SerialPort2_ addition to having written several I had to create a new project called PinChanged event in the project. As I articles for Circuit Cellar and having “Serial2.” Why? When there is an already mentioned, you don’t need to published ideas in other periodicals, event handler within the code, there is use an AddHandler declaration, but Aubrey wrote Excel by Example: A no way to disable it. If the event you could insert it for good form. Microsoft Excel Cookbook for Elec- occurs, it is “handled” even if it per- tronics Engineers (Newnes, 2004). tains to something else like a different SHORTCOMINGS example. As with all event handlers in The VB2005 SerialPort class has a PROJECT FILES Visual Basic, if the handler doesn’t few shortcomings. For instance, the con- To download the code, go to ftp://ftp. exist, the event is ignored. The setup trol placed from the toolbox doesn’t link circuitcellar.com/pub/Circuit_Cellar for the project is identical to “Serial1.” to the object, and it has only one event. /2006/197. You can use the DataReceived, In addition, event-driven and asynchro- ErrorReceived, and PinChanged nous events lead to uncertainty as to REFERENCES events independently. There is no pre- whether a message has been successfully condition for the use of any. The received and whether the process is [1] R. Ashby, “COM Port Woes,” EE events are asynchronous and so there completely over. Clearing the In buffer Times, Feb. 2002, http://archive. is an issue of how to pass data from doesn’t always clear all of the bytes chipcenter.com/eexpert/rashby/ one to the other. As you can see in because some may arrive after the com- rashby057.html. Listing 4, I again resorted to an object. mand is executed. There is no buffer of [2] Microsoft Corp., “Visual Basic 2005: Listing 5 shows the code that was faults, and there is no linkage to bytes so Overview,” http://msdn.microsoft. added to the OpenPorts procedure. that an error can’t be associated with a com/vstudio/express/vb/. The code for both handlers is shown particular byte. Furthermore, it isn’t in Listing 6. After the port is initiated, possible to read faults directly. [3] Microsoft Corp., “How to Access no code ever needs to treat the port There are other shortcomings to Serial and Parallel Ports by Using directly, but it can access the IF2 consider. Different methods of the Visual Basic .NET,” 823179, 2006, object to see the status. One of the SerialPort object may not work http://support.microsoft.com/ problems with WWW.GiURUMELE.Hi2.ROthe Windows/Visual depending on how the control is initiat- default.aspx?scid=kb;en-us;823179 Basic approach to events is that they ed (opened). The Receive method does- &Product=vb6#EWACAAA. are asynchronous. You’re never sure of n’t work for bytes. Also note that the [4] C. Cavalli, “Serial Communication the sequence or the relative times of incoming buffer size (less than 4,096) is With VB.Net,” www.codeworks. each event. As a result, it is impossi- ignored (according to the documenta- it/net/VBNetRs232.htm. ble to tie an error to a particular byte tion), so it isn’t possible to narrow down so that error correction is not feasible. the buffer so that an error is associated It’s possible that a message is read, with a given byte. Finally, there is no RESOURCE processed, and completed by the end-of-transmission event so that the PC Innovatic, “Serial COM Port Commu- ReceivedMessage event before the resources are dedicated to writing the nication,” 2006, www.innovatic.dk/ ReceivedError event is processed. It series of bytes or characters to the serial knowledg/SerialCOM/SerialCOM.htm.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 53 2608017 bate.qxp 11/2/2006 10:57 AM Page 54

FEATURE ARTICLE by Alan Bate Third Overtone Crystal Clock Oscillator Alan describes a requirement for a low-jitter, 54-MHz third overtone design. It’s a good solu- tion for high-volume manufacturing.

Conventional quartz crystals are the 1930s to serve ham radio opera- has an operating range from 0° to 70°C limited in their fundamental frequen- tors, but it grew during World War II and a frequency tolerance between 10 cy range to around 20 to 35 MHz. This to meet the huge military demand for and 100 ppm. The maximum equiva- is a physical process limitation that radar and telecommunications tech- lent series resistance (ESR) ranges requires thinner and more fragile nology. This has enabled today’s indus- from 35 to around 800 Ω depending on quartz wafers with increasing frequen- try to produce crystals that have been the frequency. For the frequency range cy that results in lower manufacturing ground, polished, and trimmed to high discussed in this article, a maximum yields due to wafer breakage. orders of dimensional and frequency ESR of 40 Ω is typical. Its load capaci- To obtain higher frequency opera- accuracy. By the judicious slicing of the tance is 12 pF. The drive level is tion, conventional crystals are often crystal with respect to its atomic lat- between 100 µW and 2 mW (maximum) operated in a harmonic or overtone tice, an entire range of temperature depending on the package and type.[1] mode. The idea is to achieve frequen- coefficients is obtainable. Crystals are cy multiplication while maintaining typically packaged in resistance-welded, CRYSTAL OPERATION the high-accuracy, high-stability, low- hermetically sealed leaded or surface- Quartz or silicon dioxide (basically a temperature drift associated with mount metal cans that are either vacu- crystallized version of sand) is a material quartz resonance. The current trend to um-sealed or filled with dry nitrogen. that has polarized or permanently use phase-locked loop (PLL) frequency For less than $1 for high-volume charged molecules. All such material multiplication has phase jitter limita- orders, who can beat that? Quartz crys- exhibits the piezoelectric effect. If the tions. This can be a problem with tals have excellent frequency stability material changes its physical dimensions increasing use in modern digital chips because we are essentially talking from an applied pressure, then a corre- with internal core clocks of several hun- about the dimensional stability of a sponding electric field is developed at dred megahertz that are derived from a piece of rock. Fortunately, the crystals opposite faces of the material because of basic low-frequency system clock. also have excellent frequency stability. the charged molecules aligning so that In the set-top box design field in A typical commercially available their charges add. The process also works which I work, achieving high clock sta- crystal will age at a rate of ±5 ppm per in reverse so that an identical applied bility at low cost is an issue. In this year. (Aging occurs mostly in the first electric field will produce a corresponding article, I focus on a requirement for a year. The rate improves considerably mechanical distortion of the crystal.[1] low-jitter, 54-MHz third overtone design when soldered cans are replaced by To ensure consistency in quality for high-volume manufacturing. Hence, resistance-welded cans.) Such a crystal and cost, modern crystal manufacture preset “tweaking” is not an option. uses pure cultured quartz grown from a seed crystal. This is simi- Seed crystal QUARTZ CRYSTALS lar to the semiconductor indus-

Quartz crystals are unique com- BT-CUT try’s manufacturing of pure sili-

ponents with exceptionally high 49° Y-axis con. After slicing the quartz bar Q factors, typically ranging from AT-CUT into wafers, the quartz is accu- 10,000 to higherWWW.GiURUMELE.Hi2.RO than 100,000. rately ground and shaped into a This is three to four orders of 25.25° disc or a plate. It’s then polished magnitude higher than what is to create an efficient miniature obtainable from most real-world high-Q mechanical resonator.

LC resonant circuits. Even low- Z-axis There are three main modes of loss, air-cored coils barely reach Q Y-axis vibration depending on the type Mechanical Required factors of more than 200. The only X-axis blank of slice or cut taken relative to

Q challenger to the crystal would Sliced wafer the quartz bar longitudinal or Z- be a microwave cavity resonator axis, which is referred to as the Figure 1—Check out the two principle cuts used in electronics. This machined out of solid aluminum. cultured quartz Y-bar is grown from seed crystal. Circular blanks are optical axis: Longitudinal mode, The crystal industry began in machined from the cut wafers using only the grown crystal regions. Low-Frequency Face-Shear mode,

54 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2608017 bate.qxp 11/2/2006 10:57 AM Page 55

and High-Frequency Shear mode. Also they have fewer problems The precise cutting angle is con- with spurious operation when trolled at high levels of accuracy using higher power levels and with x-ray diffraction techniques. lower loss than the more recently The most commonly used cuts introduced low-profile surface- have names like AT-Cut, which mount welded can varieties.[1] produces an S-shaped frequency The expensive inverted-mesa temperature characteristic, and BT- process has helped manufacturers Cut, which has a parabolic charac- overcome the fundamental fre- teristic. Figure 1 illustrates the two quency limit problem associated principle cuts from the cultured with conventional crystal manu- bar. The quartz bar is a sandwich in facturing. This process generates which the seed crystal is the filling thin quartz through the chemical and the bread slices are pure Z- Photo 1—Check out this network analyzer plot of the transfer func- milling or etching of a “well” on grown synthetic quartz, which are tion between the oscillator terminals with the crystal in-situ and the opposite faces of the quartz blank, tank circuit removed. The spurious resonances around the funda- known as lumbered M-bars. mental and higher overtones are easy to see. which is surrounded by a thick ring of unetched quartz for strength. At SPURIOUS MODES present, inverted-mesa crystals In practice, spurious resonances are diameter, thickness, and mounting have a fundamental frequency range of also produced. Spurious modes are (along with the tight process control of up to approximately 500 MHz.[1] additional unwanted parasitic reso- the polished surface finish) all ensure The mesa process is not without its nances to the fundamental. These that the spurious modes are sufficient- problems, though. The smaller mass additional modes are normally close to ly suppressed. This helps prevent an of quartz means there are more resid- the desired overtone. Photo 1 shows a oscillator from starting up and locking ual contaminants. network analyzer frequency sweep of to the wrong frequency. an in-circuit 18-MHz fundamental The older more bulky HC49 style of EQUIVALENT CIRCUIT crystal and its associated overtones. through-hole crystals with their larger If you examine an impedance plot The careful design of the quartz’s quartz mass have lower phase noise. for a typical crystal, you’ll see that the

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 55 2608017 bate.qxp 11/2/2006 10:57 AM Page 56

ways in which the circuit can resonate. impedance, making the crystal reso- One is from the resonance of the nance nearly independent of any

motional inductance (LM) representing external circuit. The other mode, par- the quartz mass combined with the allel resonance (or anti-resonance), Figure 2—This is a simple model of a crystal’s imped- capacitance (CM) representing the quartz provides a high dynamic resistance at ance seen at the fundamental mechanical resonance. compliance or elasticity, which provides resonance. This occurs when the com- L , C , and R are apparent values of LC and R that M M M a series resonance. At resonance, the bination of motional inductance (L ) represent the mechanical piezoelectric performance. M inductive and capacitive reactances can- has an inductive reactance that equals The ESR is not shown, but it’s made up from RM and the dielectric loss in the quartz self capacitance. cel, thereby reducing the series imped- the total effective capacitance seen by ance to the equivalent series resistance. the crystal (i.e., the self capacitance

crystal has close series and parallel reso- The motional resistance (RM) is combined with the oscillator circuit and nances at the fundamental and all the mainly due to frictional losses. In board parasitic capacitance). Therefore, overtones (see Figure 2). There are two series resonance, you have a low crystals designed to operate in the paral- lel resonance mode have a specified load capacitance. As a result, the oscillator design must provide this load capaci- tance for correct frequency operation. In practice, the discrete capacitor values are reduced from their nominal values to allow for any stray circuit capacitance. The crystal’s quality factor (Q), equiv- alent series resistance (ESR), and motion-

al resistance (RM) are derived from 50-Ω network analyzer measurements. The equivalent series resistance represents the total loss, including motional friction loss, and the quartz dielectric loss in the quartz self-capacitance and the RF loss in the crystal connections. The inductance can be derived from the measured Q factor, the specified

ESR, and the CSERIES from the series reso-

nant frequency (FR). For example, assum- ing a typical Q factor of 100,000 and a specified maximum ESR of 40 Ω, then:

ωL Q = ESR You can rearrange the formula in terms of the motional inductance:

WWW.GiURUMELE.Hi2.RO

Figure 3—This is a conventional asymmetric third over- tone circuit.

56 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2608017 bate.qxp 11/2/2006 10:57 AM Page 57

anti-resonance, not the theoretical filtering of noise and harmonics. It Q × ESR 40 L = = 100, 000 × true resonant point of zero phase shift, also helps to limit the crystal drive ωπ2 F R where the crystal impedance becomes power, typically specified to be 1 mW In this project, the fundamental fre- a high dynamic resistance. But this is for the larger HC49 types. This is quency is 18 MHz. Therefore, the effec- academic when working with crystal important for avoiding premature aging, tive motional inductance is around 35 Q factors of 10,000 and higher. unwanted overtone, and even fractures.

mH. The crystal resonant frequency is: Any propagation delay through the The loading capacitors CL1 and CL2 are in inverter is absorbed into the overall phase series across the crystal along with all of 1 shift by reducing the phase lag of R and the stray board capacitances to ground F = LG R 2π L C M M CL2. The CMOS gate output impedance and the IC amplifier port capacitances.

where LT and CT represent the motion- adds to the required series resistance RLG.

al inductance and capacitance. The The RLG-CL2 pair also forms a low-pass THIRD-OVERTONE OPERATION

motional capacitance (CM) is: filter that provides the high-frequency Although any crystal can be operat- 1015 CM = 2 ()218π 6 ×× 35. 37 10−3

The model values can be applied to a SPICE circuit simulation. The effec- tive motional capacitance for series resonance is 2.2 femtofarads. (Yes, that’s 10–15.) These are typical crystal model values.

OSCILLATOR DESIGN Digital IC clock oscillator circuits invariably use a Pierce oscillator, which is a derivative of the Colpitts oscillator. The Pierce topology lends itself well to CMOS IC design. The gain element need only be a single high-speed logic inverter with low propagation delay. The intrin- sic IC pin and PCB capacitances to ground can all be conveniently absorbed into the required crystal loading capaci- Exceptional tance. The crystal merely replaces the Professional Featu res – Price inductor in the original Colpitts cir- cuit. Figure 3 shows a Pierce circuit 34 Channels sampled at 500 MHz modified for overtone operation with the addition of an LC tank circuit. Sophisticated Multi-levelTMulti-level Triggering Because of the high gain of the logic inverter, you can safely assume there Transitional Sampling //Timi Timing and State will be enough loop gain for oscillation. Therefore, you need to consider only the Connect this indispensable tool to your PC’s phase criteria. For oscillation, the USB 1.1 or 2.0 port and watch it pay for itself within hours! required total loop phase shift of 360°

is met by the inverting amplifier’s nomi- 500 MHz Sampling / Timing Mode (Internal clock) Interpreters for I2C, SPI and RS232 nal phase shift of 180°. The parallel res- 200 MHz Sampling / State Mode (External clock) Integrated 300 MHz Frequency Counter onating crystalWWW.GiURUMELE.Hi2.RO and loading capacitors Multi-level Triggering on Edge, Pattern, Event +6V to -6V Adjustable Logic Threshold form a pi network referenced to ground, Count, Group Magnitude/Range, Duration etc. supports virtually all logic families Real-Time Hardware Sample Compression adding another nominal 180° of phase Full version of software free to download Qualified (Gated) State Mode Sampling Mictor adapter available lag. The lag resistor (RLG) and the crys-

tal loading capacitor (CL2) add a small www.pcTestInstruments.com extra phase lag to make up for any Visit our website for screenshots, shortcomings in the overall loop phase specifications and to download the shift due to circuit losses. easy-to-use software. In practice, the crystal operates at or Intronix Test Instruments, Inc. Tel:(602) 493-0674 Fax:(602) 493-2258 near the peak of the positive reactance www.pcTestInstruments.com at the onset of parallel resonance or

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 57 58.qxp 10/26/2006 11:24 AM Page 1

WWW.GiURUMELE.Hi2.RO 2608017 bate.qxp 11/2/2006 10:57 AM Page 59

ed in an overtone, crystals manufac- the overall phase lag below the 360° of the deviation in inductance from the tured for overtone applications must phase criteria. The network should nominal design value or about 4.5%. have low loss and be cut to enhance the also provide a nearly –90° (capacitive) Ideally, the inductor self-resonant mechanical resonance at the desired phase lag at the overtone frequency. frequency should be appreciably above overtone. Therefore, overtone crystals This is met by a simple LC parallel the operating frequency. Looking at

are special. Typically, the maximum ESR resonant circuit circuit formed by CL2 the data for a typical surface-mount

of the crystal is specified as 40 Ω. This and LT. The resonance is situated mid- chip inductor, the Taiyo Yuden limit has proven to be sufficiently low way between the fundamental and the LEM2520 series of 0603-style chip loss without affecting production yield. overtone frequency (i.e., at two-thirds inductors easily fulfill the requirement The overtones can be simply modeled as of the third overtone frequency). The with such a modest inductance. The additional series resonant circuits to LC circuit is not critical in its resonant LEM2520 has an inductance of 560 nH the fundamental series resonance. frequency, but it needs sufficiently high (10% tolerance), a minimum self-reso- To achieve overtone operation, the Q to ensure the circuit tolerances are nant frequency of 300 MHz, a minimum circuit must suppress the crystal fun- not dominated by inductor parasitic quality factor of 30 (measured at 25.2 damental mode and ensure an overall losses and can be defined by design. MHz), and a DC resistance of 0.25 Ω. loop phase shift of 360° with a gain With the LC resonance at two-thirds Note that Q = ωL/ESR. Assuming Q greater than 1.0 at only the required of the third harmonic frequency, and is constant (it isn’t), the ESR at the overtone. There are three solutions, but assuming an inductor Q of only 20, inductor test frequency of 25.2 MHz is: only one is viable for mass production. the phase lead at the fundamental is 2π ×××× 25 2 106 560 × 10−9 The first two methods both involve approximately: 30 band-pass tuning the loop to provide − ⎛ f f ⎞ gain at only the overtone. This can be ≅− tan 1 Q⎜ RESONANCE ⎟ The ESR is 3 Ω. Strictly speaking, this f f done by making the inverter a tuned ⎝ RESONANCE ⎠ applies at only a 25.2-MHz test frequency. amplifier or adding the band-pass filter ⎡ ⎛ ⎞⎤ The chip inductor self capacitance ≅×−−1 36 118 (LC tank circuit) at one of the inverter tan ⎢20 ⎜ ⎟⎥ (C ) is derived from inductor self ⎣ ⎝ 18 36 ⎠⎦ SELF ports to filter the crystal network. It resonance: = 88° phase lead, inductive requires the filter to have a high dynam- 1 ic impedance that is resistive at the This is a healthy phase lead at the fun- CSELF = π 2 L overtone frequency (i.e., the tank circuit damental preventing any oscillation. 1 would need to be high Q and tuned to At the overtone, the phase has gone = π× × 6 2 ××−9 resonate precisely at the overtone). capacitive, approaching a –90° lag. In ()2 300 10 560 10 The filter circuit therefore requires other words, the tank circuit’s presence C = 05.p F high-Q low-loss components with virtually disappears and the circuit SELF tight tolerances to define the circuit reverts back to the crystal’s half loading But soldered onto a PCB, this will be

by design. If low-loss components capacitance (CL2), thereby enabling nor- more like 1 to 2 pF because of board with loose tolerances are chosen, then mal oscillator operation (see Figure 3). parasitic capacitance.

the circuit would require a manual CT is simply a DC block. It must be calibration step in the manufacturing INDUCTOR CONSIDERATIONS large enough to bring the unwanted series

process to set the tank resonance. For a quick ballpark calculation of resonance with LT well below and out of You would need a high-quality inductance, the required inductance is: the way of the crystal’s fundamental reso- inductor with a self-resonant frequency nance. When C is 10 nF, the tank series 1 T well above my 54-MHz requirement. LT = resonance will be an acceptable value: ⎛ 2 ⎞ 2 ⎜2π f⎟ () C + C This will limit any surface-mount chip ⎝ 3 OVERTONE⎠ L2 SELF 1 inductor value below 1 µH and there- Tank series resonance = 2π L × C fore limit the possible Q. Air cored Allowing 5 pF for inductor self capaci- = 1 coils would be far better, but they are tance (C ) and strays, the nominal SELF 2π 560 nH × 10 nF more bulky and not generally conven- 32-pF loading capacitance (C ) is L2 = 213. MHz ient for high-volumeWWW.GiURUMELE.Hi2.RO manufacturing. reduced to 27 pF: 1 The first two solutions are unaccept- At the crystal’s fundamental fre- Required inductance = ⎛ 2 ⎞2 able for commercial mass production. ⎜2π× × 54 MHz⎟ quency, the tank circuit will be above ⎝ 3 ⎠ The third method is for phase control its series resonance and have a net × (27 pF + 5 pF) using an LC tank circuit. The require- inductive reactance. This adds a ments can be met without the afore- = 611 nH healthy 80°-plus phase-lead to the mentioned tolerance issues by simply Standard inductor values follow the loop, thereby preventing the overall providing a network that adds a posi- E24 series, so choose 560 nH as the 360° phase shift requirement.

tive reactance +jX (or inductive) at the nearest preferred value. The nominal RF provides DC feedback to bias the fundamental frequency of 18 MHz. tank resonant frequency is not critical CMOS inverting logic buffer into a This prevents oscillation by reducing and will only change by the square root class A operation to act as a quasi-lin-

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 59 2608017 bate.qxp 11/2/2006 10:57 AM Page 60

ear amplifier. It remains a sufficiently and CL2: This enables you to derive the root high-value resistance so as to not mean square voltage and current val- × unduly load the crystal circuit. CL1 = 2 specified crystal load ues by reading the peak-to-peak values Typical values are from 1 to 22 MΩ. displayed on the oscilloscope. × 1 This resistance is often provided inter- CL2 = 2 crystal load + ω×2 L nally with IC oscillator circuits. T FREQUENCY ACCURACY At the overtone frequency, the LC My 54-MHz crystal requires 16 pF The circuit must be adjusted to the

tank will have gone through resonance of loading. As a result, CL1 is 32 pF. specified loading capacitance for the and become nearly all-capacitive. But at the third overtone, the actual crystal to operate at the correct fre-

Consider CL2 and LT. The loading CL2 must be the following due to the quency. The total effective loading

capacitance CL2 will be partly neutral- presence of the inductor: capacitance will be affected by all of the ized by the inductance. The inductor discrete capacitors plus all of the stray 1 can be viewed as a negative capacitor, C = 32 pF + = 32 pF + capacitance from the crystal terminals L2 ω×2 L reducing the capacitance of C . Let’s T to ground and between the crystal pins. L2 ⎡ ⎤ call the net reactance formed by LT, ⎢ 1 ⎥ Due to variations in board layouts and C X , the two reactances in ⎢ ××6 π 2 ××− 9 ⎥ board dielectrics, the circuit will need L2 EFFECTIVE ⎣()54 10 2 560 10 ⎦ parallel. Now for just two reactances to be trimmed by adjusting CL1 and CL2 in parallel: = 32 pF + 15.. 51 pF = 47 5 pF in order to absorb the PCB strays into the effective loading capacitance. X X × X X = PRODUCT = CL2 LT Now you adjust for the inductor self- With typical values for C and C EFFECTIVE + L1 L2 XSUM XLT XCL2 capacitance (CSELF) of 5 pF and any of only 10 to 32 pF, it’s important to Thus: strays at the circuit junction. Hence, offer no additional loading from any the actual discreet value of C is: test equipment. Even the Tektronix 1 L2 C = and LeCroy active scope probes cur- EFFECTIVE ω XEFFECTIVE −− CLSTRAYS2 = 47.pF 5 5 pF C rently on the market have an input

Therefore, substituting for XEFFECTIVE: capacitance of around 1 pF, which is a I would choose 39 pF for an initial E24 noticeable percentage loading of the ⎛ 1 ⎞ ⎜ + jω L⎟ design value. C and C capacitors. ⎝jCω T⎠ L1 L2 C= L2 This drops the tank resonance by To correctly calibrate the circuit, EFFECTIVE ⎛ 1 ⎞ jω⎜ xjLω ⎟ roughly √32/47, but this does not mat- selected crystal samples should be ⎝ jCω T ⎠ L2 ter in practice because the phase lead obtained from the supplier, which are This simplifies to: at 18 MHz has such a large margin. A spot on nominal frequency and nomi- ⎛ 1 ⎞ SPICE simulation with an inductor of nal loading capacitance. The capaci- C = ⎜C − ⎟ L2 EFFECTIVE L2 ω2 560 nH and 7 Ω of ESR showed a tors also need COG or NPO dielectric ⎝ LT ⎠ phase lead of +70° with the 15.5 pF with a tolerance of 1% or better, or

The inductance acts as a “negative added at CL2. The tank resonance had they are selected for nominal capaci-

capacitance,” reducing the CL2 value by: fallen to around 32 MHz. tance using a precision LCR meter Consider the 560-nH inductor. This accurate to 0.1% 1 2 is a lower, more suitable value for a The inductor tolerance of 5% is not ω L T chip inductor than the differential so critical. The tank resonance is pro- Ignoring the inductor for the moment, design I’ll cover later. I chose the near- portional to the square root of the the loading capacitance seen by the est E24 value of 560 nH. inductance. This reactance is virtually

crystal is simply CL1 and CL2 in series. Finally, because of the specific PCB removed at the overtone frequency.

The effective capacitive load is then: layout, the value of RLG is adjusted 111 during development for a reliable NO BUFFERED CLOCK = + start-up and crystal drive power limi- If there is no buffered clock port CLOAD CL12C L C × C tation. Monitoring the crystal current available from the IC, then the only C= L1 L2 LOADWWW.GiURUMELE.Hi2.RO with a wideband clip-on current probe acceptable way to test the circuit is to CL1 + C L2 and oscilloscope checks the crystal use a sniffer cable (coax with the first

CL2 is modified to CEFFECTIVE. The actual power dissipation. Use the smallest 5 cm of screening stripped back) with

CL2 must be the following to accom- possible wire loop for the probe. an accurate spectrum analyzer fitted modate the partial neutralizing by the I use a simple equation for deter- with a TCXO-based clock. The typical inductor: mining crystal power: initial frequency accuracy for these 1 ≈ ()instruments is 0.5 PPM. The sniffer C + Crystal power RMS crystal current EFFECTIVE ω×2 L probe should be held 5 to 10 cm from T × ()RMS drive voltage aat the crystal the circuit so that there is minimal The usual design procedure is to Because of the high Q filtering, the coupling. It may be useful to disable

equally split the loading capacitors CL1 crystal current is a quasi-sine wave. all of the digital circuitry and memory

60 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2608017 bate.qxp 11/2/2006 10:57 AM Page 61

in the unit for this measurement. the internal cabling from the main digital The procedure involves setting the board in addition to the usual common spectrum analyzer’s center frequency to filtering at all of the digital I/O ports. the nominal clock frequency (54 MHz in this example). First, set the resolu- DIFFERENTIAL OSCILLATOR tion bandwidth to minimum and the The modern IC approach to the amplitude sensitivity to maximum. overtone oscillator is to use a balanced Following this, turn on the video aver- circuit that generates a differential sig- aging and initially set the analyzer nal across the crystal using a push-pull span to 10 kHz. Next, fix the sniffer arrangement of CMOS inverting gain [2] cable (around 5 cm from the clock out- Figure 4—The differential signal developed across the elements (see Figure 4). The circuit put pin). When you locate the signal, crystal gives a balanced signal around the supply rail uses transconductance instead of volt- reduce the SPAN setting (the horizon- and ground. The result is a low net signal current enter- age amplifiers, where the external net- tal frequency range) to the minimum ing the supply and ground terminations. work impedance forms the load to setting (typically 1 kHz). You should each amplifier. This is necessary with then adjust the spectrum analyzer’s which I work is RF radiation from the the back-to-back configuration. amplitude sensitivity for the signal current loop formed by the crystal and Otherwise, with voltage amplifiers, peak to be between 80% and 90% of loading capacitors. Laying the PCB signal each oscillator port would look into full scale. Finally, set the cursor to traces to have minimal loop area and the low output impedance of one Peak Search and read the frequency. arranging the loading capacitors to be inverting amplifier and short the exter- star-point connected to the ground nal network. Transconductance ampli- BUFFERED CLOCK plane can minimize the problem. fiers are volt-in to current-out devices. If a buffered clock output is available, The common asymmetric circuit As a result, they have high output there should be no problem with loading. accentuates this problem by not only impedance and avoid the problem. You need to use only the frequency/timer creating additional current loops with By using star-point connections to counter with a minimum resolution of the LC tank circuit, but also placing ground and the internal IC supply rail, eight digits. It should be fitted with a an unbalanced signal current in the the net signal current over an entire TCXO frequency standard of 3-PPM ground plane. This can add to the cycle into the ground plane and the sup- accuracy (e.g., the 12-digit, 225-MHz overall common-mode noise generated ply rail is zero. This reduces the need for Agilent 53132A universal timer/counter within the PCB. efficient high-frequency local supply fitted with a TCXO oven option). Good commercial design today decoupling. In addition, the high output Alternatively, you can use a low-cost requires PCB layouts to have inherent- impedance of the transimpedance invert- 200-MHz frequency/timer counter like ly low common-mode emissions in ers provides good rail noise rejection just the Thurlby Thandar Instruments TF810. order to meet the international EMC like the current mirrors of a typical lin- Use the external precision reference thresholds. In ideal situations, this does- ear IC. Figure 4 illustrates the concept option. The reference should be precision n’t add the costs of extensive shielding without the amplifier bias circuit detail 10 MHz at TTL levels and traceable to and common-mode filter components. that makes it all practical. the National Physical Lab (NPL), which I recently looked inside a competi- maintains the U.K.’s national standards. tor’s product and found a poor PCB lay- DIFFERENTIAL LC TANK You can also obtain a suitable preci- out. The company had added expensive The tank circuit performs the same sion reference source from a GPS time common-mode ferrite chokes to all of function as in the asymmetric design and reference receiver such as with a slight refinement. The the now obsolete HP58503A or tank circuit is split symmetri- 3.00 k the currently available Tank resonance cally to preserve the balanced Symmetricon 58503B. In addi- 2.00 k network impedance to ground Z tion to GPS, you also have the 1.00 k at each crystal terminal. option (in the U.K.) of using an Remember: the common-mode 0.00 AM off-air referenceWWW.GiURUMELE.Hi2.RO PLL receiv- rejection capability of any dif- Phase lead of 9° at the fundamental er that’s tuned to the Rugby or ferential circuit is effective 30.00 Droitwich long-wave AM carri- only by making the shunt 0.00 ers that are traceable to the NPL. impedances from each differen- –30.00 tial terminal to ground sym- GOING DIFFERENTIAL –60.00 metrical. Splitting the series- Phase degrees –90.00 Crystal clock oscillators can 10 100 resonant capacitor also helps

be a source of EMC problems if Phase lag of –85° (doubling the value of each you aren’t careful with the lay- at 54 MHz tank capacitance). It makes it a out. One well-known issue in Figure 5—Take a close look at this SPICE simulated impedance Bode plot more practical value that’s less the set-top box design field in of the tank network seen by the crystal. comparable to the circuit

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 61 2608017 bate.qxp 11/2/2006 10:57 AM Page 62

80 work impedance ground seen from each crystal terminal seen by the crystal. is identical. The loading and the stray 60 The SPICE circuit capacitances to ground should be con- simulation of the nected to a common star ground point 40 Increasing Optimum value optimized damping for minimum noise injection into the around 300R Z Phase at 18 MHz fundamental suppresion gave 9° at 18 MHz ground plane. Finally, the loop formed

0 and –85° at 54 MHz. by the crystal and loading capacitors The shortfall in should be laid out to achieve minimal –20 phase lag was due to loop area. This minimizes RF radiation circuit loss. It was to nearby circuits. –40 100R 200R 300R 400R 500R made up by the Figure 7 shows a tried-and-tested lay- R T amplifier propaga- out. The oscillator signal traces are Figure 6—I plotted the damping resistor value versus the LC tank phase.You can tion delay and the brought from the IC at a minimum trace see the critical region for R . T RC lags RLG1, RLG2, width of 0.005” separated by the same

CL1, and CL2. Figure 6 amount in order to reduce board capaci-

strays. The LC tank is wired across shows the damping resistor value RT tance and (more importantly) the mini- the crystal in keeping with the differ- versus phase lead at the fundamental of mum current loop area. The loading ential operation; otherwise, you need 18 MHz. This indicates the optimum capacitors are star-point grounded into

two matched tank circuits at each RT value to be around 300 Ω. the ground plane. Symmetry in the cir- crystal terminal to ground to maintain My circuit required an inductance cuit layout is maintained in order to keep a balanced network around ground. between 2.7 to 3.3 µH. This was just the inherent common-mode isolation of One disadvantage is the inductance, about practical for a surface-mount chip the differential circuit with balanced which like the crystal sees the loading inductor because such a large chip impedances to ground at each crystal ter- capacitors in series halving the effec- inductance meant the self-resonant fre- minal. The traces to the through-hole tive parallel tuning capacitance and quency was just high enough. connections of the HC49 leaded crystal therefore doubling the required size of Datasheets typically specify self-res- fold back on themselves in “bifilar-wire” the inductance. Placing the inductor onance at 41 MHz. The modest Q fac- fashion to cancel the trace inductance across the crystal adds another com- tor of 45 was less of a requirement and avoid spur connections to the crystal plication. If the inductor Q is too high, because the tank circuit had been terminals. Small spur lengths of high-fre- the tank resonance will become the damped anyway. However, this meant quency signal traces make good antennas! dominant loop resonance and the cir- the circuit loss couldn’t have been as Assuming you are using a multilay- cuit will oscillate at the LC tank fre- well defined by the series damping resis- ered board, the capacitive loading on

quency. With the Pierce circuit, the tors RT1 and RT2 as I had wished. Figure 4 the clock circuit is minimized by cut- crystal merely replaces the inductor of is the differential overtone circuit. ting a window through the ground the original Colpitts circuit. To pre- planes. The edges of the ground vent this and to provide a defined GOOD PCB LAYOUT PRACTICE planes, and any adjacent copper phase control at the suppressed funda- With a clock frequency starting at ground flooding on the signal and mental, a damping resistor is placed 54 MHz, you can reckon on dealing power layers, are stitched with vias to across the series resonance capacitance. with major harmonic levels to at least reduce RF ground impedance. This can be simplified to a parallel res- the tenth, or 540 MHz. In a mixed-sig- onant LC network with lossy induc- nal system like a set-top box, this can GUARDING THE CLOCK tances (L) and capacitances (C). Although cause intermodulation products in the When it comes to clock signal it’s slightly simplified, this version still RF front-end mixers that

requires a lot of tedious math in order to in turn produce unwant- Ground planes derive the overall phase/frequency char- ed in-band spurs. This is stitched together acteristic for which standard solutions a real headache for ana- can be found in older reference books. log video channels. You

Therefore, it wasWWW.GiURUMELE.Hi2.RO decided to model the must lay out the PCB LT RT1 actual distributed network in SPICE for carefully in order to CT1 RT1 XTAL 1

the sake of accuracy and development maintain the good EMC art of IC XTAL 2 p time. The values of the damping resistors properties of the differen- RD1 C were iteratively adjusted to give a small tial clock. T2 Clock RD1 but adequate positive phase to suppress In order to fully the fundamental at 18 MHz. This was exploit the noise-cancel- also the maximum practical damping ing properties of the dif- Cut out in ground plane that could be applied to suppress the ferential design, the cir- Ground plane tank inductor Q. cuit must be symmetri- Figure 7—A good PCB layout is important for signal integrity and low common- Figure 5 is a Bode plot of the total net- cal. The impedance to mode board emissions.

CIRCUIT CELLAR® 62 Issue 197 December 2006 www.circuitcellar.com 63.qxp 10/26/2006 11:10 AM Page 1

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

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

G r e a t P r o d u c t s . Awesome Prices. 2608017 bate.qxp 11/2/2006 10:57 AM Page 64

integrity and low common-mode result of the minimal circuit loop area. REFERENCES board emissions, a good PCB layout The same advantages apply when includes guard traces to each high- you use guard tracing with a multilay- [1] MtronPTI, “Understanding Quartz speed clock signal and high-frequency er board. The guard trace provides the Crystals,” www.mtronpti.com/pdf/ signals in general. Before the days of clock signal with a private return contentmgmt/understanding_quartz multilayer boards and ground (more path, taking the high-frequency signal _crystals.pdf. accurately, reference) planes, there current out of the common and often [2] Broadcom Corp., “BCM7038: Dual were double-sided boards without a the overworked system ground plane High-Definition Digital Video, ground plane. If you wanted to send a with its mere 35 µm of copper foil! System-on-Chip Solution for Cable, fast signal around a board, you had to How do you ground the guard Satellite, and DTV,” www.broadcom. provide a well-defined return signal traces? Trial and error has shown that com/products/Cable/Digital-TV- path or guard trace. The guard trace the best arrangement is to pin the Solutions/BCM7038. was placed along the outgoing signal guards at the near and far ends to the path or on the opposite side of the immediate local grounds. On a large SOURCES PCB shadowing the outward signal system chip, this can mean locating 53132A Universal timer/counter trace. This provided a low-inductance the nearest associated ground pin to Agilent Technologies, Inc. signal path with a smooth characteris- the IC’s internal circuit. I www.agilent.com tic impedance. The low inductance comes from the field cancellation of Alan Bate ([email protected]) BCM7038 VLSI IC the adjacent go and return signal cur- holds a degree in electrical and electron- Broadcom Corp. rents. The guard trace is therefore the ics engineering from the University of www.broadcom.com return path of choice for the high-fre- Leeds. He is a senior hardware design LEM2520 Inductor quency signal. engineer for Pace Microtechnology. Taiyo Yuden (U.S.A), Inc. Guard tracing generates good signal www.t-yuden.com integrity because of the well-defined PROJECT FILES transmission path with no impedance For a list of useful resources, go to TF810 Frequency counter discontinuities and no reflections. Low ftp://ftp.circuitcellar.com/pub/Circuit_ Thurlby Thandar Instruments crosstalk and low radiation are the Cellar/2006/197. www.tti-test.com

WWW.GiURUMELE.Hi2.RO

64 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 9/27/2006 11:58 AM Page 1

WWW.GiURUMELE.Hi2.RO 2612012-Eady.qxp 11/2/2006 11:21 AM Page 66

APPLIED PCs by Fred Eady

Ethernet on a Chip This month, Fred describes his recent work with the ASIX Electronics AX11005 development kit. Using a Keil C compiler and some Digital Core Design hardware, he created a powerful Ethernet development suite that now enables him to produce some pretty exciting Ethernet- based equipment.

I recall standing in a room full of this go-round, I got to take a look at its instructions using 16-bit large pro- Token Ring equipment some years ago new AX110xx development kit, which gram addressing mode, which calls on and one of my coworkers looked at all is based on the new AX11005 single- the 80C51 instruction set. A 16-KB of the new stuff we had just installed chip microcontroller with TCP/IP and SRAM area is used for program flash and said, “Ethernet is dead.” We both 10/100-Mbps fast Ethernet MAC/PHY. memory mirroring. In addition, 32 KB should have turned around and took a of on-chip user SRAM is allocated in closer look at the new Ethernet stuff ETHERNET SoC the external data memory area. the other guys were installing on the The AX11005 is designed to do a bit It almost seems as though the other side of the room. Why? That more than just service Ethernet AX11005’s 10/100 Ethernet capability “dead” Ethernet equipment is still in frames. The core of the AX11005 is a is an afterthought because the micro- use to this day, while the Token Ring fast (up to 100 MHz) 100% binary- controller supports a 1-Wire interface, stuff is nowhere to be found. compatible clone of the venerable three RS-232 ports, I2C, PWM, count- Ethernet technology has come a 8051. The 19-bit flat program address- er/timers, three SPI masters, a SPI long way since then. It has become ing mode uses the 80C390 instruction slave, and 16 bits of general-purpose faster and can travel over many types set to enable bankless 0- to 512-KB I/O. The idea behind the multitude of of media. In essence, the core of access of on-chip program flash mem- communications interfaces is to put Ethernet technology hasn’t really ory. The AX11005 can also execute the AX11005 into an application space changed that much over that can convert RS-232 the years. However, the serial data to Ethernet way Ethernet is used frames or communicate 512-KB changes daily. For 32 GPIOs 32-KB Memory arbiter with a ZigBee radio via Flash SRAM and bootloader instance, Ethernet is now memory the SPI port and bidirec- being incorporated into Local bus/Digiport tionally transfer data

embedded devices just as I2C Three timer/ between the ZigBee PAN Debugger regularly as RS-232. In counters and Ethernet link. With SPI fact, Ethernet is more and Watchdog 1T 8051/80390 Clock its many ways of com- more becoming a familiar 1-Wire timer 100 MHz generation municating, the AX11005

resident on microcon- Power Interrupt is powerful enough to act Three UART troller silicon. WWW.GiURUMELE.Hi2.ROWe’re all management controller as a network processor

watching the Ethernet-on- Five PCA serving other link- TCP/IP 10/100-Mbps microcontroller revolu- Offload Ethernet attached or physically tion happen with all-in- engine MAC attached microcontrollers. 10/100-Mbps one parts emerging from DMA A single 3.3-VDC Ethernet Engine Microchip Technology, PHY power source powers the Freescale Semiconductor, AX11005. Keeping with and ASIX Electronics, to the system-on-a-chip Figure 1—If you ignore the TCP/IP offload engine and the 10/100-Mbps MAC, the name only a few. AX11005 looks like a high-end microcontroller. Here you see 32 bits of general-purpose I/O, (SoC) concept, an on-chip Thanks to the folks at which is correct for the AX11005’s big brother, the AX11015. The AX11005 supports only 1.8-VDC regulator feeds ASIX Electronics. During 16 bits of I/O. the CPU core. The

66 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612012-Eady.qxp 11/2/2006 11:21 AM Page 67

HAD2 uses USB Full Speed technolo- gy to interface the AX11005’s internal debugging system to the debugging application running behind the USB interface on a PC. My HAD2 hardware is from Digital Core Design, which also supplied the Windows-based debugging application software. The HAD2 and Windows debugging soft- ware come bundled together. The Photo 1—The HAD2 is powered by the USB port and HAD2 debugging software package is manages communications between the AX11005 on- fully compatible with all existing chip ICE circuitry and the debugging application run- ning on a companion PC. 8051/80390 C compilers and assem- blers. In addition to debug duty, the debugging software can be used as a AX11005 requires only a single 25-MHz software simulator too. Photo 2—This is one busy board. The HAD2 connects crystal for all of its internal clock gener- The HAD2 package was originally using the shrouded and keyed pins below the Ethernet magnetics. Move down below the eight-position dip- ation processes. There’s even a built- designed for SoC designers that needed switch and note the inclusion of screw terminals to in, on-chip, power-on-reset circuit. the capability of debugging applica- facilitate RS-485. The AX11005 boot EEPROM can be The AX11005 will most likely find tions before they were to be commit- seen in the upper-left corner. itself embedded in an install-it-and- ted to silicon. It’s pretty obvious now forget-about-it environment, so sim- that the AX11005 contains a Digital plete and needs nothing else in the ple methods of upgrading the SoC’s Core Design (DCD) 8051/80390 IP way of features to make it better. But firmware must be available. The Core, because the AX11005’s DCD IP it does get better. You can also use the AX11005 can accept updates by way Core is specifically designed to work DoCD system to program the target of the Ethernet port or the UART. with the HAD2 and the DCD Debug device’s program flash memory. You can also use the UART to pro- IP Core. This mix of IP cores and the gram the device. HAD2 is called DCD on Chip Debug AX110xx DEVELOPMENT KIT I’m particularly interested in the System (DoCD). I have an AX11005 part, so you can TCP/IP offload engine (see Figure 1). But The Debug IP Core is a real-time safely assume that all of the pre-sili- before I delve into that, let’s look at hardware debugger that enables a full con work on it has been done. That what it takes to support the AX11005. nonintrusive view of the on-chip regis- means you can use the HAD2 in con- ters, memories, and peripherals associ- junction with the AX11005’s debug IP I’VE BEEN HAD! ated with the DCD IP Core, which is Core. To help facilitate faster proto- From what I’ve seen thus far, the the 8051/80390 IP core in this case. type cycles, ASIX offers the AX11005 AX11005 is a pretty heavy little The DoCD debugging system doesn’t development kit. microcontroller. It would be close to require any resources from the target. My AX11005 development board is impossible to attempt to apply an Thus, all of the target device’s features shown in Photo 2. All of the microcon- application to the AX11005 hardware and peripherals can be accessed during troller’s bells and whistles are accessi- without a good debugging system. The the debug phase. As you’ve already ble by pin or connector. The schematic AX11005 doesn’t disappoint. It comes ascertained, the DoCD system is com- diagram for the AX11005 development standard with an on-chip in-cir- board is six pages deep. So, cuit emulator feature that’s instead of trying to nudge the designed to interface with a piece schematic into this column, I of external ICE hardware. The posted it on the Circuit Cellar task assigned to the ICE is to FTP site for easy access. manage communications Although the AX11005 is an between the AX11005’sWWW.GiURUMELE.Hi2.RO on-chip awesome piece of silicon, the ICE circuitry and a software kit’s real strength lies in the debugger application running on a abundance of AX110xx soft- PC. The external ICE hardware ware modules and utility pro- that mates with the AX11005’s grams. There is a source code on-chip ICE circuitry is called the module supplied for every Hardware Assisted Debugger AX11005 peripheral. AX11005 (HAD). The latest version of utility programs that come Photo 3—The MicroEngineering Labs LAB-XUSB shown here was really HAD is called HAD2. As you can with the kit include a flash designed to get you started with embedded USB. I was elated to see an I2C see in Photo 1, I’ve been HAD. EEPROM socket on this board. It that meant I didn’t have to fire up the sol- memory programming utility, Powered by the USB port, the dering iron and build up the EEPROM circuitry from scratch. HEX2BIN utilities for both

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 67 2612012-Eady.qxp 11/2/2006 11:21 AM Page 68

DOS and Windows, and a TFTP/DHCP Listing 1—Here’s an example of a standard read register driver call versus a set IP adder API call. The server application (just to name a few). AX11005 driver and API code is not commented too heavily, but it is relatively easy to follow and understand. My AX11005 development board The core of the I2C code was pulled directly from the driver source code that comes with the Custom came preloaded with a TCP/IP stack Computer Services PIC C package. All I really had to do was match up my code’s I2C interface pins with the and sample code for what the ASIX LAB-XUSB and write the EEPROM read/write code in the main function.

folks call a “lightweight” TCP/IP // Examples of driver and API routines in the stoe.c code module stack. It came on the kit’s CD-ROM. void stoe_ReadReg(U8_T regaddr, U8_T XDATA* pbuf, U8_T length) A comprehensive software user’s { U8_T isr; guide goes into detail about connect- isr = EA; ing your application to the software EA = 0; modules’ internal API function calls. TCIR = regaddr; while (length—) For instance, to use the AX11005’s pbuf[length] = TDR; TCP/IP offload engine to set the IP EA = isr; address, all that needs to be coded is a } /* End of stoe_ReadReg */

call to the STOE_SetIPAddr() func- void STOE_SetIPAddr(U32_T ip) tion. STOE refers to an API call that { works against the TCP/IP offload if (ip != PNetStation->StationIP) { engine. The source code also uses PNetStation->StationIP = ip; stoe (lowercase) to delineate driver stoe_WriteReg(STOE_IP_ADDR_REG, (U8_T XDATA*)&PNetStation->StationIP, 4); calls from API calls. Examples of the } } /* End of STOE_SetIPAddr*/ API and driver calls I’ve referenced are ********************************************************* shown in the top part of Listing 1. //Simple CCS PIC code to modify the contents of the AX11005 Boot EEPROM The only hardware change you will #include <18f4550.h> #device *=16 have to make to give the HAD2 access to the AX11005 is a bit change within #fuses HS,NOWDT,NOPROTECT,NOBROWNOUT,NOLVP,NOWRT the Atmel AT24C02B EEPROM. Bit 7 #use delay(clock=20000000)

of the byte located at address 0x01 #ifndef EEPROM_SDA within the AT24C02B determines if the CPU debugger pins are muxed to #define EEPROM_SDA PIN_A4 #define EEPROM_SCL PIN_A5 the Ethernet status LEDs or to the HAD2. The default state of bit 7 is a #endif one, which muxes in the Ethernet sta- #use i2c(master, sda=EEPROM_SDA, scl=EEPROM_SCL) tus LEDs. It’s easy to lash up a little #define EEPROM_ADDRESS BYTE PIC I2C interface and change the bit. I #define EEPROM_SIZE 256 used a MicroEngineering Labs LAB- void init_ext_eeprom() { XUSB, which already has the socket laid output_float(EEPROM_SCL); in for an I²C EEPROM (see Photo 3). output_float(EEPROM_SDA); With a little bit of help from my }

Custom Computer Services PIC C BOOLEAN ext_eeprom_ready() { compiler, I had the EEPROM bit int1 ack; banged to zero in a couple of minutes. i2c_start(); // If the write command is acknowledged, ack = i2c_write(0xa0); // then the device is ready. The compiler is great for stuff like i2c_stop(); this because it’s fully tilted toward the return !ack; PIC architecture. It includes built-in }

PIC-specific functions that take most void write_ext_eeprom(BYTE address, BYTE data) { of the effort out of coding things like while(!ext_eeprom_ready()); I2C, SPI, and RS-232. My little bit- i2c_start(); WWW.GiURUMELE.Hi2.ROi2c_write(0xa0); twiddling C code is shown in the i2c_write(address); lower portion of Listing 1. i2c_write(data); i2c_stop(); KEIL’S BEEN HAD2! } The AX11005 software guide tells BYTE read_ext_eeprom(BYTE address) { you up front that Keil’s C develop- BYTE data;

ment tools were used to craft the while(!ext_eeprom_ready()); AX11005 software drivers, so it would i2c_start(); be a wise decision to continue to use i2c_write(0xa0); i2c_write(address); Keil’s C platform for your develop- i2c_start(); (Continued) ment work. One advantage of sticking

68 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612012-Eady.qxp 11/2/2006 11:21 AM Page 69

this sense is the automatic handling of Listing 1—Continued. the Layer 2 ARP Cache, ARP requests, i2c_write(0xa1); ARP responses, and the automatic pro- data=i2c_read(0); cessing of IP packet headers in Layer 3 i2c_stop(); (see Table 1). return(data); } If you have studied and written TCP/IP stacks, you know that lots of BYTE data_in,data_out,x; code time is absorbed in the handling void main(void) of packet headers as they pass from { layer to layer within the stack. The init_ext_eeprom(); term “automatic” here with relation data_in = read_ext_eeprom(0x01); data_out = data_in & 0x7F; to Nontransparent mode means that write_ext_eeprom(0x01, data_out); the AX11005 hardware takes care of data_in = read_ext_eeprom(0x01); the headers instead of your software. ++x; } When a socket is established, the TOE submodule grinds out a memory segment that includes a buffer descrip- with the C tools is that the Keil C let’s take a look at how it works. tor page (BDP), a receive packet buffer tool suite natively supports all of the The AX11005 Ethernet module con- ring (RPBR), and a transmit packet AX11005/8051/80390 stuff that you sists of a 10/100-Mbps Ethernet MAC buffer ring (TPBR). If you don’t need to need to drive AX11005 code. In addi- and PHY interface. The thing that modify the buffer sizes, the TOE sub- tion, when you initially install the really makes the module interesting module will allocate 8 KB of RPBR DoCD drivers, the necessary HAD2 and different is the TCP/IP offload and 4 KB of TPBR memory space. drivers and support files are automati- engine (TOE). Thus, the module is That’s pretty much in keeping with cally inserted into the Keil C tool based on a trio of submodules: the other buffer allocations I’ve made with suite framework. TOE, the MAC, and the PHY. Module other Ethernet engines. There’s Adding the DoCD drivers to the driver source code for the TOE, MAC, enough room for a couple of incoming Keil µVision IDE pulls everything and PHY is included with the packets and plenty of space to queue together into a single seamless AX11005 development package. As I up transmit packets as you so desire. AX11005 development environment. showed you earlier, API calls are min- The BDP is fixed at one page of 256 The µVision IDE incorporates the gled in with the TOE and MAC driver bytes. Transparency mode and buffer DoCD drivers into its debugging sys- source code modules. memory sizes are statically defined tem and enables the AX11005 applica- The TOE submodule handles all of using standard #define constructs in tion programmer to edit, compile, pro- the TCP/IP offload engine functionali- the stoe_cfg.h file, which is part of the gram, run, and debug without having ty. There are two modes in which the TOE submodule code set. to leave the µVision window. TOE code can execute and both of A TOE header is employed regard- Showing you a screenshot of a debug them support TCP/IP, UDP, ICMP, less of the Transparency mode. Every screen full of little windows and data and IGMP hardware checksum func- other Ethernet engine I’ve ever worked would be confusing at best. So, Photo 4 tions. Transparent mode doesn’t sup- with has provided the length of the is a screenshot of the Load window that port the AX11005’s hardware accelera- packet and a pointer to the next pack- supports the AX11005 inside the µVision tion functionality, but Nontransparent et in some type of header arrange- environment. This should give you an mode uses the services of the ment. The AX11005 is no different. idea of how smooth the DoCD/µVision AX11005’s hardware acceleration The first 2 bytes of the 6-byte TOE really is. package. Hardware acceleration in contain the pointer to the next packet.

ETHERNET MODULE Offset address Bit field Field name Size Description Now you knowWWW.GiURUMELE.Hi2.RO00h bit[15:0] NPR 2 bytes Next pointer which hardware and 02h bit[11:0] Length 12 bits Packet length software tools you’ll bit[14:12] BPBB 3 bits RX buffer used page number before REPP boundary (only valid when PCB = 1) need to be successful bit[15] PCB 1 bit Packet crossing boundary flag with the AX11005. 04h bit[7:0] Data offset 1 byte Data offset address of RX data payload Although the bit[15:8] Protocol 1 byte Protocol type. It should be equal to the protocol field of the IP header for IP AX11005 is a feature- packets. It should be set to 0xFF for non-IP packets. rich microcontroller, my real interest (and NPR Length BPBB PCB Data offset Protocol IP Header (for nontransparent) Data payload hopefully yours) is the 2 bytes 12 bits 3 bits 1 bit 1 byte 1 byte or Ethernet header (for transparent) AX11005 Ethernet Table 1—This is how the AX11005 sets up a packet for processing. All of the header information and the data payload can be easily module. With that, accessed by with the AX11005 driver and API calls that are provided with the AX11005 development kit.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 69 2612012-Eady.qxp 11/2/2006 11:21 AM Page 70

code seemed a bit confusing. However, there’s nothing going on here that does- n’t go on in similar implementations. Basically, the application code uses TOE and MAC submodule API calls to crank up the hardware driver firmware in the TOE, MAC, and PHY submodules.

SERIOUS STUFF The AX11005 development kit is very comprehensive. When you drop the Keil C compiler and the DoCD hardware into the AX11005 develop- ment kit mix, you create a potent Ethernet development suite that will enable you to produce some pretty heady Ethernet-based equipment. Personally, I’ve got some ZigBee ideas that I would like to apply to the AX11005. If I can pull them off, you’ll see them in a future article. From what I’ve seen thus far, the AX11005 development kit isn’t complicated. It’s Photo 4—This is a shot of the Flash Download Setup window that is found within the µVision set-up dialog area. embedded. I The check boxes make this window self-explanatory. Fred Eady ([email protected]) has more The 12-bit packet length follows the TOE submodule will add the TOE than 20 years of experience as a sys- next packet pointer. Other information header at the beginning of the trans- tems engineer. He has worked with offered up the TOE deals with packet mit packet, store the packet to be computers and communication sys- boundaries and the beginning offset transmitted in the TPBR, and kick off tems large and small, simple and address of the packet’s data payload. the mechanism that will transfer the complex. His forte is embedded-sys- The final byte of the TOE header iden- packet to be transmitted from the tems design and communications. tifies the packet’s protocol. The TOE TPBR to the MAC layer SRAM. packet protocol byte is identical to the Incoming packets will have the PROJECT FILES protocol type found in the IP header. If TOE header placed at the front of the To download the schematics for the the packet is not an IP packet, the TOE packet by the TCP/IP offload engine. AX11005 development board, go to packet protocol byte is set to 0xFF. The The packet is then stored in the RPBR. ftp://ftp.circuitcellar.com/pub/Circuit application must make sure the correct After the incoming TOE-headered _Cellar/2006/197. protocol type is contained within the packet in the RPBR, the application TOE header to avoid checksum errors. can use the TOE submodule’s basic Transparent mode will leave the driver and API calls to parse the TOE SOURCES Ethernet header intact so that layers header and access the packet data. AX11005 Development kit of the stack can process it. The The MAC submodule is used to ini- ASIX Electronics Corp. Ethernet header will immediately fol- tialize the AX11005 MAC and PHY www.asix.com.tw low the TOE header if Transparent interfaces to enable normal Ethernet PICC C Compiler mode is in play. Nontransparent mode packet transmission and reception. CCS, Inc. will strip the Ethernet header as the The application can use API calls to www.ccsinfo.com AX11005 hardwareWWW.GiURUMELE.Hi2.RO performs the header handle PHY link change events, set operations. The IP header will be placed up receive filter modes, and enable DoCD HAD2 Debugger immediately behind the TOE header wake-up functions such as Magic Digital Core Design when Nontransparent mode has been Packet and external pin wake-up. www.dcd.pl selected. The data payload will follow The PHY submodule has no API call PK51 C Compiler the Ethernet header of IP header depend- access. The MAC submodule calls any Keil ing on the Transparency mode that has functions performed by the PHY sub- www.keil.com been selected by the programmer. module. The PHY submodule primari- It’s the application’s responsibility ly checks and retrieves the PHY Media LAB-XUSB Board to populate the TOE header before mode for the MAC submodule. MicroEngineering Labs passing it to the TOE submodule. The At first glance, the AX11005 driver www.melabs.com

70 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 71.qxp 10/26/2006 11:11 AM Page 1

You need these cutting edge products to quickly solve your toughest design and measurement problems! New Products HumidiProbe / PT104 Touch-sensing ICs Video Modem USBwiz Dualcore...... dual ARM IC HumidiProbe - Temperature VPORT - MPEG4 with Web Quantum ICs- World-beating capacitive sensor USBwiz - Easily add USB Emulin...... LlNbus/J2602 emulator and Humidity Logger for PC. browser/Ethernet interface ICs for switching and control with patented fea- peripherals to your system. Includes WIZnet...... TCP/IP IC PT104 - High resolution and and built-in motion detection. tures like Adjacent Key Suppression, FATfile system for USB thumb & Hunt RTG...... instant FPGA/DSP accuracy. Platinum sensors. 352 x 240 color video streams Spreadspectrum, adjustable sensitivity. QRG ICs external USB hard drives. No Byteparadigm...... USB 2.0 I/O USB powered - no power at 30fps with 24 kbp audio in use worldwide by the world’s largest con- USB knowledge needed, plug-n-play! Systembase...... Quad UART chip supply required. Free s/ware. coding. sumer/appliance manufacturers <$1 (10K) Owasys...... embedded wireless from $241/759 96047627 $450 IC $29.95 Demoboard $59.95 2/4ch 12-bit USB scope FATfile Storage Touchpanel Controller CAN-USB Tiny USB Stepper Motor

PP298/PP300- High-perf. USB2.0- Easy-Step™ 3000 - advanced stepper pwrd scope-in-a-probe! Up to motor drive and control system for 100MS/s, 25MHz 24kS buffer. unipolar stepper motors up to 35V/3A +/-100mV to +/-20V. 20ns/div - and 3 Amps - ideal for robots/industrial 50s/div C/VBDelphi/LabView/ control – turns you into an instant VEE drivers. $643/$1127 motor control expert! from $119 Easy VGA SM PCB Adapters

microVGA - graphics adapter that OM-Adapt SM miniboards allows micros to display text & have two footprints on either graphics on any VGA monitor. side. Now use your ultra fine pitch Connect to any host micro controller, embedded device or a SMD components with more PC with a USB or serial port. useful 0.1" inline spaced holes. Clever & simple to use. $139! One-to-one pinouts. ~$10.00 Ethernet to Serial USB-Serial Adapters

EG-SR-7150MJ - ready-to-go iLCD Starter Kits - let you TR-72W - Networked logger for PS3424 - New 4channel 12-bit DLP-D - Programmable USB Serial port for laptops without serial-to-Ethernet Gateway. Simple custom-program graphics LCDs remote msmt. of ambient. Send 20MS/s USB2.0-connected/powered Security Dongle based on one! USB-COM instantly updates into your product quickly! set-up for 10/100Mbps Ethernet email or phone warnings if scope adapter. Scope, FFT, and FT232R - log use/user/expiry, older RS232 products to USB! Touch-panels too! Create - 230kbps serial. Ethernet/ PC thinks it’s using COMport up perfect LCD screens with any thresholds exceeded. Optional meter displayed simultaneously etc. Optional sophisticated Internet-enable any serial part. font & animated graphics within min. WiFi for remote locating & msmt. with . software allows customizability. to 8 channel. EG-SR-7150MJ <$35 iLCD from $151 TR-72W $527 PP298 $1269.95 DLP-D only $12.99 only $30 (1) or $25 (100) Easy USB GPS Logger USB Logic Analyzer EMI Tents USB Bus Analyzers LCD Scope NEW

Low-Cost!

microUSB - Tiny USB ready- TrackStick™ - gumpack-sized ANT16 Matchbox-sized USB- EMI shielding tents made from Ni/Ag Tracker 110/Explorer 200 high- PDS5022 - 25MHz 2-ch + made USB Interface to 1 Mbps 0.7” logger tracks position data for powered logic analyzer. Sample fabric. -86dB 20MHz to 18GHz. perf. economical USB 1.1/2.0 trig. Standalone bench scope shipments, vehicles, personnel, x 0.5” based on SiLabs CP2101. 16 channels at up to 500 million Portable - tabletop to room/lab size for protocol analyzers. $999/$2999 with USB connection and etc. Records date, time, location, Gnd/RX/TX Suspend, Reset, & on-site, on-demand pre-compliance speed, heading and altitude at samples-per-sec. View traces USBEX300 for debugging USB 7.8” color LCD. Built-in meter 3.3V 100mA source –40°C +85°C. pre-set intervals - shows on PC. Print or save for later testing. External PVC or aluminum wireless Wimedia <$29,500 - great for your service kit. microUSB only $25 route/speed on PC! $249 review! (8-ch. ver. too!) $299 frame. from $3500 New - Bluetooth Sniffer <$10K PDS5022 $399 I2C for PCs WWW.GiURUMELE.Hi2.ROFrontDesign Ether-IO Signal Wizard USB to I2C FREE COFFEE

Call 1-888-7SAELIG

PCI93LV: industry-standard I2C FrontDesign - software for designing Ether-IO - UDP/IP-controlled 24 Signal Wizard - easy-use real- USB I2C/IO - provides a simple Mention Offer# SBW card for PCs. WINI2C/PCI software professional-looking front panels - X digital I/O board. 3 x 8-bit TTL time DSP-based filter board for "drop-in" solution for connecting gives windows-interface to develop to get a free with a host of drawing functions. ports each independently pro- audio bandwidth signals. Design your PC to 90kHz I2C + 20 I/O and debug I2C bus systems. STARBUCKS Card UCA93LV is new USB version. Print, mill or engrave, or export grammable. Connects to any filters in seconds without any DSP lines. Free software. Use multiple with your order! final at 600 dpi. TCP/IP Ethernet network. knowledge! NOW! - transparently monitor at boards for more I2C/IO. While supplies last - 400kHz! only $499 FrontDesign only $79.95 Ether-IO 24 from $99 Signal Wizard II only $399 USB I2C/IO only $79 not available with any other offers

Saelig Co. searches the world to bring you unique, easy-to-use Also: Wireless Temp Loggers, Stepper Motor Controller, PC for harsh environments, control and instrumentation products from overseas. Customers Automotive Diagnostic Kit, PC for Healthcare, Wireless controller, Oscilloscope, JTAG include: Intel, Philips, NEC, Kodak, Nokia, US Military, testing, Indicator modules, Video Motion Detectors, Industrial IO modules, Software Microsoft, Dell, Xerox, Universities, T.I., Harris, Sony, J&J, for soundcard - front panels - logic simulation and hardware control - CAD Thomson, Sandisk, General Dynamics, H-P/Compaq, etc. If you don’t see what you need maybe we can find it for you? - Ask for sales! 72.qxp 10/26/2006 11:13 AM Page 1

PC/104 Single Board Computers

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

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

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

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

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

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

Ethernet Ports

DIO Channels - up to 40

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

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

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

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

New Products and PC/104 Peripherals

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

Up to 128M SDRAM

802.11g WiFi

SD Flash Card socket

1 external USB port

1 10/100 Ethernet

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

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

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

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

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

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

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

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

see our website for more boards and option details WWW.GiURUMELE.Hi2.RO Technologic SYSTEMS We use our stuff. Visit our TS-7200 powered website at www.embeddedARM.com 2612002-Bachiochi.qxp 11/2/2006 11:29 AM Page 74

FROM THE BENCH by Jeff Bachiochi

Portable Lightning Detector Looking to protect your home and electrical systems from lightning? Jeff describes lightning protection technology and explains how to build a PIC16F687 microcontroller-based portable lightning detector.

Our local Boy Scout troop has So, the light sprinkling of rain on weekly meetings that rarely deviate that particular evening didn’t faze from a standard 7:00 to 8:30 P.M. anyone. The game’s intensity schedule of indoor activities. During increased as the score bounced back the last meeting in June (just before and forth and continuously shifted taking a break for the summer), we each team’s destiny. It was like a held an outdoor track meet at one of World Cup playoff. No one gave the the local high schools. It gave the boys weather a second thought. We saw a physical outlet that up to that point nothing. We heard nothing. But it had been restricted to monthly camp- seems pretty clear now that a light- ing trips. Spring in the Northeast is ning strike must have hit the prime thunderstorm season, but we ground somewhere close by. How had never run into any foul weather close is unknown. Those clad in during our “Track Nights.” This year, bare feet were instantly hit with a however, the skies were darkened by burning sensation in their toes. We scattered cloud cover, which moved at were experiencing surface current a brisk pace. We could see for quite a that was traveling along the ground distance thanks to the surrounding like spokes extending from a wagon cornfields. The high heat and cool wheel’s hub (the point of impact). grass invited a shoeless game of Fris- Half of the field emptied in panic as bee soccer. those affected began running in Photo 1—Staying in touch with nature enhances outdoor We camp rain or shine every month every direction, mostly toward the safety. My portable lightning detector offers its take on storm activity in the area. The LED’s relative intensity indi- in whatever weather nature provides. shelter of vehicles in the nearby cates when a storm is approaching or going away. parking lot. Mean- while, the sneakered players were dumbstruck rod.” Trying to direct a lightning at the sight of so many strike is like playing with fire. One instantly possessed by an weak link and a hit will light your unseen force. fire. In “Ground Zero: A For those times when you may find WWW.GiURUMELE.Hi2.ROReal World Look at yourself exposed to hazardous light- Lightning,” Steve Ciarcia ning strikes, being aware of storm and I presented you with tracks makes healthy sense. After some basic information all, the best way to survive lightning about lightning (Circuit is to avoid it. With this month’s proj- Cellar 90, 1998). We also ect, you can take charge of lightning included the steps need- strikes with your own portable light- ed to change the status ning detector (see Photo 1). This Photo 2—Check out this photo of lightning taken from space in 2003. Here of Steve’s house from combines an RF analog front-end you can see the thin veil of Earth’s atmosphere running vertically. Stars are evident on the right side against the darkness of space, and an electrical “lightning rod” to “pro- detector with a microcontroller. storm rages over a landmass on the left. tected by the lightning LEDs indicate the status of a storm’s

CIRCUIT CELLAR® 74 Issue 197 December 2006 www.circuitcellar.com 2612002-Bachiochi.qxp 11/2/2006 11:29 AM Page 75

activity. three varieties. The first is via optical was a step in the right direction. Charles monitoring. Photographers often use Wenzel has some great circuits on his BREAKING THE SOUND BARRIER slave flashes to augment their camera web site (http://www.techlib.com/ The potential buildup of unlike mounted flash. These devices monitor electronics/lightning.html). His analog charges in thunderclouds seems to illumination levels and can trigger circuit is a perfect match for this proj- occur from the rising and falling of ice their secondary flash based on “see- ect. As you can see in Figure 1, the particles. This was evident a few ing” the camera’s flash. The optical front-end antenna/tank circuit gathers weeks ago as a thunderstorm passed monitoring of lightning is similar, any activity in the 300 kHz range. over Crystal Lake here in Connecti- although this type of detection is Oscillations are amplified through T1 cut. The soft splashes of rain falling most difficult on sunny days. A and applied to the base of a flip-flop amid the cracking of thunder gave way stormy sky offers enough contrast for (T2/T3). Sufficient signal will turn on to a couple of minutes of clinking. a strike to be sensed easily. When T2 (and T3) and discharge timing This rapid change in timbre on my used in conjunction with LF (audible) capacitor C11. Because C11 provides office window led me to the porch waves, the optical sensor can be used the biasing for T2/T3, these transis- where I watched 0.5″ hailstones fall to initiate a simple count between tors are turned off as the capacitor is from the sky while the thermometer flash and crash to produce a distance- discharged. A diode between C11 and was approaching 90°! to-strike value. the pull-up resistor (R7) allows C11 to Cloud-to-cloud lightning is far more A second type uses RF detection. If discharge quickly but through R7 prevalent than the cloud-to-ground you’ve listened to AM radio, you more slowly. The minimum low time events caught by many photographers. know that lightning’s discharge pro- of the output pulse is approximately Theories abound on just how a dis- duces static noise across the frequen- 20 ms. charge path between a cloud and Earth cy spectrum. Mother Nature would Each strike produces an output is determined. A strike takes about certainly fail the FCC’s allowed emis- pulse from the analog front end. By the same amount of time as a single sion testing. Luckily, she is covered monitoring these pulses, you can execution cycle in many microcon- by the grandfather exemption. determine a few things about the trollers! Because of the intense energy Although this spectrum noise is easily storm’s movement. From a fixed posi- (millions of volts and thousands of detectable, other noise sources can tion (wherever you are), every storm amps) of a discharge, the surrounding produce false triggers. Monitoring for will pass you by. Assuming that a air is superheated. The expanding coinciding triggers at multiple fre- storm moves in a straight path, it can heated air causes a shockwave along quencies can reduce false triggering. be moving either toward or away from the entire discharge path. The shock The last method measures electric you. Whether or not you can actually wave propagates as a thunderclap with fields. A cloud and the Earth act as detect it depends on how close you are varying duration, depending on your plates in a capacitor. As the potential to its path and the size of its umbrella. I orientation to the discharge. Count the increases between the plates, this can use the word umbrella to help visualize seconds between seeing the flash (the be measured as a change in the Earth’s that a storm has dimension to it. A speed of light) and hearing the sound of electric field. Under sunny skies, the lightning strike may originate anywhere thunder (the speed of sound) to deter- ionosphere is responsible for produc- beneath this umbrella and not just at the mine the strike’s distance. The dis- ing less than 100 V/m. During storm storm’s centroid moving along its path. tance to the strike is about one mile for activity, this each 5 s of time delay. value can rise to If you follow NASA Select by satel- thousands of volts lite, cable, or via the Internet, you’re per meter. These familiar with the nighttime views of values rise with the Earth from 200 miles up (from the approach of either the Shuttle or the ISS). The potential strike, most prominent feature from above is so the electric the clouded sky featuring spectacular field can be used lightning at a rateWWW.GiURUMELE.Hi2.RO that can exceed one to warn of an strike per second (see Photo 2). Imag- impending strike. ine the quantity of available energy. Harnessing this energy has the poten- SEARCH FIRST tial of eliminating oil as the world’s In searching the most important resource and changing Internet for avail- forever the face of world politics. able information about lightning DETECTION TECHNOLOGY detection, I ran Figure 1—A lightning strike produces EMI across the frequency spectrum. The ana- Today’s technology for detecting across an interest- log front end of this project picks up activity in the 300-kHz region and produces a lightning activity can be divided into ing project that 20-ms pulse indicating its presence.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 75 2612002-Bachiochi.qxp 11/2/2006 11:29 AM Page 76

LEDs. Figure 3 shows interstrike time in seconds) is initial- the digital portion of ized to maximum. The FIRST flag is the device. The first also set to indicate when you haven’t LED is used to indi- received any strikes yet. cate that the system is operating. LEDs 2 HIT ME, BABY through 8 show The program written for this project storm activity. An is interrupt based. Although most of Storm movement approaching storm the time is spent idle in the main exe- activates LED 2 cution loop, all of the action takes (green). As the activi- place within interrupt routines. Each ty intensifies, LED 3 action has its own routine. A change- (yellow) is triggered. of-state (COS) interrupt handles push Red LEDs 4 through button presses. The strike pulse pro- 6 indicate maximum duced by the analog front-end edge- Sensor activity. LED 6 signi- triggers an external interrupt. Seconds position fies that the storm is are accumulated by overflow inter- beginning to leave rupts of Timer1. The piezo element the area. LED 7 (yel- receives a 4-kHz tone burst via the low) confirms that Timer0 interrupt routine. the worst is over, The falling edge-triggered external while LED 8 (green) interrupt monitors pulses from the indicates the final analog circuitry. When triggered, the fringe activity. external interrupt routine sets the Figure 2—A storm’s umbrella coinciding with the sensing umbrella of the PLD As I stated earlier, BEEP flag so that a short 4-kHz burst makes the sensing of a lightning strike possible. The more overlap (closer the the storm status is will allow the piezo device to audibly storm), the higher the potential strike rate. PLD activity is a function of both storm speed and proximity. based on the time signal each strike. If the FIRST flag is between lightning set, this indicates that no strikes have strikes. Determining been detected up to this point. So, the An approaching or receding storm a storm’s status begins with a clean external interrupt routine needs to can be beyond the detection distance. slate. The slate is cleaned (variables clear only the FIRST flag and the The detection distance can also be initialized) whenever the circuit is count in Tic, which is the variable thought of in terms of an umbrella. As powered on or a time of 256 s has holding the count in seconds since the a storm umbrella overlaps the detec- passed without a strike producing last strike. (Tic continuously incre- tion umbrella, it becomes possible for pulse from the analog input. Peak- ments based on the Timer1 overflows a strike to be detected. However, if Time (a variable holding the shortest at a 1-s rate.) With the FIRST flag any strike activity were to take place on the far side of the storm’s umbrel- la, these strikes may be outside the detection range (see Figure 2). While a storm’s activity may remain constant, its strike rate from our vantage point changes.

DIGITAL PORTION The detection method used here does not measure energy levels. The status warningWWW.GiURUMELE.Hi2.RO level is based on the hit rate of a storm, which should increase as the storm’s umbrella over- laps more of the detection umbrella. As the storm’s centroid passes its clos- est point to the detector, the hit rate should begin to decrease as the over- lapping areas decrease. The status warning level of a storm is displayed in a bar graph. One of the Figure 3—The digital portion of this project monitors the time between pulses (strike rate) and produces an LED microcontroller’s ports drives eight status display based on preconfigured constants.

76 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612002-Bachiochi.qxp 11/2/2006 11:29 AM Page 77

Present time Warning level Present level DIR Flag (0 = Approaching, 1 LED 2–8 constants = receding) > 128 s — 0 — none 127–64 s 128 (level 1) 1 0 2 (green) 63–32 s 64 (level 2) 2 0 3 (yellow) 31–8 s 32 (level 3) 3 0 4 (red) < 8 s 8 (level 4) 4 0 5 (red) 31–8 s 32 (level 3) 3 1 6 (red) 63–32 s 64 (level 2) 2 1 7 (yellow) 127–64 s 128 (level 1) 1 1 8 (green) > 128 s — 0 — none

Table 1—The PresentTime is compared to each of the four level constants to determine the appropriate warning level (PresentLevel). The DIR flag is based on the PresentTime and the PeakTime. The four constants (Level 1:4) make it easy to experiment with the warning level parameters.

cleared, any subsequent strike trigger- may be cleared. The TOG flag is alter- ing the external interrupt saves the nately set and cleared by this interrupt Tic count into the PresentTime vari- routine at the routine’s 1-s rate. When able. Tic is then cleared again, begin- TOG is set, the power LED 1 is turned ning the count to the next strike. on. When TOG is cleared the LEDs 2 Based on PresentTime, a level of through 8 are turned on. Only one warning is determined. LED draws current at a time. There are four (warning) levels set Additionally, this routine monitors by constants. These predefined times the BEEP flag. If a beep has been are compared to PresentTime to deter- requested, the Timer 0 interrupt is mine PresentLevel and PeakLevel (see enabled and the BEEP flag is cleared Table 1). PeakLevel is a peak detector, by setting the BEEP flag elsewhere. and it increases as PresentLevel Otherwise, the Timer0 interrupt is increases. However, if PresentLevel disabled. This action allows the should fall below PeakLevel, PeakLevel Timer0 overflow interrupt routine to won’t decrease and the DIR flag is set toggle the output bit (tied to the piezo to indicate that the storm is moving device) at each Timer0 interrupt. away. Finally, based on PresentLevel Because the Timer0 interrupt will be and DIR, the proper LED is enabled by disabled the next time through the clearing the appropriate bit in LED- Timer1 interrupt routine, the 4-kHz Flags prior to leaving the external tone will last for just 1 s. interrupt routine. ZZZZZZ ONCE UPON A SECOND By allowing no more than one LED Besides having the responsibility of to be on at any time, you keep the oper- incrementing Tic, the Timer1 over- ating current to approximately 10 mA flow interrupt routine has other func- (depending on the LED’s series resis- tions. If a storm abruptly ends or the tors). The analog section requires very PLD is not triggered by radiated noise little current. I used an I/O bit on a from some other source, the rollover Microchip Technology PIC16F687 of Tic is monitored. After 256 s with- microcontroller to power this portion out a strike, theWWW.GiURUMELE.Hi2.RO system reverts back of the circuit. This allows the analog to the initialized state. This takes care section to be powered down before of those situations in which activity entering Sleep mode. When the circuit has ceased, and it requires more than has battery power applied, it will 4 min. without any detection. begin initializing and executing code. Before leaving the Timer1 interrupt Push button switch SW1 toggles the routine, the LEDs are updated. Under power LED on and off. The main rou- normal operation (no storms), only the tine’s only function is to monitor the power LED 1 would be cleared in LED- status of this bit and go to sleep if SW1 Flags. In stormy conditions, an addi- turns off the lower LED 1 (power). The tional LED (2 through 8) warning level PIC16F687 microcontroller can exit

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 77 2612002-Bachiochi.qxp 11/2/2006 11:29 AM Page 78

Sleep mode on MCLR reset or any that suggests this (sort of). You see an bolt avoid all of the taller targets and enabled interrupt source. Individual AM radio on a table playing tropical hit a chimney that didn’t have any peripherals can be disabled prior to tunes as waves roll in on the deserted antennas or lightning rods? going to sleep to prevent a wake-up beach in the background. A bottle of We certainly have a lot to learn from an unwanted source. I’m allow- Corona next to the radio leaves the about lightning and our world in gen- ing only the COS interrupt from SW1 field of view (refreshing its owner off eral. Who knows what insight further to wakeup the processor. camera). When it’s placed back on the investigation will bring? Nature is In Sleep mode, the current in the table the radio reception is rather both helfpul and dangerous. It might microcontroller is down in the awful. Adjustments to the bottle’s be obvious that swinging a golf club microamp range. However, the battery position relative to the radio clear up on hilly terrain that’s devoid of struc- current in Sleep mode was approxi- the reception. Well, because I couldn’t tures is potentially dangerous. And, mately 4 mA. After much head fit multiple loopsticks with the right after seeing or hearing a storm, any scratching, I realized the culprit. The orientations into the Serpac’s enclo- sane person would seek shelter. But if 78L05 voltage regulator has a 4 mA sure, I buckled under the pressure and you’ve ever been anywhere near an idle current specification. This 4 mA made provisions for an extendable actual lightning strike, you know that looks like a 2.2-kΩ load to my 9-V whip antenna. this is something you do not wish to battery. That’s about 50 h (or two Let me tell you one last story on the mess with. Any additional warning days) independent of whether or not subject of lightning. One of the Boy can mean the difference between life the circuit is sleeping! By switching to Scout troop leaders was working and death. I a Zetex Semiconductors ZMX500C around his house when he heard a voltage regulator (still in a TO-92 mighty crash. The volume was suffi- Jeff Bachiochi (pronounced BAH-key- package), the quiescent current is cient to pique his curiosity, so he AH-key) has been writing for Circuit reduced to less than 50 µA. At 50 µA, went outside to see if the local inter- Cellar since 1988. His background that same 9-V battery would last section was featuring a confrontation includes product design and manu- about a year. That seems sufficient between metal beasts. With no traffic facturing. He may be reached at without having to worry about using in sight, he scanned the horizon to see [email protected]. either a lever switch to cut power if he could find any abnormalities. completely or design in a regulator Everything seemed normal, apart from PROJECT FILES with an on/off input like the Toko the missing chimney. Ah, that’s why TK11150CS voltage regulator (with an there were bits of brickwork strewn To download the code, go to ftp://ftp. off current of less than 1 uA). around the yard! The chimney had circuitcellar.com/pub/Circuit_Cellar/ been blasted apart by lightning. This 2006/197. PACKAGING made no sense. The yard was littered Serpac’s H series enclosures have with huge trees towering over the roof RESOURCES either a twin AA or 9-V battery com- of the house. You’d think, “A strike The National Severe Storms Labora- partment option. The enclosure looks must have been attracted to one of tory, “Questions and Answers About like a TV remote (see Photo 1). I also those giants.” Lightning,” 2004, www.nssl.noaa.gov/ got the enclosure with a belt clip, After inspecting the remains of the edu/ltg. which is really handy for sticking the chimney in the attic and determining system on my belt, in my pack, or in that the roof was intact, there didn’t C. Wenzel, “Lightning Detectors,” any other handy location. seem to be any interior damage to the Wenzel Associates, Inc., www.techlib. I used a 9-V battery with this cir- structure. So, he shrugged it off and com/electronics/lightning.html. cuit. However, using two AA batteries began searching for masons in the would probably work well because the phonebook. About 30 min later, he SOURCES microcontroller will operate down to smelled a hint of smoke. Recognizing PIC16F687 Microcontroller 2 V at 4 MHz. (I’m running at 2 MHz.) the importance of swift action, he Microchip Technology, Inc. Of course, there are other parts of the called 911. Members of the town’s vol- www.microchip.com circuit that mayWWW.GiURUMELE.Hi2.RO run out of steam (i.e., unteer fire department began arriving piezo volume and LEDs). within minutes. Because of his quick H-65, 9-V Enclosure call, firefighters were able to assess Serpac Electronic Enclosures HINDSIGHT the situation before flames could take www.serpac.com I despised trying to use a whip hold. From the attic, they zeroed in on TK11150CS Voltage regulator antenna, so I attempted a few versions the top of a wall that had smoldering Toko America, Inc. of the RF front end using a loopstick insulation. Downstairs, they opened www.toko.com antenna. I had a serious episode of up the wall and removed the offending brain fade. I forgot about the direc- insulation with little interior damage. ZMX500C Voltage regulator tional characteristics of this antenna. No one could make any sense of the Zetex Semiconductors There is a cute commercial by Corona strike’s selection process. Why did the www.zetex.com

78 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 63.qxp 5/4/2006 1:10 PM Page 1

WWW.GiURUMELE.Hi2.RO 2612003-Cantrell.qxp 11/2/2006 11:32 AM Page 80

SILICON UPDATE by Tom Cantrell

Ferro-51 Twenty-five years after the debut of the original, a new ’51 MCU is making headlines. Tom describes Ramtron’s VRS51L3074 FRAM-enhanced ’51 MCU and prepares you for what’s to come.

By the time you read this, I’ll have replacing stand-alone DRAM and flash ed multimemory setups. Faster, lower given my “Is ARM the ’51 of memory. Thus, it’s no surprise that power, nonvolatile, cheaper, and more Tomorrow?” presentation at the ARM “Ramtron Introduces the First FRAM- flexible: that’s what I’m talking about! Developers’ Conference in Santa Clara, Enhanced 8051 MCU” was right up my Sounds good, but that’s not what the California. Can ARM match the popu- alley and definitely got my attention. new Ramtron VRS51L3074 microcon- larity and longevity of the venerable Ramtron’s been in business selling troller is. The press release is careful to ’51? Is it MCU déjà vu all over again? FRAM memory chips for a long time, say that the ’3074 is just the first step Leaving those questions for another but I didn’t know they made ’51s. Ah along the way. Witness the fact it still day, this month’s topic draws from ha, it turns out they’re new to the has flash memory (64 KB) and SRAM one of the punch lines in my presenta- MCU game, buying into the market (4 KB + 256 bytes) along with the 8 KB tion. In one sense, ARM can’t be the with their recent (August 2005) acqui- of FRAM (see Figure 1). Indeed, under ’51 of tomorrow because, ta-da, the sition of Goal Semiconductor, a niche the hood, I’m pretty sure you’re look- ’51 is the ’51 of tomorrow. supplier of mixed-signal ’51s. ing at separate MCU and FRAM chips That’s right. While there’s no doubt Imagine an MCU that gets by with rather than true unification of FRAM that low-cost flash memory 32-bit just FRAM instead of the motley collec- and CMOS processing on a single die. MCUs are taking off, the idea that tion of flash memory, RAM, EEPROM, Based on the specs of Ramtron’s very they will replace 8-bit MCUs ROM, etc. that clutters today’s chips. SRAM-like 1-Mb chip that I covered last overnight is ludicrous. Rather, my take Better yet, FRAM would eliminate all the month, I expected to find a similar is that while the 8-bit MCU growth granularity issues (e.g., code versus data FRAM on the ’3074. Thus, I was a bit rate may be topping out, the 8-bit story storage) associated with today’s fragment- surprised to find that the integrated is far from over. FRAM on the ’3074 isn’t nearly as One thing both ARM and the ’51 capable as the stand-alone part. VRS51L3074 do uniquely share is a multisourced Mult/Accu/Div 8051 Core JTAG First the good news. Once all is architectural bandwagon. That’s with 32-bit barrel Single cycle with on-chip said and done, access to the on-chip shifter (40 MHz) emulation important because it increases the FRAM is via the ’51’s MOVX instruc- Ports (7) Flash memory SPI variety of specialized parts designers I/Os (56) (64 KB) tion (i.e., the same instruction used to have to choose from. Case in point External data RAM access the on-chip SRAM as well as I2C is this month’s topic, yet another bus controller (4,352 bytes) external memory and I/O devices). UARTs, On-board FRAM “new” ’51 making its debut fully a data rate There’s no need for the multi-instruc- oscillator (8,192 bytes) quarter century after the original. generators (2) tion software bit-banging or program- Crystal Interrupt ming routines typically required by oscillator controller MEMORY MAPPINGWWW.GiURUMELE.Hi2.ROinputs flash memory or EEPROM. A bit of Dynamic As I was researching last month’s PWMs/timers (8) software is required to set up and article on alternative memory tech- clock control enable the FRAM; but after that, a Watchdog Pulse-width nologies, I came across an interest- timer counters (2) MOVX is all it takes. ing press release on Ramtron Last month’s 1-Mb FRAM chip Power-on/ Timer capture International’s web site. As I men- reset inputs (3) did a decent job of delivering on the tioned in that column, when it promise of next-generation memo- comes to MRAM, FRAM, and the Figure 1—Ramtron makes their move into the MCU business ries by offering the speed and like, I think embedded applications with an assist from Goal Semiconductor, which they acquired read/write symmetry near that of an last year. The headline feature that sets their VRS51L3074 are a real market, one that’s over- apart from the crowd is 8 KB of FRAM, but this ’51 is also SRAM. However, the FRAM on the looked in all the Holy Grail hype of notable for its performance features. ’3074 isn’t especially fast or sym-

80 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 66.qxp 4/4/2006 3:34 PM Page 1

WWW.GiURUMELE.Hi2.RO 82.qxp 11/1/2006 10:37 AM Page 1

mikroElektronika DEVELOPMENT TOOLS | COMPILERS | BOOKS EasyPIC4 Development Board mikroBasic, mikroPascal and mikroC compilers with on-board USB 2.0 programmer and mikroICD Supporting an impressive quantity of microcontrollers, easy to use IDE, hun- dreds of ‘ready to use’ functions and many integrated tools makes MikroElektronika compilers one of the best choices on market today. Beside mikroICD mikroElektronika compilers offer statistical module, simulator, generat- ing Bitmap for graphic screens, 7 segments converter tool, ASCII, Export Code to HTML, communication tool for SD/MMC , UDP (Ethernet), USB , EEPROM editor, management of the programming modes etc.. CAN-1 Board - Interface Each compiler has many routines and examples like reading/writing on MMC, CAN via MCP2551 SD, CF cards, EEPROM, FLASH, writing to alphanumeric and graphic LCD, $18.00 USD manipulation of push-buttons, 4x4 keyboards, PS/2 keyboards, generation of signals and sounds, character string manipulation, mathematical calculations , manipulation of communications I2C / SPI / RS232 / CAN / USB / RS485 / OneWire, Manchester cod- CAN-2 Board - Make CAN ing management, logical/numerical conversion, PWM signals, interrupts, etc… The CD-ROM contains many ready-written and network with SPI interface tested programs for use with our development boards. $21.00 USD Regular price: Price with discount: RS485 Board - Connect mikroBasic(PIC) $149.00 USD Buy one of our compilers with one of mikroBasic(PIC) (-30%) $99.00 USD devices into RS-485 network mikroPascal(PIC) $149.00 USD our PIC development boards at up to mikroPascal(PIC) (-30%) $99.00 USD $17.00 USD mikroC(PIC) $249.00 USD 30% discount. mikroC(PIC) (-30%) $175.00 USD

Serial Ethernet - Make mikroBasic(AVR) $149.00 USD Buy one of our compilers with one of mikroBasic(AVR) (-30%) $99.00 USD ethernet network with SPI mikroPascal(AVR) $149.00 USD our AVR development boards at up to mikroPascal(AVR) (-30%) $99.00 USD Interface (ENC28J60) 30% discount $28.00 USD mikroBasic(dsPIC) $149.00 USD Buy one of our compilers with one of mikroBasic(dsPIC) (-30%) $99.00 USD mikroPascal(dsPIC) $249.00 USD our dsPIC development boards at up to mikroPascal(dsPIC) (-20%) $199.00 USD HARDWARE EasyPIC4 development board: mikroC(dsPIC) $249.00 USD 30% discount. mikroC(dsPIC) (-30%) $175.00 USD ICD ON-BOARD Following in the tradition of the USB 2.0 ON-BOARD EasyPIC3 as one of the best PIC 31in PROGRAMMER development systems on the HIGH market, the EasyPIC4 has more DEVELOPMENT PERFORMANCE BIGPIC4 Development Board new features for the same price. with on-board USB 2.0 programmer and mikroICD SYSTEM DEVELOPMENT The system supports 8, 14, 18, BOARD 20, 28 and 40 pin PIC microcon- Following in the tradition of its predecessor, the BIGPIC3 as one of the best best trollers (it comes with a PIC16F877A). The ultra fast mikroICD (In-cir- 80-pin PIC development systems on the market, BIGPIC4 continues tradition with more new features for same price. System supports the latest 64 and 80- CF Board - Easy way to cuit Debugger) enables very efficient debugging and faster prototype development. Many ready made examples guarantee successful use pin PIC microcontrollers (it is delivered with PIC18F8520 working at 40MHz). use Compact flash in your Many ready made examples guarantee successful use of the system. BIGPIC4 design $18.00 USD of the system. EasyPIC4 is fully optimized for fast prototype develop- ment. It allows the PIC microcontroller to be interfaced with external has many features that makes your development easy. Ultra fast on-board pro- grammer and mikroICD (In-circuit Debugger) enables very efficient debugging MMC/SD Board - Easy way circuits to a broad range of peripheral devices, allowing the user to concentrate on just the software. On a silkscreen there are labels and faster prototype developing. Examples in C, BASIC and Pascal language to use MMC and SD cards in are provided with the board. your design $18.00 USD beside every component. These marks describe connections to the microcontroller, operation modes, and some other useful notes. As a BIGPIC4 Development System ...... $132.00 USD EEPROM Board - Serial result, the need for additional schematics is minimized, because all EEPROM board via I2C the information required is already on the board. interface $9.00 USD 3 in 1 Development System : Development Board + USB 2.0 on- EasydsPIC3 Development Board with on-board USB 2.0 programmer RTC Board - PCF8583 RTC board programmer + In Circuit Debugger with battery backup System supports 18, 28 and 40 pin microcontrollers (it comes with $16.00 USD dsPIC30F4013 general purpose microcontroller with internal 12 bit ADC). EasydsPIC3 has many features that make your development easy. Many ready made examples in C, BASIC and PASCAL language guarantee successful use of the system. On-board USB 2.0 programmer allow you faster prototype devel- mikroICD is a highly effective tool for Real-Time debugging on a oping. hardware level. The ICD debugger enables you to execute a mikroC/mikroPascal/mikroBasic program on a host PIC microcon- EasydsPIC3 Development System ...... $119.00 USD troller and view variable values, Special Function Registers (SFR), memory and EEPROM as the program is running. On-board USB 2.0 PICFlash programmer – an ultra fast USB 2.0 programmer for fast MCU programming. Continuing its tradition as the fastest PIC programmer on the market, the new PICFlash with dsPICPRO2 Development Board with on-board USB 2.0 programmer ADC Board - 12-bit analog- mikroICD now supports more PIC MCUs giving the developer a wider to-digital converter(ADC) choice of PIC MCU for further prototype development. System supports dsPIC microcontrollers in 64 and 80 pin packages. It is deliv- with 4 inputs $22.00 USD ered with dsPIC30F6014A microcontroller. The dsPICPRO2 development sys- tem is a full-featured development board for Microchip dsPIC MCU. DAC Board - 12-bit digital- dsPICPRO2 board allows microcontroller to be interfaced with external circuits to-analog converter(DAC) and a broad range of peripheral devices. This development board has an on- with SPI $18.00 USD board USB 2.0 programmer and integrated connectors for SD/CF memory cards, 2 x RS232 port, RS485, CAN board, DAC etc.. Keypad 4x4 Board - Add keypad to your application dsPICPRO2 Development System ...... $239.00 USD $9.00 USD Accel. Board - Accel. is an electronic device that will measure acceleration forces EasyAVR4 Development Board $16.00 USD with on-board USB 2.0 programmer System supports 8, 20, 28 and 40 pin microcontrollers (it comes with ATMEGA16). Each jumper, element and pin is clearly marked on the board. It is possible to test most of the industrial needs on the system: temperature con- trollers, counters, timers etc. EasyAVR4 is easy to use Atmel AVR development Examples in C, BASIC and Pascal language: Printing text on LCD, system. On-board USB 2.0 programmer makes your development easy. LED blinking on PORTB, MMC/SD/CF card read and write example, Examples in BASIC and Pascal language are provided with the board. USB communication, 4x4 Keypad example, PS2 keyboard example, software SPI/I2C/RS232 communications, AD conversion example EasyAVR4 Development System ...... $114.00 USD Seven segment digit example, Timer 0 and Timer 1 time measuring, Measuring temperature with DS1820 and displaying on LCD, Graphic LCD example, examples for SPI communication, examples for CAN communication, examples for Sound generation, sending and receiv- EasyARM Development Board ing data over Ethernet, Interrupt upon PORTB state change, with on-board USB 2.0 programmer Detection of button pressed on port and many more... EasyARM board comes with Philips LPC2214 microcontroller. Each jumper, ele- ment and pin is clearly marked on the board. It is possible to test most of the industrial needs on the system: temperature controllers, counters, timers etc. EasyARM has many features that make your development easy. One of them PICFlash programmer – an is on-board USB 2.0 programmer with automatic switch between ‘run’ and ‘pro- ultra fast USB 2.0 programmer gramming’ mode. Examples in C language are provided with the board. for PIC microcontrollers. Continuing its tradition as one EasyARM Development System ...... $149.00 USD of the fastest PIC programmer on the market, the new PICFlash with mikroICD now supports more PIC MCUs giv- ing the developer a wider choice of PIC MCU for further WWW.GiURUMELE.Hi2.ROEasy8051A Development Board prototype development with on-board USB 2.0 programmer mikroICD debugger enables you to execute mikroC / System is compatible with 14, 16, 20 and 40 pin microcontrollers (it comes with mikroPascal / mikroBasic pro- AT89S8252). USB 2.0 Programmer is supplied from the system and the pro- gram on a host PIC microcon- gramming can be done without taking the microcontroller out. Many industrial troller and view variable val- applications can be tested on the system : temperature controllers, counters.. ues, Special Function Regi- Easy8051A development system is a full-featured development board for 8051 sters (SFR), memory and Package contains: EasyPIC4 development system, USB cable, microcontrollers. It was designed to allow students or engineers to easily exer- EEPROM as the program is Serial cable, User’s manual, MikroICD manual, CD with software, cise and explore the capabilities of the 8051 microcontrollers. running...... $89.00 USD drivers and examples in C, BASIC and Pascal language. Note: LCD, DS1820 temp sensor and GLCD are optional. Easy8051A Development System ...... $114.00 USD - All of our products are shipped in special EasyPIC4 Development System ...... $119.00 USD protective boxes. Optional: EasyPSoC3 Development Board - On-line secure ordering 2x16 LCD and DS1820 temperature sensor ...... $15.00 USD with on-board USB 2.0 programmer provides a fast and safe Graphic LCD 128x64 dots ...... $17.00 USD way to buy our products. System supports 8, 20, 28 and 48 pin microcontrollers (it comes with CY8C27843). Each jumper, element and pin is clearly marked on the board. EasyPSoC3 is an easy to use PSoC development system. On-board USB 2.0 Please visit our web page for more info programmer provides fast and easy in system programming. http://www.mikroe.com EasyPSoC3 Development System ...... $169.00 USD Find your distributor: http://www.mikroe.com/en/distributors/

S O F T W A R E AND H A R D W A R E S O L U T I O N S FOR E M B E D D E D WORLD 2612003-Cantrell.qxp 11/2/2006 11:32 AM Page 83

metric, with minimum access times of wind. By contrast, like FRAMCLK[1:0] = 00 FRAMCLK[1:0] = 01 1.9 and 2.6 µs for reads and writes, practically all ’51s these (Sysclk/2) (Sysclk/4) respectively. Note that the MOVX is days, the ’3074 offers good Mode Read Write Read Write interlocked so that the processor stalls performance by a combi- Normal 1.9 µs 2.6 µs 3.6 µs 4.9 µs until the FRAM read or write completes. nation of architectural Burst* 1.1 µs 0.4 µs 2.3 µs 0.7µs Like their stand-alone memory chip, turbocharging (fewer Read burst* 0.7 µs 0.4 µs 1.6 µs 0.7 µs the ’3074 FRAM does support Burst clocks per instruction) *Based on 100 consecutive read and write operations in Burst mode. modes that can increase throughput and more revs (i.e., faster Table 1—FRAM has a lot of potential, but the implementation on the ’3074 somewhat (see Table 1). But Burst clock up to 40 MHz). I fig- could be better (i.e., faster with symmetric read/write times). Burst modes mode has some gotchas that can trip ure a typical application help, but impose system timing constraints that may trip up the unwary. up unwary designers. Once you put program mix would aver- the FRAM in Burst mode, you must age three to four clocks per instruc- for speed) to drive the coprocessor, but read only consecutive addresses or tion for an honest 10+ MIPS. ultimately, it returns answers as fast as write consecutive addresses. Mixing The ’3074 features a 40-MHz oscil- you can feed it operands. It’s no DSP, reads and writes or skipping addresses lator on-chip that, with 2% precision, but the math coprocessor does deliver isn’t allowed. should be accurate enough to eliminate signal processing capability far beyond Furthermore, there is a timing con- the need for crystal in many applica- that of most 8-bit MCUs. straint limiting the idle time allowed tions. In addition, an external 4- to Another embellishment is a second between each transfer in a burst. If 40-MHz crystal can be connected, and DPTR (data pointer) register to bypass you dally too long, the FRAM auto- you can dynamically switch between the well-known bottleneck imposed by matically exits Burst mode. Although the two. In turn, the chosen oscillator the originals single pointer. For exam- the idle time allowed is somewhat feeds a 16-level power-of-two prescaler ple, block memory operations can use programmable (four choices), it does (i.e., divide ratio = 1, 2, … 32,768), which one of the data pointers for the source require that you guarantee your soft- allows software to control the throttle address and one for the destination ware can meet the required deadline. depending on the task at hand. There’s rather than having to coerce a single For example, this may require dis- even a feature that can automatically hit DPTR into serving double duty. abling interrupts during a burst trans- the gas (i.e., set clock divide ratio to There are also additional instruc- fer or at least extra software to cor- one) when an interrupt occurs. tions that streamline access to the all- rectly restart an interrupted burst. For number crunching, the ’51’s important special function registers The scary part is that if you make built-in MUL and DIV instructions are (SFRs) that control the various I/O any mistakes (e.g., mixing reads and standouts at just two clocks (i.e., 50 ns ports. In the interest of avoiding any writes, nonsequential address, missing at 40 MHz). But the math capability of possible software compatibility issues the burst timeout deadline) the FRAM the ’3074 goes way beyond just speed- that might arise with the new opcode can lose data, and there’s no interrupt ing up those native instructions. As (which is an NOP for regular ‘51s), or error flag to let you know that hap- you can see in Figure 2, the chip inte- this feature can be dynamically pened. If you must use Burst mode, grates a 16/32-bit arithmetic coproces- enabled and disabled by software. it’s there, but be careful. sor and barrel shifter that can signifi- Speaking of I/O, ’3074 upgrades fall If there’s a bright side, the relatively cantly accelerate math-intensive appli- into two categories. First, be reassured slow access time in conjunction with cations (e.g., DSP loops). There is a bit the historic ’51 I/O features are all ever-improving endurance specs virtually of software overhead (preferably ASM there and can work the same as before. eliminates concerns about Indeed, the pinout for the wear out. The ’3074 44-pin version of the FRAM retention time Adder 1 MCU (’3174) is the same MSB LSB Adder spec is a whopping 45 as that of many tradi- AUA1 AUA0 AUB1 AUB0 11 MSB LSB years! Although I couldn’t + = tional ’51s. However, find any retention time or Multiplicand 1 Multiplicand 2 going beyond compatibil- MSB LSB MSB LSB 10 01 endurance specs for the AUA1 AUA0 X 00 ity, there are also options flash memory inWWW.GiURUMELE.Hi2.RO the pre- Barrel shifter that enhance the tradi- ADDSRC {1:0} liminary datasheet, I pre- tional I/O functions AUSHIFTCFG sume they’re similar to AUB (1:0) 00 0 00 with new capabilities. those of other flash mem- AUA (1:0) 01 AUC (3:0) 01 For example, the origi- AURES (3:0) ory MCUs (e.g., ten(s) nal ’51 required using a AUPREV (3:0) 10 AUPREV (3:0) 10 MSB LSB years, thousand(s) cycles). general-purpose timer as AUB (1:0) 11 32-bit Add 11 {AUA, AUB} a bit rate generator for its + AUC MIPS MASTER MULCMD {1:0} built-in UART. By con- The original ’51 was ADDSRC {1:0} trast, not only does the rather pokey, maybe hit- Figure 2—With a combination of 32-bit multiplier, adder, and barrel shifter, the ’3074A built-in ’3074 provide dedicated bit ting 1 MIPS with a tail- math coprocessor turns this ’51 into a mini-me DSP. rate generators, but the

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 83 2612003-Cantrell.qxp 11/2/2006 11:32 AM Page 84

including packages from major suppli- flash memory programming and soft- ers like Keil and American ware debugging in a single program, Raisonance. Better yet, over the years, although each function is relatively a variety of low-cost and even free alter- stand-alone. The programming portion natives have emerged that belie the tra- handles basic flash memory operations ditional truism that you get what you and is really simple. The streamlined pay for. With Ramtron’s $99 ’3074 eval- interface offers one-click programming uation board in hand, let’s see how far (i.e., erase, write, and verify), while the freeware can take you (see Photo 1). ability to flash individual blocks and The board itself is rather minimalist multiple files supports customization and straightforward with little more (e.g., serial number and calibration data). than the ’3074 chip, RS-232 trans- Once you burn a program into flash ceivers for its twin serial ports, some memory, the debugger provides the criti- LEDs, and a connection for a JTAG cal link between your source code and debugger. Somewhat ironic consider- the relatively sophisticated debug hard- Photo 1—The ’3074 evaluation kit is relatively standard ing the ’3074’s built-in FRAM, the ware built into the ’3074 chip. There fare, but with a notable FRAM bias. In addition to the FRAM on the MCU itself, the board includes three stand- only notable add-ons are a trio of the are six hardware breakpoints that work alone serial FRAM chips. company’s stand-alone FRAMs, in the usual fashion (i.e., stopping the including a processor companion chip processor when a particular address is and SPI and I2C variants.[1] It’s a verita- accessed). In addition, there’s a “value” general-purpose timers also feature new ble FRAM traffic jam! That seemingly modes as well. For example, timers that odd situation is explained by the fact ORG 2000h are limited to 8- or 16-bit operation in a the same board is used for evaluating Start: traditional ’51 can be chained together the various FRAM chips and non- MOV A, #10 ; Load ACC with 10 to deliver 24, 32, and even 48 bits of res- FRAM variants of the MCU. Loop: DEC A olution. Another upgrade supplements The JTAG debugger dongle itself gets JNZ Loop the general-purpose (i.e., parallel) I/O marked down by virtue of the fact it LCALL Function ; Call a function lines with a pin monitor function that uses a printer port interface with the PC. JMP Start can detect a change (edge or level That was once a common hack, but it ORG 3000h Function: sense) on any and all pins of interest. has fallen out of favor with the rise of RET ; Dummy function The second class of I/O enhance- USB and the fall of PCs equipped with Branch Loop repeat Loop skip ments includes new features not found parallel ports. No problem you say, I’ll 1 0x2003 0x2003 on the original ’51. These include SPI just use a USB or serial-port-to-parallel- 2 0x2003 0x2005 (enhanced to support transfers up to 32 port adapter. Sorry, Charlie. Those are 3 0x2003 0x2008 bits in length) and I2C (both Master and designed to talk to printers, and the 4 0x2003 0x2003 Slave modes), as well as even more tim- manual cautions that they won’t work. 5 0x2003 0x2005 ing and counting capability in the form Fortunately, my desktop PC has a paral- 6 0x2003 0x2008 of an eight-channel PWM and a two- lel port, and luckily I didn’t even have to 7 0x2003 0x2003 channel pulse-width counter. The PWM twiddle any BIOS (EPP, ECP, etc.) or 8 0x2003 0x2005 features 16-bit resolution and can be driver settings (port addresses or inter- 9 0x2003 0x2008 used for generic timing if PWM capabili- rupts) to get the thing to work. 10 0x2003 0x2003 ty isn’t required. The pulse-width count- Along with evaluation versions of 11 0x2005 0x2005 er feature works with the general-pur- the pro tools (Keil, etc.), the kit comes 12 0x2008 0x2008 pose timers (i.e., T0 and T1) to boost with the bits and pieces of software 13 0x2003 0x2003 event timing and gating flexibility by that allow you to cobble together a 14 0x2003 0x2005 allowing the count start and stop condi- freeware solution. Compared to the 15 0x2003 0x2008 tions to be programmablyWWW.GiURUMELE.Hi2.RO defined in var- elegant (and pricey) one-screen-does- 16 0x2003 0x2003 ious ways. For instance, you could con- all IDEs, it may seem a bit of a hack, 17 0x2003 0x2005 figure the timer to start counting on a but I actually found the old-school 18 0x2003 0x2008 rising edge of one pin and stop counting solution quite serviceable. 19 0x2003 0x2003 on the falling edge of a different pin. The low-budget lash-up comprises 20 0x2003 0x2005 three components: a programmer/ 21 0x2003 0x2008 FREE “C” debugger from Ramtron, a GNU-based 22 0x2003 0x2003 Given the maturity and popularity of “Small-Device C Compiler” (SDCC) 23 0x2005 0x2005 the ’51, one thing you can be sure of is suite, and an editor of your choice. (I that there’s no shortage of develop- installed the freeware “Crimson” edi- Table 2—The ’3074’s built-in debug hardware includes breakpoints and a low-budget real-time trace capability. ment tools. Even as a new player, tor that came on the CD.) As shown here, the latter has the option of tracing into Ramtron has fairly decent support, Ramtron’s JTAG software packages or around tight loops.

84 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 2612003-Cantrell.qxp 11/2/2006 11:32 AM Page 85

breakpoint option that a) b) Thanks to the FPI, stops the processor using the flash mem- based on the value of a ory is as easy and data item. Although a arguably less prone to “value” breakpoint glitches and head- consumes two break- scratching than point slots, it can be using the FRAM. a real timesaver com- This isn’t a knock pared to stopping on on FRAM in gener- every access. al. Ramtron’s stand- There’s even a alone parallel and measure of real-time serial memory chips trace capability built have really grown up into the chip. This is and are already prov- something I’ve seen ing themselves in on bigger and newer real applications. Photo 2—Combining an editor with SDCC and the Ramtron JTAG debugger software (a) would seem like chips, but I can’t Rather, it’s just the a rather primitive solution, but in fact it’s surprisingly effective and easy to use (b). And with a $0 price tag, recall seeing it on a you’re definitely getting more than you pay for. specific implementa- ’51. It tracks branch- tion in the ’3074 that es (i.e., JMPS, but unfortunately not A decent compromise is to exploit seems a bit puzzling. It is all a wakeup CALLS or RETS) nonintrusively (i.e., the fact that most programming-ori- call that FRAM and other new age unlike software “non-real-time” trace ented editors include the capability to memory technologies are headed in the schemes) and has the option of skipping define editor commands and hotkeys right direction but have a ways to go. repeated entries (i.e., tight loops). Yes, that invoke external programs. The popularity and longevity of the it’s kind of clunky just showing the raw Following the directions included ’51 uniquely derives from a “more the addresses (see Table 2). Maybe a future with the Ramtron kit, I was able to merrier” supply side—the Ramtron parts revision could link those raw addresses hook SDCC into the Crimson editor being the latest, although surely not last, back to labels in the source code or even for seamless point-and-click (i.e., no addition. Putting aside the “FRAM provide a “Step Backwards” button. command line) operation (see Photo 2). Enhanced” headline for the moment, Nevertheless, like the “value” break- maybe the story worth noting is that the points, this mini-me real-time trace is NEWS FLASH ’3074 and Ramtron’s other ’51s seem a feature that could come in really After all is said and done, I’d say the pretty darned competitive. Sure, there handy when you’re scratching your “FRAM Enhanced” headlines for the are still some rough edges, but I’d say head over some intermittent “How in ’3074 kind of miss the point. First, as I their combination of FRAM know-how the heck did I end up here?” bug. described earlier, the actual FRAM func- and mixed-signal ’51 expertise gives As a C compiler that supports “small tionality seems a bit disappointing, espe- Ramtron a decent chance for success. I devices” like the ’51, ’68, and PIC, I can cially in light of the more SRAM-like say SDCC has its heart in the right (fast, symmetric read/write) specs for Tom Cantrell has been working on place. Although not fully ANSI-compati- their 1-Mb memory I covered last month. chip, board, and systems design and ble, it does have specific provisions for Indeed, I wonder if a better stacked-die marketing for several years. You may things like I/O, interrupts, and in-line option wouldn’t just combine that chip reach him by e-mail at tom.cantrell@ assembler that reflect a sensitivity to the with a de-flashed (and maybe even de- circuitcellar.com. needs of memory-constrained real-time RAMed?) ’51 MCU core. applications. For example, while the Further irony given all the “flash is REFERENCE compiler fully supports 32-bit floating- dead” hoopla is found in the fact that [1] B. Millier, “Battery-Free Nonvolatile point math, it also offers streamlined the flash memory on the ’3074 actually RAM,” Circuit Cellar 193, 2006. versions of library routines (e.g., printf) works quite well, notably delivering the that minimize theWWW.GiURUMELE.Hi2.RO associated bloat. goods at 40 MHz with no wait states. One thing that you don’t get with Yes, it’s got the usual endurance, reten- SOURCES SDCC (and don’t pay for either) is a tion, and write speed/power limitations, Crimson Editor fancy IDE. Frankly, I think a lot of the but at least it’s easy to use by virtue of a www.crimsoneditor.com popular commercial setups have fea- built-in flash program interface (FPI) VRS51L3074 FRAM-Enhanced ’51 ture-creeped beyond the needs of sim- supplementing the external (i.e., JTAG) MCU ple 8-bit applications. On the other programming option. Invoking the FPI Ramtron International Corp. hand, the old-school command-line shadows in high-level flash memory www.ramtron.com setup (i.e., DOS box) used by SDCC, functions (overlaying the top 1 KB of although capable enough in the hands code space) that take care of all the dirty Small-Device C Compiler of an expert, seems increasingly dated. work for in-application programming. http://sdcc.sourceforge.net/

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 85 ib-197.qxp 11/1/2006 11:47 AM Page 86 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

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

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

UUSSBB Add USB to your next project—it’s easier than you might think! v USB-FIFO up to 8 mbps v USB-UART up to 3 mbps v USB/Microcontroller boards pre-programmed with firmware v 2.4GHz ZigBee™ & 802.15.4 v RFID Reader/Writer Absolutely NO driver software development required! www.dlpdesign.com

Electronic parts for less

Low shipping. FREE shipping on qualifying orders. Digikey pooling to save you S/H. WWW.GiURUMELE.Hi2.ROICD2 clone kit $36 PIC12F683-I/P $1.17 See website PIC16F54-I/P $0.78 for details.

DIPmicro Electronics Fax: (866) 603-7109 [email protected]

www.dipmicro.com

86 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com ib-197.qxp 11/1/2006 11:47 AM Page 87

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 87 ib-197.qxp 11/1/2006 11:47 AM Page 88

Low Cost EDA Software For Windows 98, XP, NT, 2000

v Circuit design package with schematic entry, circuit board layout and simulation (SPICE and digital) for only $599 v Buy modules for as low as $119 v Purchase and download products instantly from our website! v Libraries include latest micros, memories, analog, and others

Contact Mental Automation at (253) 858-8104 http://www.mentala.com

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

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

88 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com ib-197.qxp 11/1/2006 11:47 AM Page 89

MYLYDIA, INC.

Layout Gerber, Prototype Making QUICK TURN PCB & Turnkey @ The Best Prices

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

WWW.MYLYDIA.COM

586-based Industrial Controller

WWW.GiURUMELE.Hi2.RO

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 89 ib-197.qxp 11/1/2006 11:48 AM Page 90

EtherSmart WildcardTM Network -Enables Your Product

$140/100sWWW.GiURUMELE.Hi2.RO

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

90 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com ib-197.qxp 11/1/2006 11:48 AM Page 91

High Quality Enclosures The Most Competitive Price

* Sheet Metal Cabinets * Aluminium Extruded Enclosures * 19inch Standard Cabinets * Plastic Injection * Precision Aluminium Die Casting * Highly Custom Made * Fast Prototyping *,,From 1pc to 10 000 000 pcs WWW.. EzPCB COM

ANYONEWWW.GiURUMELE.Hi2.RO Can Now Easily Hand Solder Surface- Mount Components! Even A 10 Year Old!

www.schmartboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 91 ib-197.qxp 11/1/2006 11:48 AM Page 92

Order online at: Phone: (719) 520-5323 microEngineering Labs, Inc. Fax: (719) 520-1867 www.melabs.com ® Box 60039 Development Tools for PIC Microcontrollers Colorado Springs, CO 80960

® USB Programmer $119.95 LAB-X Experimenter Boards BASIC Compilers for PICmicro for PIC® MCUs (with accessories) Pre-Assembled Boards Easy-To-Use BASIC Commands Available for 8, 14, 18, 28, Windows 9x/Me/2K/XP Interface and 40-pin PIC® MCUs RoHS ™ Compliant 2-line, 20-char LCD Module PICBASIC Compiler $99.95 9-pin Serial Port BASIC Stamp 1 Compatible Supports most 14-bit Core PICs Programs Sample Programs PIC MCUsWWW.GiURUMELE.Hi2.ROBuilt-In Serial Comm Commands including Full Schematic Diagram low-voltage Pricing from $79.95 to $349.95 PICBASIC PRO™ Compiler $249.95 (3.3V) devices Supports All PICmicro® MCU Families Direct Access to Internal Registers Includes: PICPROTO™ Prototyping Boards Supports In-Line Programmer, USB Cable, Interrupts in PICBASIC and Assembly ZIF Programming Adapter for 8 to 40-pin DIP, Double-Sided with Plate-Thru Holes Built-In USB, I2C, RS-232 and More Software for Windows 98/Me/NT/2K/XP Circuitry for Power Supply and Clock Source Level Debugging Large Prototype Area Parallel Port Programmer Boards Available for Most PIC® MCUs See our full range of products, including starting at $59.95 Documentation and Schematic books, accessories, and components at: Serial Port Programmer Pricing from $8.95 to $19.95 www.melabs.com EPIC™ starting at $79.95

92 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 11/2/2006 11:39 AM Page 93

1 2

3 CROSSWORD

4

56

7 8

9

10 11

12 13

14

15

16 17

18 19

20

21

Accross Down 3. GND 1. A place online where you can meet other engineers and discuss 5. Modem light: “Ready” important topics and ideas. 7. Former U.S. president (b. 1924) with a back- 2. 1,000,000,000,000,000,000 bits ground in nuclear physics and the study of reac- 4. Postal delivery. Hint: mollusk tor technology. Hint: 39 6. The IBM computer introduced in 1956 that featured disk storage. 10. A partition,WWW.GiURUMELE.Hi2.RO or screen, placed between a micro- 8. Twenty-four is the least common multiple of 12 and which num- phone and a source of sound. ber? 13. A punctuation mark, number, letter, or symbol. 9. Extension for a batch file. 14. Eight-sided polygon. 11. Field of study that deals with how humans interact and work with 15. A character that you are not allowed to use machines. when naming a file. 12. The dog Circuit Cellar founder/editorial director Steve Ciarcia 18. A low-density white metallic element. has mentioned in his editorials. 21. The H in H-menu. 16. Text message: “By the way” 17. A PC that features an Intel processor and a Mac operating system. 19. Text message: “In my humble opinion” The answers are available at 20. A standard for connecting peripherals and PCs. Hint: “scuzzy” www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 197 December 2006 93 94-advertiser's index.qxp 11/2/2006 11:41 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 2 Echelon Corporation 26 Linx Technologies 29, 81 Rabbit Semiconductor

90 AP Circuits 19 Efficient Computer Systems 11 Logic Supply, Inc. 87 Rabbit Semiconductor

88 All Electronics Corp. 31 ExpressPCB 13 Luminary Micro 89 Reach Technology, Inc.

87 Apex Embedded Systems 39, 91 ezPCB 87 MCC 17 Renesas

41 Arcom Control Systems 86 FDI-Future Designs, Inc. 89 MSC Conference 71 Saelg Company

7, 79 Atmel 40 FIRST Robotics Competition 58 MVS 91 Schmartboard

88 Avocet, Inc. 90 Front Panel Express, LLC 11 Maxstream 47 Sealevel Systems

91 Bagotronix, Inc. 89 General Circuits, Inc. 88 Mental Automation 21 SEGGER Microcontroller Sys. LLC

5 Bitscope Designs 88, 91 Grid Connect 91, 92 Micro Digital, Inc. 25 Sierra Proto Express

65 CWAV 87 Hagstrom Electronics 92 microEngineering Labs, Inc. 89 Smart Home Systems

56 CadSoft Computer, Inc. 34 HI-TECH Software LLC 82 mikroElektronika 30 Spark Fun Electronics

10 Camosun College 49 Holmate/Holtek Semiconductor, Inc. 90 Mosaic Industries, Inc. 92 Systronix

29 Circuit Specialists, Inc. 87 IMAGEcraft 50 Mouser Electronics 92 TAL Technologies

3 Comfile Technology, Inc. 90 Intec Automation, Inc. 89 Mylydia, Inc. C3 Tech Tools

90 Conitec 90 Intrepid Control Systems C2 NetBurner 72, 73 Technologic Systems

90 Custom Computer Services, Inc. 57 Intronix Test Instruments, Inc. 77 Nurve Networks LLC 86 Technological Arts

64 Custom Solutions, Inc. 25 Ironwood Electronics 92 Ontrak Control Systems 89 Tern, Inc.

1 Cypress MicroSystems 64, 91 JK microsystems, Inc. 89 PCB Fab Express 55 Tibbo Technology, Inc.

86 DIPmicro Electronics 63 Jameco 27 PCB-Pool 92 Trace Systems, Inc.

86 DLP Design 43 Jeffrey Kerr, LLC C4 Parallax, Inc. 86 Triangle Reasearch Int’l, Inc.

43 Decade Engineering 10 Keil Software 86 Phytec America LLC 48 Tri-M Systems, Inc.

40 DesignCon West 77 LabJack Corp. 87 Phyton, Inc. 88 Zanthic Technologies, Inc.

26 EMAC, Inc. 77 Lakeview Research 88 Pioneer Automation, Inc.

89 Earth Computer Technologies 87 Lawicel AB 88 Pioneer Hill Software

95 EasySync Ltd. 47 Lemos International 91 Pulsar, Inc.

Preview of January Issue 198 ATTENTION ADVERTISERS Theme: Embedded Applications February Issue 199 Multi-Input Temperature Logger Deadlines The Power of Flash: Use Flash Memory for More than Storing Code Space Close: Dec. 11 Arby: An Arbitrary Waveform Generator with a Twist Material Close: Dec. 20 Voltage Solutions: Harness the Power of Voltage Converters Theme: Self-Powered WWW.GiURUMELE.Hi2.ROSolar Data Logger Wireless Communications QuickComs: An M16C/62P-Based RS-232 Analyzer BONUS DISTRIBUTION: IPC Printed Circuits Expo, APEX, Designers Summit, and APEC FROM THE TRENCHES Hello World … Want Cookie Call Shannon Barraclough APPLIED PCs Dive Into the ZigBee Pool: An Easy Way to Start Moving Messages now to reserve your space! FROM THE BENCH Green Energy 860.872.3064 e-mail: [email protected] SILICON UPDATE Hot Chips 18

94 Issue 197 December 2006 CIRCUIT CELLAR® www.circuitcellar.com 81.qxp 6/6/2006 12:02 PM Page 1

WWW.GiURUMELE.Hi2.RO steve_197_editorial.qxp 11/2/2006 11:43 AM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director Going for the Brass Ring

I don’t know whether it’s genetic predisposition, but engineers are very predictable. Think about other people for a minute. Someone with new- found artistic talents paints a masterpiece and what does he do? Open a studio or an art gallery? Nope. He hangs it on the wall. Another per- son aspiring to be a gourmet cook creates the piece de resistance at a dinner party and what is their next thought? Start a restaurant? Nope. They just want everyone to dig in and eat it. An accomplished administrator refinishes and converts an old bureau into a magnum opus by night. Is his next thought to open a restoration shop? Nope. It’s how to finish the meeting and find the next old piece of furniture. The business crowd likes to refer to us as a bunch of geeks, but I think it’s quite the opposite. An engineer designs a widget and publishes it in Circuit Cellar or is among the winners in our design contests and what is his next thought? Go to work tomorrow and do the same old job? Nope. He’s trying to figure out how to start a company to manufacture it. More than any other subject, the question of what should engineers do in the long term fills my in-basket. Perhaps it is the realization that all of our technical training is aimed at designing widgets that someone else makes money manufacturing, or maybe it’s the insecurity of know- ing that we become dispensable when we can no longer create great widgets for an employer, that makes us feel more like a traded commod- ity than a tenured professional. Longevity in this business isn’t assured, and this isn’t a union job. The typical career path that most engineers take only adds to the dilemma. While there are some companies that still have a promotion and salary structure that rewards engineers who stay “technical,” the majority of companies reserve high-paying jobs strictly for business-side man- agement. After a few years of designing widgets, the only way to raise your salary is to become a project manager or otherwise “oversee” oth- ers doing the real design work. This only adds to fears of obsolescence. Are you a real engineer who can get another job, or are you now a proj- ect manager (whatever that is)? I got an e-mail this week from a Luminary Micro contest contestant. Like many of our readers, he is entering a contest project specifically because of engineering career anxiety. After 11 years of working for a big company in Silicon Valley, he now finds himself worrying about being outsourced or merged. His logic is that the contest serves a dual purpose. Knowing Stellaris ARM refreshes his engineering credentials with leading-edge design knowledge for his resume and being able to reference a winning or Distinctive Excellence design posted on Circuit Cellar and Luminary Micro adds instant credibility. His title may be a project manager, but this proves he is still an engineer. The second and loftier goal is using the contest as an incentive to invent the perfect widget. Deep down, most engineers know that the only hedge to the corporate rat race is being top dog instead of one of the minions. Of course, not everyone is cut out for self-employment, and get- ting there has great risks. The goal for many engineers is to bootstrap the process by designing something on the side that hopefully receives royalties or attracts manufacturing investment money from others. This happens more often to our contest project entrants than you might think. I’m not sure why anyone would want to ask my opinion, but perhaps it’s because I seem to have followed the career path they seek. A long time ago, I was one of those engineers in corporate America wondering about the future. It took five different jobs, but ultimately I could see the handwriting on the wall all too clearly. As you know, I designed a bunch of widgets on the side and my publicity was BYTE. Ultimately, the inter- est in the designs was enough that they were manufactured. Like the fantasy, I got to play top dog at the company for a number of years and start a magazine too. I guess I’ve followed the course that most engineers seek and had a good time. Before you quit your day job to go for the brass ring, how- ever, I should caution you about taking it in steps. If you start a company and work at it for a reasonable length of time, you join the club. Club benefits include a good income, no office politics, freedom to do what you want, and as many company perks as you and the IRS can negoti- ate. The downside “benefit” is that you can’t go back. Once you have a taste of real business freedom, you become non-corporate (no longer a committeeWWW.GiURUMELE.Hi2.RO person). At that point, you either have to make it really big and retire early or stay in the club because you can never be happy work- ing in big-company America again (and all the crap that goes with big-company jobs). So, it’s safe to continue renewing your subscription for quite a while. I may be an engineer who still knows a thing or two technically and could get a job. But, I’ve definitely determined that present club membership precludes it.

[email protected]

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

WWW.GiURUMELE.Hi2.RO C4.qxp 10/26/2006 10:57 AM Page 1

WWW.GiURUMELE.Hi2.RO