®
THE
MAGAZINE FOR
COMPUTER APPLICA
How To Deal With EMC Power Line Modems and Home Control One-Bit Wireless I/O Port Handling SMDs By Hand
0 5>
7
25274 75349
9
TIONS
Digital Oscilloscopes
2 Channel Digital Oscilloscope • 100 MSa/s max single shot rate • 32K samples per channel • Advanced Triggering • Only 9 oz and 6.3” x 3.75” x 1.25” • Small, Lightweight, and Portable • Parallel Portinterface to PC • Advanced Math options • FFT Spectrum Analyzer options
DSO-2102S $525 DSO-2102M $650 Each includes Oscilloscope, Probes, Interface Cable, Power Adapter, and software for Win95/98, WinNT, Win2000 and DOS.
Logic Analyzers • 40 to 160 channels • up to 500 MSa/s • Variable Threshold • 8 External Clocks • 16 Level Triggering • up to 512K samples/ch • Optional Parallel Interface
• 24 Channel Logic Analyzer • 100MSa/S max sample rate • Variable Threshold Voltage • Large 128k Buffer • Small, Lightweight and Portable • Only 4 oz and 4.75” x 2.75” x 1” • Parallel Port Interface to PC
• Optional 100 MSa/s Pattern Generator
•• Windows Trigger Out 95/98 Software
$1350 LA4240-32K (200MHz, 40CH) $2000 LA4280-32K (200MHz, 80CH) $1900 LA4540-128K (500MHz, 40CH) $2800 LA4580-128K (500MHz, 80CH) LA45160-128K (500MHz, 160CH) $7000 All prices include Pods and Software
LA2124-128K (100MSa/s, 24CH) Clips, Wires, Interface Cable, AC Adapter and Software
$800
www.LinkIns4.com Link Instruments
•
369 Passaic Ave Suite 100 •
•
Fairfield, NJ 07004 (973) 808-8990 •
•
Fax (973) 808-8786
S E R
12 20
28
Power Line Modems Meet Home Control Brian Millier
Tiny Planet—A One-Bit Wireless I/O Port Claudio Lanconelli & Alberto Ricci Bitti
Working with EMC
ISSUE
George Novacek
U T A E F
46
Hand-Soldering Fine-Pitch QFP Devices John Taylor
50
62
S N M U L O C 34
56
70
76
w w w . c i r c ui t c e l l a r .c o m
RoCK Specifications Part 2: The Circuitry
142
Joseph Jones & Ben Wirz
Design Your Own Microprocessor Jim Turley
I
ROBOTICS CORNER Behind the Scenes Part 1: Controlling an Animatronics System
6
Task Manager Jennifer Huber Getting the Right Signal
8
New Product News edited by John Gorsky
Daniel Ramirez
I
APPLIED PCs Taking a Swim with Atmel’s STK500 Fred Eady
I
FROM THE BENCH You’re Not Alone
11
Test Your EQ
94
Advertiser’s Index June Preview
96
Priority Interrupt Steve Ciarcia The Insanity of Sucess
Dealing with Isolation Jeff Bachiochi
I
SILICON UPDATE I-Way the Hard(ware) Way Tom Cantrell
C I R C U I TC E L L A® R
Issue 142 May 20025
TASK MANAGER EDITORIAL DIRECTOR/PUBLISHER Steve Ciarcia
Getting the Right Signal
CHIEF FINANCIAL OFFICER Jeannette Ciarcia
WEB GROUP PUBLISHER Jack Shandle
ACCOUNTANT Howard Geffner CUSTOMER SERVICE Elaine Johnston
MANAGING EDITOR Jennifer Huber
t
raditionally, we have used signals to communicate a plethora of information, because often, a signal is more straightforward than written or oral communication. Without the benefit of proximity, we can still convey messages. Additionally, many signals are universally understood and cross the boundaries of language and culture, such as waving a white flag. Signals are used every day. Beams of light shed from lighthouses along coastlines communicate locations of harbors and obstacles to ensure the safety of seamen and their ships. Since the mid-nineteenth century, people across the world have used Morse code for radiotelegraphy. We also have sign language and braille. With a set of hand gestures and series of bumps, both deaf and blind people can communicate as well as people with sight and hearing. Just as in other aspects of life, signals are important, if not crucial, in engineering. A multitude of various projects involve signal processing. This month, you get to read about some projects that I’m sure you’ll enjoy. For instance, on page 12, you’ll find Brian Millier’s take on home control. As Brian explains, Canadian winters can be brutal, so controlling the air temperature inside his home is essential to keeping his family comfortable. His creative plan involved adding indoor and outdoor humidity sensors using the least amount of wire hassle. Now, his home control unit is receiving all of the right signals and
ART DIRECTOR KC Prescott
SENIOR EDITOR Rob Walker
GRAPHIC DESIGNERS Cindy King Mary Turek
TECHNICAL EDITOR Jennifer Belmonte WEST COAST EDITOR Tom Cantrell CONTRIBUTING EDITORS Ingo Cyliax Fred Eady George Martin George Novacek NEW PRO DUC TS EDI TOR John Gorsky
STAFF ENGINEERS Jeff Bachiochi John Gorsky QUIZ COORDINATOR David Tweed EDITORIAL ADVISORY BOARD Ingo Cyliax Norman Jackson David Prutchi
PROJECT EDITORS Steve Bedford David Tweed Cover photograph Ron Meadows—Meadows Marketing PRINTED IN THE UNITED STATES
ADVERTISING ADVERTISING SALES MANAGER Kevin Dows Fax: (860) 871-0411 (860) 872-3064 E-mail:
[email protected] Cell phone: (860) 930-4326
ADVERTI SING COORDI NATOR works perfectly. Everyone else suffering in a cold climate can benefit from the Valerie Luster Fax: (860) 871-0411 success of Brian’s design, as well. Note, too, that this home control scheme (860) 875-2199 E-mail:
[email protected] can trap precious air-conditioned air to help you survive August in hot climates. ADVERTISING CLERK For a peek behind the curtain, you’ll also want to turn to page 34 to read Sally Collins Fax: (860) 871-0411 (860) 875-2199 E-mail:
[email protected] about controlling an animatronics system. Daniel Ramirez explores the world of special effects and brings us a step-by-step guide to building a DIY animaCONTACTING CIRCUIT CELLAR SUBSCRIPTIONS: tion system. Inspired by some of Hollywood’s legendary pioneers including INFORMATION: www.circuitcellar.com or
[email protected] To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or Walt Disney, Daniel designed a unique animation system that resides on a
[email protected] remote-controlled, servo-propelled robot. PROBLEMS:
[email protected] GENERAL INFORMATION: Daniel’s article serves the dual purposes of providing another example of TELEPHONE: (860) 875-2199 Fax: (860) 871-0411 how critical signal processing is to engineering as well as marking the advent INTERNET:
[email protected],
[email protected], or www.circuitcellar.com EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066 of Circuit Cellar’s new Robotics Corner. The Robotics Corner is a new feature NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066
[email protected] to our regular lineup. The idea came about as a result of the numerous subAUTHOR CONTACT: missions and positive feedback from all of you regarding the annual Robotics E-MAIL: Author addresses (when available) included at the end of each article. theme issue. Every year, the task of picking which articles to publish in our For information on authorized reprints of articles, Robotics issue increases in difficulty because we’re inundated with article pro- contact Jeannette Ciarcia (860) 875-2199 or e-mail
[email protected]. posals about intriguing projects. Now, you’ll have an extra dose of the robotics CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pubcontent you love each month. As always, you are our source for fresh content, lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico so head over to the Author’s Guide at www.circuitcellar.com/authors and pre- $31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico $55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money pare to share your inventive project with the rest of us. order, or check drawn on U.S. bank. Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH I want to say a special thanks to The New England Assistive Technology 03755-5650 or call (800) 269-6301. Marketplace (NEAT), which loaned us the children’s braille book about snakes Postmaster:Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the presented on the cover. For more information about assistive products, please Circuit consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of reader-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or visit the NEAT web site at www.neatmarketplace.org. from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction. The reader assumes any risk of infringement liability for constructing or operating such devices.
[email protected]
6
Issue 142
May 2002
Entire contents copyright © 2001 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.
® CIRCUIT CELLAR
www.circuitcellar.com
NEW PRODUCT NEWS Edited by John Gorsky SINGLE BOARD COMPUTER
The TC51 SBC is an industrial controller assembly that is easy to program and connect to external signals. The board can be programmed as a standalone controller using its on-board Tiny Machine Basic programming language, or it can be used as an RS-232 serial data acquisition board. The TC51 is based on the Atmel AT89C4051 microcontroller chip with EEPROM program memory, and can be reprogrammed using any number of software development tools and device programmers available for Atmel microcontrollers. There are two RS-232 ports with true RS-232 drivers and DE-9 connectors for communications. Screw terminal connectors are used for all of the digital, analog, and relay connections, which include four 10 A form C relays, four logiclevel signals usable as inputs or outputs, and two 12-bit A/D inputs. The board contains LCD support circuitry that interfaces to a 16-pin 0.1 header connector matching most LCD module connections. It also features an on-board contrast pot. LCD commands are included in the Tiny Machine Basic language. Its on-board power supply has a wide input range and includes 5- and 12-V outputs for use by external ″
devices. The TC51 package includes a serial port cable for connection to a PC-compatible computer, a wall block power supply, host computer software, programming examples, and hardware and software reference manuals. The TC51 costs $129 in single quantities.
IndustroLogic (314) 707-8818 www.industrologic.com
REFLECTIVE COLOR SENSORS
The TRS1722, TRS1755, and TRS1766 are three new reflective color sensors that combine a color LED die and a light-to-voltage converter with a corresponding color filter in a surface mount package. Each sensor is designed to emit and detect one of three primary colors: red, blue or green. The TRS1722 emits red, the TRS1755 emits green and the TRS1766 emits blue light. The output of each device is a voltage that is directly proportional to the reflected color light. Because the sensors emit and respond to a single color, they provide superior discrimination (signal to noise ratio). In addition, with the LED drive current being as low as 250 µA (TRS1766, blue), the sensors are well suited for
8
Issue 142
May 2002
SOLID STATE RELAY MODULE
The WTSSR-M is a stackable RS-232 data module with five optically isolated solid-state relays. The relays can be wired directly in place of or parallel to existing push buttons and toggle switches to enable software control of the switch operation. Relay outputs also can be used to switch external solenoids, actuators, and high-current relays. A relay can be instructed to open or close and remain at that new state or switch back to the previous state after a user-defined delay period. Each relay can be controlled individually or as a group. The built-in event sequencer allows you to load a series of relay on/off patterns and time delays that will execute sequentially. Modules in this series can be plugged end-to-end on a common RS-232 cable attached to the serial port of a PC, laptop, or other host. An on-board 32position DIP switch sets the address of each module, which is used for identifying data transmitted from it as well as directing data transmitted by the host. The data bus supports full anti-collision discipline between connected modules and will allow up to 32 modules to share the same communications line. Power is supplied by an external 8- to 30-VDC source (not included) to the first module in the chain and is carried down the RS-232 cable to successive modules. The WTSSR-M sells for $69.
Weeder Technologies 850-863-5723 www.weedtech.com
low-power and battery-operated applications. The TRS1722, TRS1755 and TRS1766 reflective color sensors combine high-output LEDs with the TAOS highsensitivity color sensors. These color sensors are based on the popular TAOS TSL257 light-to-voltage converter platform. With the TRS1722, TRS1755 and TRS1766, users can achieve 8 bits of resolution in their designs. Each of the three TAOS color sensors has a suggested resale price of $1.36 in 1000-piece quantities.
® CIRCUIT CELLAR
Texas Advanced Optoelectronic Solutions (972) 673-0759 www.taosinc.com
www.circuitcellar.com
NEW PRODUCT NEWS DIGITAL TEMPERATURE SENSOR
The DS1631 digital thermometer and thermostat is a small 0.5°C accurate digital temperature sensor. As electronics decrease in size, PC board real estate has become increasingly valuable. Meantime, the need for precise thermal management has reached critical proportions. The microSOP footprint of the DS1631 is half the size of its competitor. Its accuracy provides the tight thermal control needed for maximum circuit performance. The DS1631 provides 9-, 10-, 11-, or 12-bit digital temperature readings over a –55°C to 125°C range, with 0.5°C accuracy over a 0°C to 70° C range. It has thermostat functionality with nonvolatile (EEPROM) user-defined trip points that allow you to customize the threshold temperature and output hysteresis. Communication with the DS1631 is achieved through a standard twowire serial interface. Prices start at $1.77 for quantities of 1000.
Dallas Semiconductor (800) 998-8800 www.maxim-ic.com
w w w . c i rc u i t c e l l a r. c o m
386 ENGINE
The 386 Engine is a high-performance, credit cardsized module derived from a range of sophisticated communication equipment that has traditionally been used in large-scale banking and gaming networks. The 386 Engine consists of an Intel 386EX running at 25 MHz with compact flash memory, 10BaseT Ethernet, USB, two RS-232 ports, a real time clock, and general-purpose I/Os. The processor bus is connected to external connectors so other chips can be directly controlled by the processor. The unit is designed for minimum power consumption. Both Linux and DOS are supplied as standard features with the product and there is a full suite of communications protocols written using the EUCA protocol stacks, where available protocols include SNA, HDLC, X.25, and TCP/IP. The 386 Engine costs$199.
Sumbox (952) 201-6507 www.sumbox.com
C I R C U I TC E L L A® R
Issue 142
May 20029
NEW PRODUCT NEWS G CODE CONTROLLER FOR WINDOWS
The G Code Controller software for Windows combines a graphical part program development, animation, and verification environment into a powerful PC-based machine controller. The system can control up to five axes of motion, three displayed in a scalable, rotatable image as well as rapid front, end, and side views. It also offers tool length and radius offset compensation, with look-ahead for optimizing around corners and through vertical motion. The G Code Controller incorporates canned cycles, fixture offsets, multiple part programs per job, and unlimited subroutine nesting. Intuitive menus make setting up, saving, and retrieving jobs quick and convenient. Additionally, user-defined M, T, and S codes with advanced digital output, switch input, and stage manipulation are available. The device uses the 32-bit Indexer LPT/XQ driver for exceptionally smooth N-block look-ahead contouring in real time from IEE-1284 standard parallel ports. Ability Systems Corp. The G Code Controller costs $375 and the Indexer (215) 657-4338 LPT/XQ costs $349. www.abilitysystems.com
10
Issue 142
May 2002
® CIRCUIT CELLAR
www.circuitcellar.com
CIRCUIT CELLAR
Y
Problem 1—Design a simple circuit based on combinational logic that generates pulses at twice the frequency of an input signal.
Problem 3—Would the following code compile successfully? What is its output?
Contributed by Naveen PN
Problem 2—What does the following code output?
E
#include
main () { printf ("%c", 7["Circuitcellar" } Contributed by Naveen PN
#include
Problem 4—A crystal can be modeled as a series-resonant LCR circuit. What are typical L, C, and R values, in terms of orders of magnitude?
void main (void) { unsigned int a = 6; int b = -20; (a + b > 6) ? puts (">6") : puts ("<=6"); }
Contributed by Dave Tweed
Contributed by Naveen PN
What’s your EQ?—The answers and 4 additional questions and answers are posted at www.circuitcellar.com You may contact the quizmasters at [email protected]
RS232/RS422/RS485 Converters RS232 TO RS485 2 wire • Makes your RS232 port an RS485 port • Supports up to 40 RS485 CMC’s low cost converters adapt any devices RS232 port for RS422 or RS485 • Automatically determines operation. These converters provide your data direction. • Signal powered version RS232 device with all the advantages of available RS422 or RS485 including reliable high ADA485 (requ ires 9VDC) $79.00 speed operation (up to 200 kbaud) and 89.00 data transmission distances up to 5000ADA485-1 for 110VAC ADA485L sign al powered 84.00 feet. Two AD422s can be used to extend any RS232 link up to 5000 feet. Completely transparent to the system; RS232 TO RS485 no software changes of any type are 4 wire necessary. Converts an RS232 port for
RS232 TO RS422 • Converts bi-directionally • between RS232 and RS422 • Use as a short haul modem• • Plug in and go. No software• changes required
use with RS422 or RS485 devices Supports up to 40 RS485 or RS422 multidrop devices Adds multidrop capability to RS232 devices Automatically determines data direction.
AD422 (Requires 9VDC) $79.00 AD422-1 for 110VAC 89.00 ADA425 (requires9VDC) $89.00 99.00 AD422L sig nal powered 84.00 ADA425-1for 110VAC Mention this ad when you order and deduct 5% Use Visa, Mastercard or company purchase order
code CC83
Connecticut microComputer, Inc. PO BOX 186, Brookfield,CT 06804
WWW.2CMC.COM w w w . c i rc u i t c e l l a r. c o m
C I R C U I TC E L L A® R
(203)740-9890
Fax:(203)775-4595 Issue 142
May 200211
dozen years ago when I built my home, energy conservation was a big consideration in home design. In Canada, the R-2000 building certification program
Although the technology in this area has undoubtedly progressed, the HRV unit initially installed in our house had the most rudimentary control system: an inexpensive humidistat (mounted inside the unit) that sampled the air passing through the unit. The system had provisions for an external humidistat that could be mounted in the actual living area of the home, but the contractors didn’t provide this optional humidistat. During the building of the house, I just had too many other things on my mind to think of it. The only control scheme the unit came with turned the unit on if the humidity inside the house became too high. Actually, it sensed the humidity in the basement where the unit was located, which was not particularly representative of the house itself. Humidity is a legitimate concern, but it is only one of many. For instance, a minimum number of total changes of interior air per day are needed for health and comfort reasons. There’s also no point in running the unit to reduce humidity indoors, if the humidity outdoors is as high, or higher than indoors. There are times of the day
addressed this issue by definingsealing minimum standards for insulation, to prevent air leaks, and many other issues involving energy conservation. At the time, it was known that you couldn’t make a house airtight for energy conservation purposes without introducing some rather nasty health and comfort issues. To address these concerns, air exchangers were introduced. Obviously, any device that exchanges the air in a home on a regular basis will suck out a lot of heated air in the winter. Therefore, air exchanger designs soon improved and became known as heat recovery ventilators (HRVs). The new designs included a heat exchanger to recover
when outdoor temperature is more likely the to be moderate and operation at this time would be more efficient. Last but not least, I don’t like the unit to come on at 3 a.m. and blow cool air on me while I’m trying to sleep! What I sought to design was a controller that considers all of the above concerns. Because the house construction is complete (including a finished basement), running additional control wires would not be an easy task. I began searching for a method that would not involve running a lot of control wires around the house. I decided that I would want temperature and humidity sensors both inside and outside of the house. The
some of the heat that would otherwise be pumped outside and lost. These HRVs are 60–80% efficient at best, so there’s still a significant amount of heat lost in operation. I live in a cooler climate, but I suspect that in areas with hot summers, the loss of air-conditioned air during the summer is of equal concern.
indoor sensors would be part of the master control module that would be located in the main living area. I decided that it would be easy to wire the outdoor sensors directly to the slave controller mounted next to the HRV unit in the basement using a small hole in the outside wall of the house where other wires already trav-
FEATURE ARTICLE Brian Millier
Power Line Modems Meet Home Control
a
Energy conservation is an important consideration when building a house. But, a poorly designed control system prevented Brian’s heat recovery ventilators from being as effective as possible. So, he tried some new power line modems to get the sensing units to talk to each other.
12
Issue 142
May 2002
® CIRCUIT CELLAR
www.circuitcellar.com
eled. Communication between the master and slave modules would be accomplished using power line modems, which I’ll described in detail later on.
If the inside temperature is greater than the temperature 3 set point and the outside temt 2.5 perature is less than the u o 2 e inside temperature, then turn g a lt 1.5 on the HRV. o V 1 CONTROL ALGORITHMS And now for the last rule. 0.5 Depending on the climate Regardless of humidity, if the 0 where you live, the optimum outside temperature is more 0 20 40 60 80 100 % RH operation of an HRV could vary than 10° greater than indoors, significantly from what I decid- Figure 1—The SC-600 exhibits a linear response between 20% and 90% RH. turn off the HRV. ed was best for my home. Let In practice, there will be me briefly describe our climate and be heating the cold outside air when it many times when inside humidity (or the control algorithm that I settled on. was pumped in, it would actually temperature) conditions can’t be Because conditions change with the exhibit a much lower relative humidiimproved by running the HRV because seasons, I implemented a different ty after it got inside and was heated. outside conditions are even worse. algorithm for each. The solution is to convert the RH This controller won’t overcome this, Our winters are moderate, but it’s readings into precipitable water readbut at least it won’t waste energy by cold enough that all doors and winings, which are temperature-independ- needlessly running the HRV. dows must be kept closed. To keep the ent, and compare those values. If the air fresh and healthy, the HRV must outside air is drier than inside air, the MEASURING HUMIDITY run at least a minimum number of HRV should be turned on. To save One of my previous projects hours to provide the necessary air heat, I decided to prevent the HRV required a low-cost humidity sensor. exchange. The best results occur when from running if the outside temperaA search on the ’Net produced a referthis doesn’t happen in one long cycle, ture is more than 45°F below the ence to an inexpensive relative humidbut instead is broken into several inside temperature. Of course, this is ity sensor ($15 in unit quantities) intervals throughout the day. a subjective decision that might not made by Ohmic Instruments. I ended The new control program allows me work in colder climates. up using the Ohmic sensor for both to specify any number of intervals durNote that I don’t address what hapthat project and this one. ing which the HRV will run, regardless pens when the inside humidity is too The SC-600 module contains both a of any other conditions. To maximize low. This does occur, but generally the humidity sensor and the associated SC-600 Humidity sensor response
3.5
efficiency, it makes sense to place of these running cycles in the after-some noon, when the outside temperature is generally at its highest. The controller also allows me to specify any number of favored time periods. These are the times in which the controller will use the readings from its indoor/outdoor sensors to decide whether or not to run. Basically the control algorithm works as follows. In the winter, it’s important that the inside humidity does not get too high because the windows may suffer from condensation and, if serious enough, wood rot may occur. So, the controller checks to see if the inside humidity is higher than the user-specified setting. If it is, then you must
outside humidity alsowill lownot in winter, so turning on the is HRV help. In the summer, the rules are different. Our summers are moderate in temperature and not extremely humid, with temperatures generally cooling down each evening. I can still program run cycles to ensure a minimum number of air changes per day, but in the summer windows are often left open, making this issue less important. However, I can program the unit to run for a period in the late evening in an attempt to cool down the house. During the user-defined favored periods for run cycles, the controller reads its sensors like during the winter. In the summer, however, different rules
electronics to condition the humidity sensor signal into a useful range. The sensor must be driven by an AC excitation source, which in this case is a 440 Hz, 150-mV signal provided on the module. The actual sensor exhibits an impedance that varies in an inverse logarithmic relationship to the relative humidity. The module contains an on-board chip to convert this relationship into a linear function. As you can see in Figure 1, the 20% to 90% RH range of the sensor is linearly converted into a voltage between 1.25 V and 3 V. The specification sheet shows a set point accuracy of ±2% and the units that I obtained meet this specification.
consider whether or not pumping in air from outside will help the situation. At first I considered comparing inside and outside relative humidity (RH) values directly to make the judgment. This won’t work because an RH reading takes into account the fact that cold air can’t hold as much moisture as warmer air. Because we would
apply. Let’s go through these rules. If the inside humidity is greater than the humidity set point and the outside humidity is less than the inside humidity, then turn on the HRV. If the inside humidity is less than the humidity set point and the outside humidity is greater than the inside humidity, then turn on the HRV.
Relative humidity sensors are normally extremely sensitive to temperature, but this module is temperaturecompensated. The outdoor sensor will get rained on, so the fact that the SC600 sensors recover from condensation was important. The operating temperature is –4°F to 140°F. Although the outdoor temperature would go lower
w w w .c i rc ui tc e l l ar.c o m
C I R C U I TC E L L A® R
Issue 142
May 200213
than –4°F on occasion, under these conditions the RH is usually low and the temperature is a more important factor. The module itself measures 35 mm × 20 mm × 15 mm and is a three-wire device: 5 V, signal, and ground. Photo 1 is a split view showing both the sensor and the electronics side of this module.
MEASURING TEMPERATURE I was initially tempted to try something different for the temperature sensors. I use precision linear thermistors for sensitive temperature measurements at work as well as thermocouples for wide range measurements. I had some samples of Dallas one-wire thermometers as well as DS1620 SPI thermostat chips, and my BASCOMAVR compiler even has built-in support for both of these protocols. However, because the humidity sensors produced a DC voltage output, and the ’8535 microcontroller contained an eight-channel 10-bit analogto-digital converter, it made more sense to use temperature sensors that also produced a voltage output. I chose the National Semiconductor LM34DZ in a TO-92 package.
choice because its temperature range extends down to –40°F and it will measure down to 5°F without a bipolar ADC or extra circuitry, which is more expensive and probably not necessary in my climate. The Plinius power line modem, described in detail later, contains an internal 2.50-V reference, so I used that for the ADC’s reference voltage. Although this was not an ideal voltage, it was a good compromise for both the humidity and temperature sensors, and it provided enough resolution for my purposes. The LM34DZ’s accuracy is rated at only ±3°F. The units I’ve used are certainly no more accurate than this, so I included a calibration constant in my program to correct this.
PLINIUS TO THE RESCUE For this project, I had srcinally intended to use some low-cost wireless modules to interconnect the various sensors and the main controller. Around this time, however, I received an e-mail from a long-time Circuit Cellar reader, Vincenzo Izzo from Italy. He had read my recent article “A Wireless Remote Control MP3
Cellar Jukebox” 134) and as it turns out,(Circuit he works for Telecontrolli (manufacturer of the wireless modules I used in that project). He sent me some datasheets on the Plinius bidirectional power line modems, which he thought I might find useful. The modSY HDB HDB DAB SAB DAT DAT CR ules are manufactured by NC 2 1 A1 A2 C Telecontrolli using an ASIC Each byte in the packet is described as follows: designed by Siemens Metering SYNC Sync byte (54 H) is predefined by HTH HDB2 Header definition byte 2 has a value of 50 H, which defines: in Italy. After reading the 1-byte source and destination addresses No protocol specific flag bytes datasheets, I agreed with him No ACK/NAK packet requested in return that these modems would be a HDB1 Header definition byte 1 has a value of 32 H, which defines: good fit for my current project. 8-bit CRC error detection 2 bytes of data The project’s main controller would be near a power outlet DAB Destination address byte = 1 for the master on the main floor of the house, = 2 for the slave
Unlike many other solid-state sensors whose signal output is referenced to absolute zero Kelvin, this unit produces 10 mV/degrees Fahrenheit over the 32°F to 212°F range. For the outdoor sensor, the LM34CZ is a better
SAB
Source address byte = 1 for the master = 2 for the slave
DATA1
Runflag (from master to slave) Outside temperature (from slave to master)
DATA2
Unused (from master to slave) Outside humidity (from slave to master)
CRC
1-byte CRC (error detection)
Figure 2—For my project, I used this form of the SNAP packet.
14
Issue 142
May 2002
and the slave unit would be mounted next to the HRV in the basement, also near a power outlet. A few days later, a parcel containing several Plinius modules as well as a nice assortment of RF and PIR detector modules landed on my doorstep. ® CIRCUIT CELLAR
The Plinius module is an FSK-modulated transceiver capable of sending data through power lines at rates up to 2400 bps. As shipped, these units use a 132.45-kHz carrier frequency, which falls within the CENELEC band used in Europe. Although the datasheet indicates that the carrier frequency is programmable via the SPI connections on the module, I was told that the necessary information for that task isn’t available to the end user. Plinius operates in Half-Duplex mode, which means it cannot transmit and receive simultaneously. Its direction is defined by the host microcontroller through the REQUEST TO SEND (RTS) pin. A CAR RIER DETECT signal is also provided by the module, which indicates the presence of a Plinius signal on the power line. (Note that both the RTS and CARRIER DETECT signals are actually negative logic signals; their names in the datasheet do not correctly reflect this fact.) The Plinius modules come in two flavors: an industrial version and a home version. As far as I can tell, the only difference between the two is that the industrial version uses a 24-V booster power supply puts out more power than the and 12-V-powered home version. Both models also require a regulated 5-V power supply capable of supplying 25 mA. I used the home version, which measures about 40 mm × 23 mm × 13 mm. Photo 2 is a close-up shot of the module. An 18-pin dual 0.1 header is all that’s needed to connect all of the signals, and the power line connections are placed as far away from the latter as possible, which makes a safe PCB layout much easier. The units I received are meant to be connected to 240-V lines, but also work fine on the 120-V lines found in North America. Apart from its central communica″
tion function, there are several useful features incorporated into this module. A power-on reset generator with a programmable threshold is provided and both 11.0592- and 5.5296-MHz clock signals are available. Unfortunately, the real-time clock needed in my project would not work using either of these frequencies. I was, www.circuitcellar.com
For complete rules and entry form
www.circuitcellar.com/PSoC2002 Get paid to learn about PSoC™ MCU The fastest growing MCU architecture • The highest level of integration • The next new thing in Embedded
Take your career to the next level. \64
\ 64
Win a share of
$15,000 in Cash Prizes!
Brought to you by:
The Cypress logo mark is a registered trademark of Cypress Semiconductor and Cypress MicroSystems, PSoC, and Programmable System-on-Chip are trademarks of Cypress Microsystems Inc. The Circuit Cellar name is a registered trademark of Circuit Cellar Inc.
tem via a center-tapped 240-V transformer. This means that there are two out-of-phase 120-V distribution lines (L1 and L2) provided that share a common neutral. In any home, some of the receptacles will be tapped off of one of these lines, and the rest will come from the other. The RF signal from Plinius modules (as well as X10 modules and such) will not easily cross over from L1 to L2. We have an electric heating system, the heating elements of which connect directly across L1 and L2.
ice routine can clear the UART’s receiver flag and data register, and start the polling process. If you intend to connect a Plinius modem directly to a PC’s COM port, then you’ll want to use communication driver routines that enable the UART’s receiver only when the carrier detect handshake line is true. If you don’t, the PC’s incoming data buffer will be constantly filled with these extraneous characters when the actual data is not being transmitted. I found that the sheer number and random-
however, able to use the last remain ing feature, the 2.5-V reference source, for the ’8535 microcontroller’s internal ADC reference. The Plinius modules contain an input pin labeled ZCROS, which stands for zero crossing. This signal is not required for normal operation, but the Plinius ASIC can be reprogrammed through its SPI port to use this signal to synchronize the start of data transmission with a zero crossing line. I can’t be definitive about the range of these modules. Power line modems are not like wireless links, the range
The signal sneak frombut L1 to L2Plinius through thesecan heater loads, this is more of an exception than the rule. I made sure that both my master and slave modules were fed from receptacles that shared the same power phase. This arrangement became somewhat of a nuisance as most of the receptacles in the house were on one phase, except the receptacle for the HRV, which happened to be on the other. Alternately, you can fit a signal coupler in your power entrance box to couple the RF signal from one phase to the other. These devices are commonly available for X10 systems. One example would be the passive CP000 available from HomeAutomationNet.com
ness of these extraneous enough to overcome any characters checking is that I might try to do in software (i.e., looking for a sync character). The other problem I had was in regard to the modem’s susceptibility to RF noise on its V CC line. This problem came up during preliminary testing when I used an Atmel AT90S2313 microcontroller to interface to the Plinius modem. The AT90S2313 turns out to be a strong little RF signal producer! I was unable to get the Plinius to transmit good data any time it was being powered by the same 5-V power supply as the AT90S2313. Several hundred millivolts of RF noise (at the second harmonic of the clock) were present on
of which is generally quoted as a maximum distance under ideal, line-ofsight conditions. The range of a power line modem is determined more by the type of loads connected to the same branch of the power line. These loads may inject RF noise onto the power line itself, which interferes with the modem’s carrier signal. During tests in my house in which I sent a constant small packet of known data once per second, I experienced only a few errors over several hours. I induced a few errors by starting up any of the large power tools in my workshop, but that was limited to the actual turn-on transient and did not persist while the tool was left run-
for about $30. I haven’t tried one of these devices, but the fact that X10 uses a 100-kHz carrier should allow it to work well with Plinius modems operating just a bit higher in frequency at 132.45 kHz. I must mention some problems that I ran into while incorporating these modems into my design. To start with, it’s important to monitor the carrier detect line before actually accepting characters coming in from the Plinius modem’s received data output because the modem will produce a constant stream of extraneous characters whenever there is no valid signal coming in from another transmitting Plinius modem. If you’re con-
the 5-V line whenever the AT90S2313 microcontroller was plugged in. No amount of filtering across the 5-V supply would reduce it sufficiently to allow the Plinius to work properly. This problem is not the fault of the Plinius modems. It took a while to uncover this problem though because I had used AT90S2313s with VHF RF modules successfully before, and had never actually used an oscilloscope on the VCC line or observed this RF interference before. The Atmel ’8535 microcontroller, which I used at both ends of the data link, does not generate this RF interference. Although not a problem, I should mention that the Plinius does not
ning. In mya home, there would not be more than 30-m distance between any two receptacles and Plinius modems work fine in that setting. However, I must emphasize that in North America, domestic power is provided from the distribution sys-
necting a Plinius modem microcontroller, your best bet istotoa operate its internal UART in a polled mode and use the CARRIER DETECT signal as an interrupt source. That way, when the CAR RIER DETECT signal is active, the associate d interrupt serv-
like to see its RTS line held (transmitting) for more than low 3 s. It will switch back to Receive mode if this occurs and stay in that mode until the RTS line is toggled high and then returned low. The goal behind this is to prevent a Plinius module
Photo 1—This split image shows the SC-600 sensor along with its built-in signal conditioning electronics.
16
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
from saturating or hogging the power line with an RF carrier, in the event that a runaway microcontroller program leaves the device in Transmit mode. This limitation did not affect my application in any way because my data packets are short.
The Plinius CARRIER DETECT signal will become active 4 ms after a carrier of minimum-acceptable amplitude is present at its receiver. I transmit a preamble of six 0AAh characters ahead of the actual data packet so the CARRIER DETECT signal is true just before the actual data packet starts. For anything other than a hardwired serial data link, a fixed packet structure with
THE DATA LINK The hardware layer of the data link is taken care
of by the Plinius modules synchronization and error mentioned earlier. They checking is an absolute Photo 2—This is a close-up view of the Plinius line modem module. The module will send and receive asynnecessity. I’m sending only could be much smaller except for the large line coupling capacitor seen just behind the 18-pin signal connector. chronous data from the a few byte-wide variables microcontroller’s UART (temperature, humidity, port at up to 2400 bps without any off-keyed wireless transmission link. runflag) and there are only two Plinius particular regard to data format. I’m sending a small data packet so I modules involved, but I decided to Because the Plinius uses FSK modusettled on a transmission rate of allow for the possibility of using addilation, you don’t have to worry about 1200 bps to improve reliability. This tional Plinius modules in the house formatting the data for roughly equal for future ideas. In my initial talks was the slowest standard rate the occurrences of ones and zeros in the microcontroller will produce using a with Vincenzo, he mentioned that he datastream as you would with an on4.19-MHz crystal. had tried the SNAP protocol with his Plinius devices. Like the Plinius modules themselves, the SNAP protocol is of European srcin, so I opted to keep everything in the same family, so to speak.
SNAP TO IT SNAP stands for Scalable Node Address Protocol, which was developed by High Tech Horizon (HTH) in Sweden. It is a free, open network protocol that, when scaled down to its simplest form, requires minimal MCU resources to implement. Although the protocol can be configured to handle up to 16.7 million node address, it can be scaled back to run a simple home network containing less than 255 nodes. The SNAP protocol can operate in a peer-topeer or a master-slave configuration and supports many forms of error checking or detection
Figure 3—I chose the AT90S8535 for both the master and slave modules. The ’8535 has enough flash memory to allow writing the program in BASIC, as well as 10-bit ADCs for reading the sensors. w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
schemes. SNAP was designed be media-independent, so it is to completely flexible with regard to data format and preamble specifications. And this protocol can operate in simplex, half, or full-duplex mode. Issue 142
May 2002 17
SNAP can be used freely by anyone for personal projects such as this one. Even if it is used commercially, there aren’t hassles. The only requirement is that the user register with HTH to get a free vendor ID number. The SNAP protocol is clearly defined on HTH’s web site. I won’t repeat all of the information, but I’ll show you the SNAP packet structure that I implemented to handle the simple communications that I needed for this project. A 6-byte (0AAh) preamble is sent
make is that the CRC byte is correct after the packet is fully received. The possibility exists that an incomplete packet may come in, so I constantly check for the presence of a true CARRIER DETECT signal during packet reception and abort the packet handling routine with an error flag set if the CARRIER DETECT signal disappears before the packet has been fully received. Although the data require-
followed an 8-byte as shown inby Figure 2. Forpacket my particular situation, I knew there would never be more than 255 nodes in my home, so I am never going to need anything other than 1-byte node addressing. That allows my SNAP driver to be compact. I merely check that the incoming packet comes from the correct source and is addressed to the correct destination. The only other check I
ments particular are modest,ofI this think it made data senselink to settle on a readily available packet standard rather than trying to roll my own.
Photo 3—Here’s a look at the master controller module with the top cover removed. The Plinius modem is mounted at the upper right corner of the PCB.
(in software) thatupon sets the mode depending the operational time of day. The decision whether to turn the HRV on or off is made by this unit’s microcontroller, based on the rules as THE MASTER CONTROLLER described earlier, as well as the values The master controller contains a of the inside/outside sensors . The keypad/LCD for the user interface, the outside sensor values are reported by inside temperature and humidity senthe slave module in response to a data sors, and a Plinius power line modem. request sent by the master via the This unit maintains the real time clock Plinius power line modem link. Photo 3 shows the unit with the cover (containing the LCD and keypad) removed. Figure 3 shows the complete diagram of the master unit. I picked the Atmel AT90S8535 device from the AVR family mainly because it had a built-in eight-channel, 10-bit ADC for the sensors as well as 8 KB of flash memory (almost all of which was needed to hold the compiled BASIC program). The device also contains 512 bytes of SRAM, plenty for this application, as well as 256 bytes of EEPROM. All operational parameters are stored in EEPROM so the unit’s parameters won’t have to be reprogrammed if the power goes out. The ’8535’s clock signal is provided by a 4.1934-MHz crystal, which
Figure 4—Take away the user interface and the slave module looks a lot like the master. A power supervisor chip is added for security because this unit is hidden away in the basement.
18
Issue 142
May 2002
CIRCUIT CELLAR®
was chosen because divides down nicely it when used by the real time clock software routine. The user interface consists of a 16-button matrix keypad connected to port C www.circuitcellar.com
and a 4 × 20 LCD, driven by six lines of ports B and D. A small piezo buzzer driven by port B4 alerts me if a power failure occurred (which requires user intervention to reset the clock). The Plinius power line modem is connected directly to the ’8535’s serial port. The Carrier Detect and RTS handshake lines are connected to ports D2 and D3, respectively. The inside sensors for temperature and humidity are connected to channels zero and one of the ’8535’s internal ADC. The LM34DZ has a voltage
The heartbeat LED is driven by port B1, and flashes briefly every time the Carrier Detect interrupt service routine executes. Because the master sends a data packet once per second, the LED will normally flash at this rate if everything is OK. Note that this LED will flash if the data packet has errors in it, so it’s not really a full test of the data link. Because this unit is hidden away in the basement, I decided to use a power supervisor chip to reset the controller if power glitches occur.
Writing the program in BASIC also has the advantage that it is much easier for you to modify my control algorithms to better suit your climate.
output that falls within the 2.5-V ADC range, but the SC-600 humidity sensor produces 3 V full-scale, so it is scaled down to 2.5 V by a calibration potentiometer. The ADC of the ’8535’s gets its 2.5-V reference from the Plinius module. The power supply is a conventional transformer-driven bridge rectifier followed by a three-terminal regulator. You can’t substitute a wall wart adapter because both L1 and neutral lines are needed to connect to the Plinius mains pins. Components R3 and R4 set the threshold for the power-on reset circuit within the Plinius module. Although I chose not to use the Plinius reset output to generate the ’8535 reset signal, the com-
The software also usestothe watchdog function of the AVR reset the device if the program should run away for any reason.
around the house. Brian Millier is an instrumentation engineer in the Chemistry Department of Dalhousie University in Halifax, Canada. He also runs Computer Interface Consultants. You man reach him at [email protected].
ponents mentioned are needed to provide a proper reset for the ASIC chip contained in the Plinius itself.
Figure 4 illustrates the wiring of the slave controller. If it looks a lot like the master controller, that’s because its circuitry is similar. The slave doesn’t require a user interface, so the keypad and LCD are out of the picture. In their place is the HRV control relay and the heartbeat LED. The same type of temperature and humidity sensors are used, but in this case they are placed outdoors in a small plastic box. My Lifebreath-brand HRV has an
important consideration here because interrupts are used for both the software real-time clock, and the Carrier Detect interrupt service routine. The fact that the compiler contains a built-in device programmer for AVR devices is icing on the cake. I described this compiler in more detail in my article “My fAVRorite Family of Micros” (Circuit Cellar 133). The program code for the master controller uses almost all of the 8192 bytes of available flash memory, precluding the use of less wellendowed members of the AVR family. On the other hand, the slave required only 1422 bytes. I’ll admit that I could have gotten away with a
external terminal strip to which remotely located humidistat mayabe connected. This is a common 24-V control circuit. The slave’s control relay contacts are wired to this terminal strip in order to turn the HRV’s fan on and off.
smaller microcontroller here. The pin AT90S4433 was available and 28certainly would have done the trick, but I didn’t think it was worthwhile to switch from the ’8535 device, which I keep on hand, just to save a few dollars.
THE SLAVE CONTROLLER
w w w .c ir c u it c e ll a r .c o m
FIRMWARE None of the code for either the master or slave modules had to be particularly fast. There’s always a fair bit of code involved in providing a userfriendly interface, which involves entering numerous parameters. Some floating-point operations were also needed so I chose to write the firmware for both modules in compiled BASIC, using the Bascom-AVR compiler from MCS Electronics. This compiler supports all of the AVR’s interrupts, which was an
® C IR C U ITC E L LA R
GASPING FOR AIR The controller is telling my HRV to pump in some fresh air as I sit at the computer writing this article. You may be happy with the control aspect of your home’s environmental control system, but that shouldn’t stop you from looking into the Plinius modules for other remote control applications I
SOFTWARE To download the source and object code for the master and slave controllers and the Plinius datasheets, go to ftp.circuitcellar.com/pub/ Circuit_Cellar/2002/142/. This and any additional information is also available on the author’s web site at is.dal.ca/~bmillier/index.htm.
SOURCES
AVR data books, assembler, and simulator Atmel Corp. www.atmel.com BASCOM-AVR Compiler/programmer MCS Electronics (Holland) www.mcselec.com Plinius power line modems Telecontrolli s.p.a. +39 2 5516417 www.telecontrolli.com Lextronic (01) 45-76-83-88 www.lextronic.fr
SC-600 Humidity Sensor Ohmic Instruments Co. (410) 820-5111 www.ohmicinstruments.com SNAP network protocol High Tech Horizon www.hth.com Issue 142
May 2002 19
FEATURE ARTICLE Claudio Lanconelli & Alberto Ricci Bitti
Tiny Planet—A One-Bit, Wireless I/O Port
o
Claudio and Alberto took a closer look at the connector on a cell phone and designed a circuit that would allow users to keep in touch with machinery and hardware anywhere in the world. Staying in touch with products can be just as easy as staying in touch with people.
20
Issue 142
May 2002
n December 12, 1901, scientist and Nobel Prize winner Guglielmo Marconi was able to transmit across the Atlantic ocean for the first time in history. One century later, wireless communications are ubiquitous. Anyone can pick
Additionally, you can use the device to relay the status of the input port, automatically sending a message every time the in put changes. To get input status at any time, the device can send back an SMS based on the status of the input as a response to a request message. SMS messages are simple and convenient; they can be entered, stored, and read directly on the cell phone itself. Incoming messages are completed with the time of reception and stored automatically in the mobile phone’s memory. By offered means by of one the various services net-of work operators, they can be converted to faxes, e-mails, and even voice calls spoken by a synthetic voice. As an additional benefit, the service is fairly priced because it doesn’t require precious real-time bandwidth. The potential applications are countless. You can use it to make an extended range remote control, operable from anywhere in the world. For industrial purposes, it can monitor if a machine is running or if some threshold is surpassed. The technical staff is alerted automatically and can remotely operate an immediate countermeasure. Commercial applications are numerous as well. All of the
up a cell phone and talk with a friend located on a different continent. Voice calls are only one of the options; the latest cell phones can send faxes, exchange text messages, e-mails, music, and even connect to the Internet. In other words, whatever the srcin of your information, if it can be reduced to small data packets it can be delivered to a mobile phone. This circuit connects to the serial port featured by many cellular phones. Its function is to provide an input and output port capable of being remotely controlled using another mobile. Control takes place by means of short message service (SMS). When the mobile phone receives a predefined text
components of a home automation system can be conveniently controlled and monitored from a cell phone. To enhance its wide applicability even further, the circuit is small and battery-operated.
message “Activate burglar alarm” or “Start (e.g., backup pump”), the circuit automatically recognizes it as a command and switches the output accordingly. Besides switching the port on or off, you can pulse it for a short period (e.g., “Reboot remote server”).
and serial RX TX. I would haveand connected it immediately to the PC COM port, but the connector on the mobile is too small to get a reliable contact without risk of damaging the phone. I, Alberto, decided to buy a ready-made data
CIRCUIT CELLAR®
INFORMATION GATHERING As an engineer, that little golden connector on the bottom of my cell phone always attracted me. After a little Internet browsing, I found the connector pinout of my Ericsson T10s. The signal names confirmed my expectations: audio input and output to connect an external hands-free, mute-control, flash memory-programming signal, battery, external power,
www.circuitcellar.com
cable, and in the meantime, continued searching for more information about the data protocols. One of the aspects of the Internet that I like most is its capability to seek information straight from the sources. I subscribed to the developer zone on Ericsson’s main web site, and after some unsuccessful navigation found an interesting message in the forum. This time I was surprised. To start with, similar to modems, cellular phones can accept AT commands (more precisely, an extension of the AT command set). Besides SMS management, the extension handles many functions, including mobile identification, address book management, signal strength level, call waiting and forwarding, error report, battery charge monitoring, ringing tones, volume, plus nonstandard commands introduced by manufacturers. But the real surprise was to discover that the standard rules that govern GSM cell phones (including the AT modem command set extension) derive from the European Telecommunication Institute (ETSI), which published them online. The rules applicable here are ETSI GSM 03.40 and ETSI GSM 04.11. I immediately downloaded the relevant standard and started deciphering it.
SERIAL COMMUNICATION Trial and error with the phone connected to the PC helps understanding the extended AT command set used by the cell phone. After setting
Figure 1—The only active parts of the circuit are the ATtiny2L and a transistor. A voltage regulator is unnecessary.
HyperTerminal to 9600 bps, no parity, 8 bits, and 1 stop bit (a lucky guess), I started typing in commands. Listing 1 states the commands and responses from the cell phone (in italic). Using the technique demonstrated in the first command, I selected the commands relevant to the application, manually simulating the intended algorithm. [1] I saved you thepain going straight to the conclusion. First, you tell the phone which memory to use for successive commands. This instructs
the fourth message, a one means it has been received and read. It is 27 bytes long and is in Proto col Description Unit (PDU) format. The PDU format is complex; it contains many subfields packed together using different encoding. Among other things, it also holds service center numbers, srcin numbers, nation codes, a time stamp, and a descriptor of the character set used. For more detailed information, see the “SMS Data Dissected” sidebar. For
the mobile unit to use internal memory “ME” in place of the “SM” memory from the subscriber identity module (SIM) as default memory. Next, a message can be read from that memory specifying its number. In
our purposes, it is sufficient to know that the text bytes are on the rightmost position. Storing a signature from the last six bytes of the message, the device will be able to recognize incoming messages. At this point, you are able to download messages from the mobile phone. The next command frees precious mobile phone memory, deleting the seventh message. The last step is to send an SMS message. This proved to be the more difficult part, because I had to find a workaround in order to avoid building a PDU from scratch. The trick is to ask the user to send the message manually, during the first setup. In this way, the mobile
Listing 1—The microcontroller issues these commands. When connected to a PC through a data cable, a GSM phone resembles an ordinary modem accepting specialized AT commands. AT OK AT+CPMS="ME","ME" +CPMS: 7,15,7,15,7,15 OK AT+CMGR=4 +CMGR: 1,,27 0791934329005000040C9193433728501400001060314104350809D02A735A043 DAB54 OK
unit complete theitPDU all of thewill required fields, will with pack the text and numbers, and will store them in the sent messages memory. At a later time, a simple command is all that is required to resend the message from memory.
AT+CMGD=7 OK AT+CMSS=1 +CMSS :96 OK
w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 21
SMS DATA DISSECTED
S u b f ie l d N a m e
De f in it i o n
Le n g t h
SCA Service Center Network operator’s service center number. Not required by all 1 or 2 to 12 Connecting to a mobile phone Address phones. A hex value of 00 or 01-80 means “unknown”: the bytes and issuing a few AT commands phone will use the default number stored in its settings is straightforward. However, ID TPDU type identifier SMS-DELIVER or SMS-SUBMIT identifiers and flags (e.g., request 1 byte of a status report or presence of VP field) exchanging SMS data requires MR Message Reference Progressive number (0 to 255) 1 byte familiarity with the composiOA or Originating or Sender’s or destination phone number. Different number encoding 2 to 12 DA Destination Address from that of SCA is used. bytes tion of the Protocol Data Unit PID Protocol Identifier Nature of data transported (fax, voice, etc.), used by the service 1 byte (PDU), which is required by or center for a better routing given in response to most SMSDCS Data Coding Format of the data transported (7 or 8 bits, alphabet, etc.) and where 1 byte Scheme to store it (phone memory, SIM module, or for immediate display) specific AT commands. You SCTS Service Centre Year, month, day, hour, minute, seconds and time difference with 7 bytes have to be prepared for minor Time Stamp respect to GMT VP Validity Period How long the network operator service center will hold the message 0, 1, or 7 changes depending on the manifundelivered(A7=24hours) bytes ufacturer’s implementation of UDL User Data Length Length of data prior to encoding (e.g., 11 7-bit characters fit into 10 bytes) 1 byte the standards. UD User Data The message data, “HALLO WORLD” 0-140 bytes A PDU looks like a long Table s1—You’ll need the definitions of the subfields. hexadecimal string, representing the number of the network operator’s SMS central service center address (SCA). fields in addition to the message text. Most data is The SCA is chained to the packet used in the SMS packed to save bits. transport layer (often referred as Transport Protocol A nice way to get a copy of both sent and received Data Unit, or TPDU). The latter includes many subPDUs is to send yourself a simple SMS, connect the 01
80
SCA
11 00 0A ID MR
81
43 37
28
90
DA
55
00 00 A7 0B C8 20 PID DCS VP UDL
93
F9
04
5D
9F
04 5D 9F
52
26
11
User data
SMS—Submit TPDU PDU Returned by the AT+CMGL command
07
91
93
43
29
SCA
00
50 90
04
0C
91
ID
93
43
37 OA
28 90
55
00
00
20
10
PID DCS
31
61
55
61
SCTS
04
0B UDL
C8 20
93
F9 04 5D 9F 52 26 11 UD
SMS—Deliver TPDU PDU Returned by the AT+CMGL command
Figure s1—SMS data is stored in phone memory along with the information required by the GSM transport layer. The resulting record is referred to as PDU.
Besides being simple for the microcontroller, this technique is simple for you too. I like to call it “set up by example.” To set up the system for which text to send, phone numbers to use, and commands to recognize, just send the information once manually (as usual, using the mobile unit), then press the Configuration button to make the machine learn them automatically. Another advantage of using only four among the many AT commands available is an improved compatibility. Manufacturers introduced minor differences while implementing the standards. Although it has been tested with the Ericsson T10s only, the
cell phone, he agreed that the subject was worth a try. We decided to use the smallest processor and as few external parts as possible. The circuit makes the most of a ATtiny12L and a transistor, and is remarkably simple (see Figure1). Atmel’s ATtiny-12L is an 8-pin microcontroller with 512 words of flash memory code, 32 registers, and 64 bytes of EEPROM. Three AA cells, for a total of 4.5 V, power the circuit. The ATtiny12L has an internal brownout, therefore, it can run safely without requiring a voltage regulator. Apart from VCC and GND, all of the eight pins are available thanks to an internal oscillator running at a respectable speed
The serial stream enters the chip through PB4. Diode Z1 and R4 cut the negative fraction and limit input swing. Conversely, the output stream from PB2 drives transistor Q1. On the collector, a negative voltage is derived from the input stream. In this way, the data output to the cell phone is a true bipolar signal. The output stream also is used to drive an LED; it is connected straight to PB2 and flashes at every transmission. The PB0 pin is connected to a jumper that tells the software to disable automatic notification of input changes. It is pulled up internally, and resistor R6 is used to resolve conflicts during in-
unmodified circuitdevice should work with any other mobile that supports the same command subset.
of 1serial MHz.communications With 1 MIPS at our the can disposal, be handled entirely in the software. Precise timing is not sacrificed by means of an adaptive algorithm that adapts serial port speed to the internal clock variations as the battery discharges.
system programming. R6with can be ted if the ISP takes place theomitjumper removed. The pins are assigned to functions that don’t impede ISP. The input goes to pin PB3, which is pulled up internally; the output comes from pin PB1. Both have a small protec-
CIRCUIT DIAGRAM When I told Claudio about how easy it would be to control things using a
22
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
mobile unit to the PC, and then read the First byte Second byte Third byte Fourth byte Fifth byte Sixth byte Seventh byte Eighth byte (length) (format) message from its memory using the AT+ 5 0 F 9 9 1 9 3 4 3 2 9 0 0 0 7 CMGL command. The following example shows the PDU for the message “HALLO Figure s2—The digits are stored in nibbles. The format differs for SCA and DA/OA numbers. WORLD,” sent from the number ++39 347 3820955 at 4:55:15 p.m. on January 13, If the length is odd, the unused nibble (semi-octet in 2002. The mobile phone used was an Ericsson T10s and ETSI language) is padded with “$F”. Some mobile the service center number was ++39 349 2000509 (see phones don’t require the SCA or accept 00 or 01-80 as Figure s1). The first packet is the SMS-SUBMIT, used for valid values for the service center address. In that case, sending a message; the second isthe SMS-DELIVER packthe phone will use the default service center number. et for receiving. The subfields are detailed in Table s1. An SMS message, according to ETSI specification, can Phone numbers start with the length of the number, be up to 140 bytes long (octets in ETSI terminology). intended as field length in bytes for the service center (SCA) and digits for the remaining numbers (DA, OA). The second byte specifies the numbering plan: 80 is unknown, 81 is a national number, 91 is First byte an international numS0 G6 G5 G4 G3 G2 G1 G0 1 1 0 0 0 1 1 1 ber. Then follow the Second byte digits, swapped in pairs M1 M0 S6 S5 S4 S3 S2 S1 and each occupying a 0 1 1 0 1 0 0 1 nibble. This is how the Third byte phone number ++39 349 zp zp zp M6 M5 M4 M3 M2 200059 is encoded. See 0 0 0 1 0 0 1 1 how the numbers are stored in Figure s2. Figure s3—To save space, text (7-bit)
The usual GSM alphabet requires only ter (septet), allowing for the packing of 7 upbits to: per charac-
Let’s go over an example of how 7-bit data is packed between successive bytes. The 7-bit binary encoding of the string GSM is G = 1000111, S = 1010011, and M = 1001101. Let G0 be bit 0 of letter G, G1 be bit 1 of letter G, and so on. Then, the PDU will pack data as is shown in Figure s3. Note how the last three spare places are padded with zeroes.
data is packed among successive bytes.
w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 23
tion resistor connected in series. The RESET pin is pulled up with an external resistor, because the internal pull-up has a high value. Conversely, lowering input impedance removes the risk of picking up noise emanating from the intense electromagnetic field of the mobile phone.
sage, it compares its signature against all of the stored versions. If one of the signatures matches, the relevant command (i.e., pulse output, set output, clear output, or sendback input status) is executed. Using signatures instead of the full text allows the system to Photo 1a—How do you mount a 50-mils part on a 100-mils breadboard? save EEPROM, and makes mesProgramming is done in-system via the strip socket. b—After you’ve finHOW THE CODE WORKS sages of arbitrary length possiished programming the unit, you can place it in a small plastic box. The code was written in ble. The system is safe, as well, assembly on the AVR Studio assemdelete all of the messages from the requiring an exact match of the last bler. The algorithm at the heart of the mobile phone prior to setup). six characters to accept a command. a)
Tiny project is simple. setup,Planet the four messages used During as commands and the two messages used as responses are stored in the phone memory, where they can be read back by the controller issuing the appropriate extended AT command. For every command message, the setup routine extracts a unique 6-byte signature from the last message bytes and stores it in EEPROM. The system expects that every message be stored in a fixed position, as shown in Figure 2 (to ensure this,
24
Issue 142
May 2002
b)
Outgoing messages in positions one and two, which are indicate a low input and high input, respectively. Incoming command messages are in position three (request to report the input status), four (command to pulse output), five (command to set output), and six (command to clear output). Position seven is kept free for incoming command messages. During operation, the device repeatedly checks the message memory in position seven for the presence of a new SMS. When it finds a new mes-
CIRCUIT CELLAR®
The Input Status command well asSend a level change of the input as pin when the autosend jumper is open, causes a message to be sent out. It is neither necessary to recreate the outgoing message from scratch nor store it in EEPROM. It’s sufficient to resend the first or second message from the mobile phone’s message storage, according to the status of the input pin. At the end of the cycl e, the mes sage is cleared from memory and the system is ready for a new command.
www.circuitcellar.com
MBasic Software Whether your just learning or aprofessional, Programming PICmicro® MCUs has never been easier ! MBasic is much simpler than C or Assembly. MBasic creates a one click solution that allows you to experiment and test code changes on-the-fly! Bring your projects to life quicker and easier with MBasic for PICmicro® MCUs !
ICD - In Circuit Debugger Stop wasting time strategically planting debug statements throughout your entire program. MBasic includes a built-in ICD (In Circuit Debugger ) FREE. Watch variables, SFRs and RAM values as each line executes. MBasic’s ICD is so easy to use, even the first time user can have it up and running in minutes !
MBasic and Assembly Language Seasoned Assembly programmer or just learning MBasic ? allows an easy mix ofBASIC and Assembly . Instead ofspending weeks writing your program, have it done in days !
Syntax Learn to Program PIC Microcontrollers in easy to use BASIC
A complete set of easy to use commands ! Serin, Serout, If..Then..Elseif..Else..Endif, Do..While, While..Wend, OWin, OWout, ADin, Pulsin, Pulsout, PWM, Xin, Xout and more! Plus easy acces to all PICmicro built-in hardware peripherals.
Math
Download MBasic Lite FREE !
MBasic is the only BASIC compiler that supports 32 bit floating point and integer math. This includes 32 x 32 bit divides and multiplies.
Try before you buy !
MBasic Pro Only $229.95 Includes Printed Manual and CD-ROM with MBasic.
® Optional ISP-PRO Items Available
- Plastic Enclosure - 40 Pin Zif Adapter - Universal Adapter
ISP-PRO Programmer
Solderless Development
Development Kit
- Uses PC Serial port (USB w/ adapter) - Very Simple to use - Free Software updates - Complete with Windows IDE! - Easy in-circuit programming - Supports PIC, Scenix, I2C and more! - Firmware upgrades Free! - RJ-11 / 10 Pin Header - Includes RJ-11 Cable
- Completely Assembled Board - In Circuit Programmable (ISP) - Solderless Bread Board - Built in RS232 (w/ Max232) - Built in Power Connector - Removable Oscillator - Documentation - Auto Disconnect for RB3, RB6, & RB7 - Available in several models
Includes: - MBasicPro Compiler - 2840Development Board - ISP-PRO Programmer - PIC16F876-20 - 10MhzResonator - SerialCable - PowerSupply - CD-ROM andManual
Starting At $59.95
Starting At $159.95
Only $59.95
Join our on-line PIC forums, information and help FREE!!! www.basicmicro.com
Microcontro
llers Made Easy™
MBASIC is a registered trademark of Basic Micro Inc. PICmicro is a registered trademark of Microchip Inc.
RUNNING ON BATTERIES The software implements lowpower techniques, which extend battery life to more than a year of continued use using AA cells. The ATtiny12 is perfectly suited to run on batteries. Most of the time the controller is in Sleep mode with only the watchdog on. In this condition, power consumption is only 200 µA. Control is resumed when the watchdog expires (a couple of seconds) or when the input pin changes, thanks to the ATtiny12’s capability of wak-
of the cell phone. Packed together, the box and phone can be placed practically everywhere (see Photo 2).
USER INTERFACE
Photo 2—The prototype is connected to an Ericsson
The device is simple to use. You can customize the text messages for both commands and readouts (see Photo 3). Plain text messages like “Activate burglar alarm” work well. Just make sure that the at least one out of the last six characters is different for every command. To prepare your system for setup,
ingWhen up onrunning, a pin change. the required current is about 1 mA for a period as short as 20 ms. Every 10 short breaks (about 20 s), the microcontroller starts a longer dialog with the mobile unit, requiring an extra 840 ms at 1 to 2 mA (shown on the left in Figure 3). The circuit runs on the internal oscillator, so the clock frequency varies over the lifetime of the batteries. The serial port routines implement an auto-baud algorithm that adapts its timing as clock changes. To save another nibble of energy, the calibration value is stored in EEPROM and the calibration is repeated only when needed. Last but not least, the circuit must
T10spackage GSM cellcan phone. Packaged together, the phone and be placed practically anywhere.
The circuit is made of a small number of parts, so we skipped the preparation of a PCB and replaced it with a breadboard. All of the components are through-hole except the ATtiny12, which is a surface mount device. But who’s afraid of SMD? Just solder a row of 50-mils pin strip to each side of the IC. In order to fit the 100-mils spaced breadboard, gently bend the legs of the spider (See Photo 1). Fortunately the ATtiny can be programmed in-system, so it doesn’t need to be removed. Fitting the remaining parts was a breeze. And, the finished board looks
first mobile phone anda then switch connectonitthe to Tiny Planet using suitable data cable. This is the slave phone, to differentiate it from the master phone, used to issue commands. To set up a new set of messages, send them in the usual way using the cell phones for editing. Use the following sequence of tasks. First, begin from the slave mobile: delete all of the messages currently in memory, send the message for the input low condition (e.g., “The input is low”) to the master, and then send the message for the input high condition to the master. These messages must be sent even if you aren’t going to use the input port feature of the Tiny Planet. Next, it’s time to move to the mas-
behave correctly when still connected to a discharged battery. The prototype passed the test brilliantly: the internal brownout halted the controller as expected.
spacious and clean. The circuit and the batteries are enclosed in a small plastic box. On one end of the box, we cut the holes for the Configuration button, LED, and connector for the input and output (actually a four-pole RJ-45). You may wish to replace the autosend jumper with a panel switch and place it on the front panel. We found this unnecessary. On the opposite end of the box, we cut the hole for the D-type connector for the serial port. After you place all of the components and double check the board for errors, you may start programming. We used
ter mobile phone, which you use to issue commands. Issue the following commands in the order given. First, send the message for requesting the input status (e.g., “What is the input status?”) to the slave. Second, send the message for pulsing the output (e.g., “Pulse output”) to the slave. Third, send the message for clearing the output (e.g., “Switch output off”) to the slave. Fourth, send the message for setting the output (e.g., “Switch output on”) to the slave. Again, all of the messages must be sent even if you aren’t planning to use a specified command. When all six messages are received, press the Config uration button. The
BUILDING THE PROTOTYPE
Photo 3—One of the best features of this project is that you can customize text messages.
26
Issue 142
May 2002
the excellent PonyProg software written by Claudio. And, we powered the board with 5 V from a bench supply. The finished prototype is compact and professional looking. The box is about the size CIRCUIT CELLAR®
LED will is complete. That’s all flash thereuntil is to setup it! If your application doesn’t require automatic notification of the input changes, remember to close the autosend jumper. When the system is running, the LED flashes once every 20 to 25 s. www.circuitcellar.com
Making designs as simple as possible improves every aspect #6: Command: set output Signature: command = on #5: Command: clear output Signature: command = off of a product. The #4: Command: pulse output Signature: command = pulse result costs less, is eas#3: Command: request input status Signature: command = request ier to manufacture, has #2: Outgoing message when input = 1 a smaller size (even in #1: Outgoing message when input = 0 its actual handcrafted Figure 2—To compare variable length messages without RAM, messages form!) and costs less to are reduced to signatures. To check if a new SMS is valid, its signature is package and ship. A compared against the authorized set. The 6-byte signatures for each of the lean bill of materials is four commands are stored in EEPROM. also the best insurance LESS IS MORE from parts shortages. All of these I like clean designs with great poten- aspects contribute to increasing both #8: Free
#7: Incoming messages go here
tial because of (not despite) theirissimplicity. The Tiny Planet project a simple, flexible, portable solution that’s useful for a wide range of applications. It doesn’t use a voltage regulator and makes profitable use of every feature of its components, including EEPROM, brownout, internal oscillator, watchdog, wake up on pin change, in-system programming, sleep modes. The code is dense, including power management and an adaptive data generator in just 417 out of the 512 words available. There is still enough space for adding new features or to modify the behavior to suit your personal taste. For example, you may want to direct the same alarm to three different phone numbers instead of one.
profitability and added The user interface wevalue. developed is remarkable as well. Most of the work is carried on the mobile phone in a common way, so a push button and single-page user manual is all that you need to run it. Compare this to a PC running the international software required to set up most industrial GSM modems. The characteristic I like most is that this little, inexpensive circuit allows anyone to start experimenting with a mobile phone, discovering a dynamic world that opens new, exciting, and unparalleled possibilities. A world discovered 100 years ago by Marconi’s invention, that ever since has made our planet very, very tiny. I
Claudio Lanconelli is the author of PonyProg, a powerful programmer for several microcontrollers and serial EEPROMs. He has several years of experience designing hardware and software for embedded systems. Some of his interests include home automation, Linux, and networking. You may reach him at lancos@ libero.it or visit his web site at www.lancos.com. Alberto Ricci Bitti holds a degree in Computer Science from University of Milan. He has 10 years of experience designing and writing software for embedded systems. In his free time, he enjoys competing in design contests, and has won several prizes. Currently he is a designer for Eptar, an industrial controllers and instrumentation firm. You may visit his web page at www.riccibitti.com or contact him at [email protected].
SOFTWARE To download the code, go to ftp. circuitcellar.com/pub/Circuit_ Cellar/2002/142/.
REFERENCE [1] Ericsson Enterprise, “T28 AT Command Online Reference,” rev. R1A.
RESOURCES European Telecommunications Standards Institute www.etsi.org Compatibility table for various phones gatling.ikk.sztaki.hu/~kissg/gsm/at +c.html PonyProg Free Programming Software www.lancos.com
SOURCES ATtiny12L Microcontroller Atmel Corp. (408) 441-0311 www.atmel.com T10s Ericsson Enterprise www.ericsson.com/mobilityworld/
Figure 3—The prototype can run on three AA cells for more than one year. w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 27
FEATURE ARTICLE George Novacek
Working with EMC
o
Teamwork involves give and take. However, when it comes to EMI, every circuit wants to give, but none of them want to take. George explains some differences between magnetic and electric emissions and how your next project can be designed to handle both.
28
Issue 142
May 2002
ne of my favorite engineering topics to discuss is electromagnetic compatibility (EMC). In past articles, I’ve talked about the various aspects and explained how understanding EMC will affect your design decisions. In this
per meter). Knowing the operating impedances, you can convert the current per meter into voltage per meter for consistency. That’s what I’ll cover in this article. Typically, effects of a 0.3 A/m hfield created by a transformer during a bulk injection testing equates to 200V/m e-field. Rarely are you faced with a pure electric or magnetic field. The magnetic component usually prevails in the low frequency range whereas the electric component dominates in the high frequency range. To design test equipment for compliance with requirements, interference in frequencies from 10 kHz up to about 400 MHz is injected into the cables (bulk injection) through a current transformer while electrical fields from 100 kHz to as high as 40 GHz are radiated by an assortment of antennas. [1] Understanding that there are two different fields, magnetic and electric, is critical because different methods of protection are needed for each field. For example, wire shielding is electrostatic, and has little effect in magnetic fields. For some protection you can reduce interference by twisting the wires. Keep in mind that twisting the wires helps with low-frequency magnetic and electric fields, but starts to
article I would like to look at EMC in a more practical way and discuss how you can bring it under control. Every electronic circuit is not only susceptible to electromagnetic interference (EMI), but is also a source of unwanted emissions. These excess emissions can interfere with other equipment. So, when considering EMC, you have to consider both the susceptibility to and the emissions of interference signals at the same time. On the up side, many of these interference signals are well outside the operating frequency bandwidth of equipment. And if you design circuits that are immune to interference, which is usually your primary con-
fail when the wave length of high-frequency electric fields approaches the pitch of the twist.
cern,care the unwanted emissions take of themselves, fallingoften well below permitted levels. Electromagnetic emissions comprise an electric field (e-field, expressed in volts per meter) and a magnetic field (h-field, usually expressed in amperes
quently exposed to high intensity fields (such as those emitted from radar antennas) must be steady under all circumstances. Opinions about how much interference is encountered in real life have been constantly changing as new evidence and test
CIRCUIT CELLAR®
HOW MUCH PROTECTION? The maximum emission levels are prescribed by legislation and you’re only option is to comply. But how much immunity to interference do we realistically need? What is the threat level we should expect? First of all, the level of protection depends on the criticality and the operating environment of the equipment. Susceptibility to interference in an entertainment appliance may be little more than a nuisance, but an aircraft fly-by-wire system that’s fre-
www.circuitcellar.com
results come to light. To the credit of the aerospace industry, only a handful of malfunctions evidently caused by EMI have been recorded; they date back to the times when a 1 V/m immunity was considered adequate. For years, 200 V/m was the maximum threat level required by military standards (MIL-STD-461/462), although other military documents tend to suggest that some operational environments significantly exceed this level of field strength. [2] So what was so magical about 200 V/m? Where did
work the other way around and sufficiently attenuate the interference internally generated. For starters, let’s assume our equipment will be exposed to a 2000 V/m efield in the frequency range of 400MHz to 40 GHz. What are the undesired effects of such exposure? The first effect is the misinterpretations of logic levels in digital devices (microprocessors, memory, or logic circuits). This can happen when the interfering voltage is about 0.4 V. The second effect is that when it
0.4 V. Such a conductor can be anything from a 100′ wire run to a component lead that is a fraction of an inch long. Figure 1 shows the voltage induced in a conductor in free air. On a 1-m length of wire placed in the 2000 V/m e-field, there will be 2000 V induced above 150 MHz. This frequency corresponds to the half wavelength represented by the length of the wire. Even if a conductor run, such as a PCB trace, was only 10 cm or 0.4″ long, the induced voltage at 150 MHz would still be a serious
the value come TheU.S. unofficial story is that for from? years the ANSI C95.1 standard was used to establish the maximum RF radiation hazard level for personnel. Therefore, it was assumed that a vehicle would not be driven in an environment exceeding the field intensity considered unsafe for humans. In free space, this e-field intensity happens to equal 196 V/m. There was also a practical consideration for military and aircraft equipment manufacturers to settle at 200 V/m. EMC testing is expensive and even now generating electric fields in excess of 200 V/m is no easy task. Over the years, the widely accepted threat profile has changed. For most avionic equipment today, the maxi-
comes analog devices, limitations most control systemstohave bandwidth of just a few kilohertz. Thus, the RF signal by itself will rarely affect the system. However, at 0.4 V, bipolar junctions begin to conduct and enter the non-linear operating region. After the PN junction voltage has been exceeded, it may start acting as a mixer or an amplitude demodulator. The resulting parasitic signals often fall within the operating bandwidth and the system fails. Using unipolar devices such as MOSFETs (which don’t exhibit the nonlinearity of the bipolar junctions) can go a long way toward taming the EMI. To cause functional upsets, the interfering field must induce voltage
200 And, taking it down to 1 cm or 0.4″,V.you still have 20 V to contend with. Such voltages are certain to cook any electronic component exposed to them. If you accept the 0.4 V as the maximum voltage tolerable, you have to reduce the interference by:
mum interference no longer exceeds 100 V/m at frequencies up to 200 MHz. That’s the good news. However, the threat level increases significantly above 500 MHz and never comes back down. How much does the EMI field strength increase? The increase in strength depends on the criticality and potential exposure of the equipment, but a requirement for several thousands volts per meter of average field strength is not unheard of. For modulated fields, you may have to deal with a 20,000-V/m peak.
or current into the conductor that is connected to a device input, which results in a voltage greater than about
INTERFERENCE REDUCTION
DEFINING THE PROBLEM Generating an accurate mathematical model for EMC analysis is next to impossible, the best solving EMIso issues is toapproach consider to the worst case scenario. Often you will see that the potential interference levels are so high, you can safely assume that by providing adequate immunity from them, the protection will also w w w .c ir c u it c e ll a r .c o m
What can you do? How do you drop the interference by 74 dB? There are several options, so let’s take a closer look at them.
The most obvious area to explore is moving the conductors from free air
Induced 1V in 1V/m e-field 20
0
] B [d e ri w n i d e c u d in e g a lt o V
–20
–40
–60
–80
–100
–120 1.E+01 0.1m
1.E+02 1m
1.E+03 10m
100m
1.E+04
1.E+05
1.E+06
1.E+07
Frequency [10 kHz to 10 GHz]
Figure 1—Use this graph to determine an interference voltage induced on a wire of given length in free air from 10 kHz to 10 GHz. Because it is standardized for 1 V/m, other field strengths will convert directly to their respective voltages. The effects of different wire lengths can be calculated by establishing their half wavelength frequency, from which to lower frequencies the signal drops at –20 dB/decade. ® C IR C U ITC E L LA R
Issue 142
May 2002 29
to the proximity of ground. For example, wire harnesses are usually run in troughs or close to the ground body, such as the aircraft fuselage. The multilayer PCBs should have ground planes. Up to –60-dB attenuation can be achieved by running the conductor 1.4 mm above the ground. That’s roughly 0.060″, the typical thickness of a PCB base material. This arrangement reduces the interference voltage induced in the PCB trace by a factor of 1000, or –60 dB. Interconnect cables are usually several feet Tests long and farther from the ground. are typically performed with harnesses and cables 15 mm (0.6″) above the ground plane, providing about –46 dB, which is 200× attenuation as compared to free air. Thus you can reduce the hypothetical interference voltage from 2000 V to 10 V. This discussion assumes that you understand and provide adequate grounding and bonding. Failing that, your guess as to how the system will react to EMI is as good as mine. For more information, please refer to my previous articles. [1, 3] Sometimes further attenuation can be obtained by taking credit for the shielding effect of the location where the system is placed (such as the aircraft fuselage). Although there used to be a tendency to expect about –20-dB attenuation caused by the effects of a vehicle body, it is generally not a good idea to rely on it. Recent studies have shown that at microwave frequencies, such attenuation degrades. At some
B
A
2 dB
0 dB Reference D
C
E
F
6 twists per foot 49 dB G
57 dB H
0
–20
] B d [ n io t a u n e tt A
–100
–120 1.E+01
Issue 142
1.E + 03 Dual Braid
1.E + 04
1.E + 05
1.E + 06
Frequency [kHz]
Figure 2—Shielding effectiveness of a wire is not constant. This diagram shows the results of an actual measurement from 10 kHz to 1 GHz on a high-quality aircraft harness with one and two shielding braids used.
frequencies and locations, resonance can, in fact, cause an amplitude boost of up to 20 dB. In summary, you can reasonably expect –46 dB attenuation of EMI simply by good multilayer PCB layout and the cable’s proximity to ground. This leaves you approximately –28 dB short of the necessary 0.4 V. And keep in mind, it’s good to have an extra 12 dB as a safety margin. So ,where do you get the additional –40 dB?
The solution is to use a doublebraided cable, the attenuation of which is shown by the dark blue trace. Its attenuation is also affected by the resonance, where it deteriorates to –55 dB. Overall, you can rely on a minimum of –60 dB effectiveness. Needless to say, double-braided wires are expensive and heavy, but if you need to work in the high intensity fields, that’s the price you have to pay. It’s absolutely imperative that immunity against magnetic fields be
WIRE SHIELDING
taken into consideration as well. Figure 3 shows the results of a study of different interfaces, published by Boeing some years ago. Case A is the baseline. You can see that the standard braided shielding provides no attenuation to a magnetic field. Case B is an example of a typical mistake made when an unbalanced pair is twisted. Because the return wire is grounded at both ends, the current returns through the ground. The loop area is the wire to ground and no area reduction is achieved by twisting of the two conductors. Case E is a coax cable working with a balanced load. In this case, the loop area is determined by the mechanical
Shielding provides only a partial answer because, contrary to the popular belief, shielding effectiveness is far from constant. First, Figure 2 shows the results of measurements performed on a high-quality aircraft harnesses. As you can see, single-shield attenuation above 1 MHz is highly inadequate. The area between 10 MHz and 100 MHz frequencies is greatly affected by the cable 6 dB length. In this particular situation a resonance at cable length equal to λ/2 is obvious, with shielding effec64 dB tiveness deteriorating down
I
71 dB
May 2002
1.E+02 Single Braid
79 dB
Figure 3—There are many ways to interconnect system components. But, when the interference comes from a magnetic field, shielding is useless. Twisted-wire pairs are the best solution.
30
–60
–80
18 twists per foot 64 dB
–40
to aand measly –15 dB 60 70 MHz. At between higher frequencies, especially microwaves, where you usually encounter strong electric fields, the attenuation barely hovers around –20 dB. CIRCUIT CELLAR®
offset between wire and metric center ofthe theinner shield (i.e., bygeothe imperfections of the coax). Imperfections are rare in quality cables. Cases F, G, and H illustrate how ineffectual the braided shield is in protecting against magnetic field. www.circuitcellar.com
make sure that should the shielding lose its effectiveness as a result of corrosion, mechanical damage, or any other reason, exposure to a high-intensity field will cause a safe shut down of the system and no permanent damage. To assure that, systems are often high-intensity radiated field (HIRF) tested with shielding degraded or completely removed.
degraded by ventilation holes, seams, drainage holes, and such. This degradation becomes critical at microwave frequencies. For example, at 1.2 GHz the ARINC connector with a 9 ″ perimeter offers 0 dB, and at 120 MHz a mere –20 dB of blockage of external signals. Ventilation holes of 0.1″ diameter degrade shielding of a 6-GHz interference voltage to only –20 dB. To achieve the desired –60-dB attenuation you have to EMI-seal the box, make up for some deficiencies by lowpass filtering of I/O lines, use a dual-
With the cable shielding correctly designed and working, the expected –60-dB attenuation will bring the interfering 10-V signal to 10 mV, which is well below the 0.4-V limit.
cavity or that all the the boxdesign, requires theabove. cable Sealing shielding become an extension of the box. That means proper connector back shell termination of the shielding, dual-braided, twisted pairs cables, foil shields, and EMI gaskets in all seams. And, as I’ve already mentioned, proper ground bonding and avoidance of ground loops is an important part of the overall system wiring design.
Photo 1—A dual-cavity box design provides immunity to the most adverse foundremoved on aircraft. the box within the box concept. environment The lid has been fromNotice the clean cavity.
Case I shows the improvement gained by tighter twisting of the wires. One often overlooked design aspect needs to be mentioned here. What happens if the shield fails? Even if it’s just one braid on a double-braided cable? What happens if the harness moves away from the ground plane? These situations are difficult to detect and consequently, such failures could lay dormant for a long time. You must
CABINET SHIELDING Just as wire shielding will reduce interference voltage induced in the wires, so a proper cabinet will shield the internal electronics from the EMI threat. Again, –60-dB attenuation should be expected, but this is often
LET’S BE PRACTICAL Unless you’re involved in the design of safety-critical systems, it’s unlikely that your system will ever encounter e-fields in excess of a few volts per meter. Most industrial requirements do not exceed 20 V/m across the entire spectrum. You’ve already seen that by employing good multilayer PCB layout practice and routing the interconnect cables close to ground you can count on –46-dB attenuation. With 0.4 V as the maximum allowed interference voltage, you should be able to design a system using only single-shielded interconnect cables, low pass I/O filters, and a nonmetallic cabinet with immunity up to about 100 V/m. With such a design, the unwanted emissions can still come back to bite you, especially if the PCB contains a fast microprocessor, switching power supplies, communications links, and such. Depending on the certification levelberequirements, can quickly fixedsuch withsituations a conductive coat on the plastic enclosure, a local shield over the offending component, a ferrite bead on the cable, or a metal cabinet. Unless your circuits radiate a lot of energy in UHF and
32
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
microwave bands, even a layer of chicken wire will do wonders. For demanding applications requiring immunity in excess of 200 V/m and especially tough immunity and emission measures (above 500 MHz), the cabinet design becomes critical. Although you can solve this problem using a sealed design, it’s easier said than done. With the need for lightning and ESD protection, ventilation and breathing holes or even displays, switches and connectors, cabinet sealing becomes too onerous. The safe
No less important is the fact that e-fields generated inside the clean cavity cannot radiate into the dirty cavity and can only propagate through conduction. With the LC pi filters in the way, e-fields will be well below the permitted levels by the time they get outside.
assumption is that above inside 1 GHz,the you must consider the e-field box to be the same as outside. The solution is a dual cavity design with low-pass feedthrough filters. Such a design is shown in Photo 1. As you can see, it’s a box within a box.The outer box, also called the dirty cavity, contains connectors, transient suppressors for lightning and ESD protection, and low pass LC filters whichthen feed the signals into the inner clean cavity. Figure 4 shows a typical topology of a signal line. The LC pi filters have a theoretical slope of –60 dB/decade, usually starting at 1 MHz. Because of tolerances and impedance mismatch, you can’t count on a better than –60 dB total attenuation. This is
beginning of the designattention process cannot be overstated. A little during the early phases of the design will prevent huge cost, performance, and schedule nightmares later on. While concentrating on HIRF, I intentionally avoided grounding, lightning, and ESD protection because different issues need to be considered. These issues deserve a separate article, but I hasten to state that when you have a good design that provides solid HIRF immunity, the addition of lightning and ESD protection will be simple. I
A FEW CLOSING REMARKS Bringing EMI under control is not as difficult as it may appear at first. However, the need to keep electromagnetic compatibility in mind from the
George Novacek has 30 years of experience in circuit design and embedded controllers. He is currently the general manager of Messier-Dowty Electronics, a division of MessierDowty International, the world’s largest manufacturer of landing-gear systems. You may reach him at [email protected].
REFERENCES [1] G. Novacek, “Testing 1, 2…”, Circuit Cellar Online, July 1999. [2] O. Hartal, “Electromagnetic Compatibility By Design”, R&B Enterprises, WestConshohocken, PA, 1996. [3] G. Novacek “The Shocking Truth About EMC,” Circuit Cellar 117–118, April–May 2000.
RESOURCE R. Goldblum, “The Continuing Saga of MIL-STD-461/462,” R&B Enterprises, West Conshohocken, PA, 1998.
enough to get rid of interference picked up by the short PCB traces and component leads inside the dirty cavity, which you consider open to the efield. It further attenuates interference picked up by imperfectly shielded interconnect cables and, most importantly, wipes out the narrow spikes that are the remnants of the clamped lightning and ESD transients due to finite speed of those devices.
Dirty R1
Clean Filters
R3
F1
Pin 1 R4 Pin 2 R2 C1
C2
F2
Transzorbs T1
T2
Figure 4—Here’s a look at the typical topology of an I/O line. It provides lightning and ESD transient protection. The residual lightning and ESD pulses as well as the remaining interference signals are attenuated before entering the clean cavity by the LC filter. w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 33
ROBOTICS CORNER Daniel Ramirez
Behind the Scenes Part 1: Controlling an Animatronics System
w
Hollywood is one of the biggest markets for automation systems, but beneath the makeup lies a number of engineering challenges. Daniel takes a shot at a DIY animatronics project that involves a controller board, motors and controllers, sensors, and a host robot.
ho could forget Patricia Neal as Helen Benson in The Day the Earth Stood Still uttering the words, “Klaatu barada Nikto” in order to activate the mighty robot, Gort? How about those nasty flying dessert plates from Earth vs. The Flying Saucers? Hollywood special effects have inspired generations of animation and robotics enthusiasts. My own favorite sci-fi flicks gave me the idea of constructing a low-cost, small-scale DIY animation system. Similar animation systems are available commercially (for storefront displays, etc.) but can be quite expensive. Although such a system could be developed on a PC or laptop, a portable animation system that fits nicely on a medium to large robot platform is also possible. In fact, I’m currently using a robot built from antique Erector sets as a test platform for this project (see Photo 1). Later, I
hope to system into some of integrate my otherthe robot platforms. The works of Walt Disney, George Pal, Ray Harryhausen, and George Lucas provided the inspiration for my interest in an animation system, but there are several books and articles
34
Issue 142
May 2002
CIRCUIT CELLAR®
that provided technical inspiration and guidance for the project. [1–3]
FACTOR 1: COST Because cost is one of the major factors for a project of this nature, I used low-cost or surplus components (or built my own) whenever possible. Although new relatively inexpensive boards such as RC servo and DC motor controllers are available commercially, the project costs can be substantially reduced if a DIY approach is used for most of the subsystem components. I elected to build the RC controller from designs freely available on the Internet. The controller uses an inexpensive PIC16C84 microcontroller. Still, I was tempted to buy the commercial Mini SSC II and MotorMind boards (discussed later) because of their compact size and specifications. I may go with the commercial boards in the future for additional devices in my animation system. If cost is not an issue and you would like to get the animation system up and running quickly, the only board that you may want to build is the PIC-based joystick controller board. The rest of the hardware may be purchased in assembled form from sources listed in this article.
SYSTEM HARDWARE The five major components of the system are shown in Figure 1. The heart of the system is the joystick controller board. The joystick controller is required to record the joystick positions/commands and button
Photo 1—I’m currently using my animation system on my RC servo propelled AntiqueBot in order to make it dance on the floor. www.circuitcellar.com
status (used for training). It computes the motor commands based on the current position of the joystick or motion input device and also plays the commands back to the currently selected motor controller. The second component needed is a motion-training device such as a joystick, mouse, trackball, variable resistor, or flexible resistor that will serve as a teaching pendant. The current design uses the time constant method (similar to the Basic Stamp’s rctime function) to read the position of the
prop to be animated. Photo 3 shows a complete animation system configuration including the PIC joystick controller board, the SERVO84 Board, two joysticks, and a tilt/pan video platform that can be used for home security or Webcam applications.
selected device. The firmware must be input changed to handle resistive analog input devices such as a variable resistor or sensor, by taking advantage of the PIC’s A/D hardware. The third major component can be any combination of H-Bridge motor controllers, RC servo controllers, motion controllers, and relay driver boards. An RC servo controller board such as the SERVO84 or Mini SSC-II is required to drive the various RC servos. An H-Bridge motor controller is needed when controlling small DC motors used in toys. A heavy-duty PWM H-Bridge motor controller drives large geared DC motors such as the ones used in my GardenBot robot (see Photo 2). A motion controller is
Thecontroller PIC18C452 used the joystick board is for a great bargain at $16 from DigiKey. The only up-front cost is the WARP13 or PICSTART programmer required to program the PIC16C84 and PIC18C452 microcontrollers, and a UV eraser to erase them. I included the firmware in hex format (see the Software section at the end of the article), so no assembly or compilation is required. I used Microchip’s 30-day demo PIC18C compiler to develop the firmware, but you would only need it if you want to learn PIC18C, in order to customize the animation system application to suit your needs. The joystick controller board shown in Figure 2 is a 3″ × 4″ board that’s
method is devised multiplex them with select controlto lines. A 24LC16B serial EEPROM is used as the primary storage device and provides storage for up to 2048 bytes, which is more that enough to control my slow moving robot platforms. The storage capacity can be easily increased with additional serial EEPROMs and minimal changes to the software for longer, smoother and more complex animations.
an expensive commercial board used in automation, CNC, and commercial robots where high precision, repeatability, and reliability are required. The relay control board is for driving relays and solenoids. The next component handles sensor feedback. I designed an optional sensor controller that I intend to integrate into the animation system in the future. [4–5] The system will be used for sensory feedback and to read older analog joysticks like those used in the
used to interface up to two joysticks, four joystick buttons (two trigger and two fire buttons), and three push-but-
complete functional description. To build the joystick controller board, use the schematic shown in Figure 2. Parts placement and board fabrication techniques are not crucial. Wire wrap, point-to-point, and PC board construction can all be used for this project. I chose to use the PC method of construction for the joystick controller board to minimize noise and to keep board size to a minimum. Start by soldering the pin headers and IC sockets onto the Radio Shack
Radio ShackOther Colortypes Computer. of sensors (e.g., video cameras) can be used too. The last main component needed is a robot, RC Toy, or animation w w w .c ir c u it c e ll a r .c o m
JOYSTICK CONTROLLER BOARD The joystick controller can recreate movements by storing the motion commands to a serial EEPROM or to a host PC/laptop for diagnostics and calibration applications.
Figure 1—There are five major components used in this animation system. ® C IR C U ITC E L LA R
ton toggle switches used for Record, Play and Calibrate functions. The board can easily fit into a small project box for added protection, or it can be mounted on the robot platform as shown in Photo 4. The two joysticks connected to two DA15 D shell connectors allow you to independently control two actuators (servos, DC motors, stepper motors), and four relays (connected to the trigger and fire buttons). The number of actuators and relays can be increased if they are slaved to one another or another
HOW IT WORKS This month, I’m going to cover the mechanical and electronic functions of the animation system. Next month, I’ll go over detailed information on how the firmware works and provide a
prototype board or PC board. Next, solder the 0.1-µF bypass capacitors as close to the IC socket power pins as possible. Don’t clip the leads because they make handy Issue 142
May 2002 35
wire wrap or point-to-point posts. Solder other discrete components such as resistors, capacitors, and diodes as designated in the schematic. Screw any PC standoffs to the prototype board and glue or solder the RS-232 connector directly to the PC board. Now it is time to check the circuit for shorts or open lines. Use your digital voltmeter to check continuity on all power, ground, and logic signals to ensure that they follow the Figure 2 schematic. Before populating the joystick con-
THE POWER SUPPLY
troller board andwith the optional SERVO84 board the ICs, power the board by connecting a 9-V battery to the positive and negative power terminals of the 5-V power supply, and check to see if the power LED lights up. If it does, check for 5 V at the V DD pin of each IC and V at the VSS pins. After this has been done, you can populate the board with the ICs and fire it up for the first time.
logic supply used byany themotor joystick power controller board and controller boards. Include bypass and filter capacitors and diodes as required to suppress voltage spikes generated by collapsing electromagnetic fields from the DC motors (if used). The test platform uses a surplus 6-V lead acid battery to power the RC servos and the Polaroid 6500 sonar ranger board. A separate 9-V battery used for
The schematic for the 5-V power supply circuit is shown in Figure 3. The power supply is used for the joystick controller board and the optional SERVO84 Board. Check for 5-V output when the 9-V battery is connected to the power input terminals. Also check for 6 V used to power the RC servos (when the SERVO84 is used), and check for 12- or 24-V motor power supply connections. Try to isolate the 6-, 12-, and 24-V motor power supplies from the 5-V
the 5-V power supply is required by the joystick controller board and the SERVO84 controller board. This arrangement keeps the motor power supply separated from the controllers to avoid power glitches. To protect the hardware from short circuits, I included an appropriate fuse between the main battery and electronics and motors in my power supply design for GardenBot. The fuse rating depends on the power requirements for all of the electronics and actuators used in the animation gear. I also used high-current rated toggle switch to acut power to the motors in case of an emergency.
BUILDING OPTIONAL BOARDS The joystick controller board can work with many commercial motion controllers as long as they use the serial RS-232 (USART) interface or the popular I2C interface. But similar DIY boards such as the SERVO84 RC servo controller board can be easily put together with the information given below. If commercial RC servo or DC motor controller boards are not used, then follow along as I briefly explain how to build the RC servo motor controller used for this article. Mark Sullivan’s SERVO84 controller is the controller that I use for most of my RC servo projects. The SERVO84 was designed for a PIC16F84 IC servo controller application for robotics platforms. Sullivan’s code is highly optimized and can control up to eight RC servos using simple RS-232 commands. I designed my version of the SERVO84-based RC servo controller by using Mark’s free PIC software (available at mks.niobrara.
Figure 2—Use this diagram to assemble the joystick controller board. Parts placement and fabrication techniques are not crucial.
36
Issue 142
May 2002
CIRCUIT CELLAR®
com/microtools.html) reverse engineering hisand code to build the board and see how he used the PIC16C84 I/O pins. This board has worked great for my RC servo robotics applications. www.circuitcellar.com
The SERVO84 works similarly to the SSC-II by accepting simple 3byte servo position commands from the serial port from the joystick con-
troller and maintaining the proper PWM waveforms every 20 ms, required to keep the RC servos positioned correctly. This board, in
Listing 1—This PIC C function is similar to the Stamp BSX rctime function that is used to read the joysticks. The ReadJoystick function reads the selected joystick using the rctime function and returns the raw x- and y-axis counts for it. void ReadJoystick(byte JoystickID, word *XCount, word *YCount) { byte PinValue; byte State; State = 0; if (JoystickID == JOYSTICK_1) { //Get counts for Joystick #1 //Read Joystick X axis using RC circuit code XJoystickDir1 = OUTPUT; //Set X joystick #1 pin to output XJoystickPin1 = 0; //Discharge the capacitor pause(5); //Allow time for discharge //Make the selected BS2 pin an input //input(Pin); XJoystickDir1 = INPUT; //Set X joystick #1 pin to input WriteTimer1_16(0); //Reset timer 1 while(XJoystickPin1 == State); //wait for Pin to equal state *XCount
= ReadTimer1();
//read timer 1 //Read Joystick Y axis using RC circuit code //Make the selected BS2 pin an output to charge capacitor for CR circuit time //low(Pin); YJoystickDir1 = OUTPUT; //Set Y joystick #1 pin to output YJoystickPin1 = 0; //Discharge the capacitor pause(5); //Allow time for discharge //Make the selected BS2 pin an input //input(Pin); YJoystickDir1 = INPUT; //Set Y joystick #1 pin to input WriteTimer1_16(0); //Reset timer 1 while(YJoystickPin1 == State);
return); CR, translates to movesending servo “B“B20”, to position 20. The Scott Edwards Electronics Mini SSC-II controller described later uses a similar syntax to control up to eight RC servos. Commercial DC and stepper motor controllers also use serial commands to ramp up a motor, position a stepper or servo and follow trajectory profiles. The embedded joystick controller software needs simple modifications to the I/O to support the commands. Listing 1 shows how RC servos can be controlled using the SERVO84 controller. The SERVO84 controller board is easy to make and not expensive if you have the tools required, including a PIC programmer. I use the WARP13 programmer for all of my embedded PIC programming tasks, because it works directly with Microchip’s MPLAB, which is also freely available as a download from the Microchip site. After you’ve assembled or purchased the optional boards, connect all the system modules as shown in Figure 1. Be sure to connect all ground and VCC lines between each module and make sure that the 5-V and the 6V RC servo terminals are connected. Check power to any other optional modules including the 5 and 6 V for the SERVO84 board.
CONNECTIONS
//wait for Pin to equal state
Twisted-pair orsystem shielded wire used connects the various boards for the RS-232 connections and the I2C connections in the system. The RC servo connectors can be assembled by soldering thin stranded wires to 0.1 ″ pin headers that mate with
*YCount = ReadTimer1(); //read timer 1 } }
w w w .c ir c u it c e ll a r .c o m
effect, acts as a coprocessor to the Stamp to alleviate the extra processing required to refresh each RC servo on the joystick controller. The Stamp is then free to perform more important tasks and also increase its response to external events. Control of up to eight RC servos using the SERVO84 controller is accomplished by sending simple command strings via the serial interface. For example, sending “A10”, CR, translates to move servo “A” to position 10 (where CR is a hard carriage
® C IR C U ITC E L LA R
Issue 142
May 2002 37
the RC servo connectors. Make sure that the connectors are keyed with the ground or positive voltage connections so power is not connected with the wrong polarity. Doing this will surely destroy an RC servo as I found out. Mechanical movements that handle repetitive motor actions (such as a tilt/pan platform) should be connected using stranded wire. If possible, these wires should be coiled to avoid breaking them. Large DC motors or stepper motors
in series with the main power lines is also a good idea.
may connections gaugerequire wire, otherwise youwith willheavy experience burnt spaghetti syndrome when they are powered. Improper connections are a definite fire hazard and should be handled accordingly. A fuse, appropriately rated for the current drawn by the motors, connected
supply spike can cause the servo motor to move unexpectedly. Noise picked up by the thin RC servo wires can also cause the RC servos to move without warning. This could be a safety concern when these servos are connected to a mechanical actuator that could injure you or someone standing
NOISE IMMUNITY Noise can be a factor when using RC servos for animations. Sources of noise include the RC servos themselves, the antenna affect of the servo wire connections, and spikes induced by other DC motors and stepper motors. The affects of noise are due in part to the sensitivity of the internal electronics. Noise generated by a power
Listing 2—Here’s the code to customize the interface commands for various kinds of motion controllers. ***************************************************************** DisplayJoystickReadings—displays the x- and y-axis joystick readings. Scaled joystick positions are sent back to the host via the serial port and also sent to the LCD display (if connected). These commands can be sampled and saved by the host or master controller for play back later (record/play), in order to implement a teaching pendant. ***************************************************************** void DisplayJoystickReadings(byte JoystickID) { //Send joystick servo commands directly to the SERVO84 controller here //Move servo "C" left wheel printf("C"); dec(XJoystick[JoystickID printf("\r"); //Move
servo "G" right wheel
printf("G"); dec(YJoystick[JoystickID printf("\r"); //Move servo "B" platform printf("B"); dec(XJoystick[JoystickID printf("\r"); //Move y-axis servo "D" forward/reverse (F-R) printf("F"); dec(YJoystick[JoystickID printf("\r"); }
38
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
Photo 2—I’m in the process of integrating the animation system into my GardenBot robot, which will be able to learn lawn boundaries when used to seed the lawn this spring.
nearby. For this reason, make sure that no one is close toThese an RCsame servo actuated mechanism. issues also apply to powerful DC geared motors and stepper motors. The best way to minimize noise is by using capacitors to filter the power lines and by also using short lengths of twisted-pair wire to connect the RC servos to the controller.
THE BATON The joystick is used as the animation system’s teaching pendant and is used to train various robots and props in a symphony of complex motion sequences. These sequences are digitized by the PIC using the C language equivalent of the BS2 PBASIC rctime command, as shown in Listing 1. For this project, I implemented some of the features from the teaching pendant used on my Heathkit Hero 1 robot (see Photo 5). These days, the PC’s game port is being abandoned in favor of the USB port for joysticks and game steering wheels. This is too bad because the game port is such a useful device for game and sensor input. On the bright side, finding a good deal on these older joysticks isn’t difficult. For this project, any RC-based input device can be substituted for the joystick as long as it meets the IBM PC joystick interface specifications for the game port adapter. Other types of devices such as a mouse,Power flexible resistors in the Mattel Glove), and(used potentiometers could also be used as input devices. For some of these input devices, the PIC’s A/D hardware would have to be used to digitize the positions. The sensor controller
40
Issue 142
May 2002
CIRCUIT CELLAR®
board can be used by the animation system specifically to digitize the positions and to provide sensory feedback from limit switches, temperature sensors, and such. To begin training the animation system, I just toggle switch S1 to the Record position and start making movements with the teaching pendant. The Record LED remains lit until the EEPROM memory buffer has been filled and the Record switch is switched off. If the switch it is not set to Off, it will start recording at the beginning again, overwriting thetoggle previous animation sequence. Next, switch S2 to the Play position, and the animation sequence will repeat. The servos or DC motors will be active during both of these operations while the live action is taking place. The Play function will remain in an infinite loop unless it is switched off. The Fire and Trigger LED indicators change state when a joystick Trigger or Fire button is pressed (toggled). These LEDs are handy when debugging the hardware or verifying if a toggle switch or button command has been accepted. They light up during start-up indicating that the joysticks are calibrated. They also light up as indicated whenever the Record, Play, or Calibrate switches are turned on. To bring the animation system to life, the joystick controller simply takes the positions read from the joy-
Photo 3—Here’s a snapshot of a tilt/pan video platform made from old Erector set parts. The platform includes the PIC animation controller board, the SERVO84 board, and a joystick. www.circuitcellar.com
sticks and maps them to commands suitable for the motor controllers using sets of equations. The first equations are used to compute scale factors for the x and y joystick positions that will be used to map raw joystick positions to scaled joystick positions or actuator commands to obtain their widest dynamic range. The window coordinates are entered during calibration and the minimum and maximum
Photo 4—The star of the show in my animation system is the joystick controller board shown here. It can easily fit into a small project box for added protection, or it can be mounted onto the robot platform itself.
joystick positions and joysticks scale factors determined when the are are calibrated: XScale[JoystickID] = (int) ((float) (XJoystickMax – XJoystickMin) / (float) (XWindowMax[JoystickID] – XWindowMin[JoystickID])) YScale[JoystickID] = (int) ((float) (YJoystickMax – YJoystickMin) / (float) (YWindowMax[JoystickID] – YWindowMin[JoystickID])) The following set of equations maps the selected joystick raw x and y counts to scaled joystick positions or actuator commands each time the joystick is sampled during an animation and sends them to the selected RC servo or DC motor controller via the serial RS-232 (USART) or I 2C interface. I take advantage of the PIC’s floating point capabilities to perform all scaling calculations.
The section code shown in Listing 2 showsofwhere to customize the interface commands for various kinds of motion controllers. The listing shows how commands are sent to SERVO84 controller via serial RS-232 interface. The joystick controller uses the timers of the PIC to measure an RC time constant to determine the PC joystick positions. This is similar to the Stamp BSX rctime function shown in Listin g 3, which is us ed to read the joysticks. The joystick controller uses the PIC’s I2C pins to write calibration data (and record or play animation scripts) to a 2-KB serial EEPROM (24LC16B). This arrangement works similarly to
Digital filtering of the joystick read-
modern CD players, televisions, and VCRs that allow daily and weekly programming of music and channels. The controller also uses the PIC’s serial port (USART) for user input from the host and to send commands to the motor controllers that are networked to it. The host mode is mainly used during debugging and calibration, but the USART could also provide more storage capability when used in conjunction with a PC or laptop host. The port D I/O lines are polled to detect if a calibration, record, or play switch has been toggled, or a joystick trigger or fire button has been pressed. The controller also uses
ings and motor possible, although I foundcommands no need toisdo it for this application. If the joysticks or input devices are purely resistive devices that cannot use the Stamp rctime function, then some form of filtering will be necessary.
LEDs connected toturns port D I/O on lines as visual cues and them or off depending on the state of the Record, Play, and Calibrate switches. Pressing the joystick trigger and fire buttons also causes corresponding LEDs to be toggled on and off.
XJoystick[JoystickID] = (word) ((float) (XJoystickRaw[JoystickID] – XJoystickMin) / (float) XScale[JoystickID] + (float) XWindowMin[JoystickID] ) YJoystick[JoystickID] = (word) ((float) (YJoystickRaw[JoystickID] – YJoystickMin) / (float) YScale[JoystickID] + (float) YWindowMin[JoystickID] )
w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 41
Photo 5—My Hero 1 robot also uses the animation controller system to improve the performance over the srcinal teaching pendant.
PWM HARDWARE The PWM hardware of the PIC18C452 is not used because all of the motor controllers that I’m working with are serially driven. The MCIPC-24 motor control board from Diverse Electronics generates the necessary PWM signals by using the PWM of the on-board Stamp BS2. The joystick controller simply sends the Stamp the motor commands and it takes care of forwarding them to the MCIPC-24.
same application to work on a PIC18C452, but to no avail. After some searching on the Internet, it would appear that I’m not the only person having these problems. It seems like there are many designers having similar problems with the I2C Slave mode using Microchip products. Although I have not tried Jeff Bachiochi’s I2C DC motor controller board design, I can see from his article that he has solved this problem using a PIC16C73. [2] In Jeff’s article, he includes complete assembly instruc-
’Net regarding various controller specifications and determining the suitability of working with my joystick controller board.
tions and the of software. At this point, I’m thinking assembling Jeff’s board and trying it out with my animation system. In theory, I can connect it to the PIC’s SDA and SCL lines with the PIC18C452 configured as the master.
sistor array such as abook ULN2803. Gordon McComb’s has a whole chapter dedicated to stepper motor circuits that can be made from discrete components. [1] Another method is to use a specialized stepper motor driver IC like Allegro’s UCN5804 which has worked well for me over the years. [7] The ’5804 is a good example of a specialized device that replaces a handful of discrete components and is affordable. It is capable of driving any 5-, 6-, or 8-lead small to medium sized unipolar stepper motors. The UCN5408 will operate motors at up to 35 V and currents of up to 1.25 A, all in a 16-pin DIP package. It also supports the wave drive format
MOTOR CONTROLLERS To control actuators such as RC servos, DC motors, and relays, the necessity arises for using a motor controller of some type. The type of controller needed depends on the kind of animation or control required as well as the power and size requirements of the selected DC motor or RC servo. For instance, DC motor control requires the use of an HBridge controller, a PID controller, or
I2C MASTER AND SLAVE 2
The I C interface is used to store data in the serial EEPROM by taking advantage of the built-in I2C hardware of the PIC18C452 and the PIC C I 2C library. The I 2C Master mode of the PIC works well in both the 100-kHz (slew off) and 400-kHz (slew on) modes. There is one aggravating problem that I have encountered and would like to solve. I would like to take advantage of the Slave mode and use it for the main communications interface in place of the RS-232. The PIC18C452 is supposed to support the Slave mode with the C library functions, but I have not been able to get
an electronic speed controller (ESC). Stepper motor control requires a stepper motor translator and an H-Bridge IC for unipolar stepper control. You’ll also need a dual H-Bridge IC for higher torque bipolar steppers. The main feature that allows any of these controllers to work with my animation system is that they must include a serial RS-232 or I 2C interface, which sends motor commands to the controller and receives diagnostic information (status or position) from it. The command stream must be customized for each controller in the firmware, as I’ll demonstrate next month. The following motor controllers
them to work PIC C. It took someproperly reading,using but I was finally able to get the Microchip application working on a PIC16F877 device. [6] I was able to send data to the ’F877 via the I 2C interface from my application. I have tried to get the
and H-Bridgefor drivers ones that I recommend use inare this project. Most of this information is available on the Internet, but I have collected some of it here for your convenience. My comments are based on what I have read in magazines and on the
42
Issue 142
May 2002
CIRCUIT CELLAR®
STEPPER MOTOR DRIVERS A number of DIY stepper motor controllers can be built around the PIC or Stamp microcontrollers. You can use the micros to directly drive the stepper motor coils using discrete components such as power transistors and diodes, or by using a high voltage, high current Darlington tran-
(one-phase), two-phase, and half-step modes for unipolar and bipolar stepper motors. Stepper motors may also be driven using a board like the Little Step-U Stepper Controller sold by HVW Technologies ($68). The board supports various stepper motor control formats and features such as velocity and acceleration profiles found in more expensive boards.
Photo 6—In fact, I use the 24-Vt MCIPC-24 motor control board shown in this photo to control the two Swiss-made 24-V geared DC motors used to move my GardenBot. www.circuitcellar.com
There are more advanced The Magnevation motor (more expensive) stepper driver kit (P/N: R121-MTRmotor drivers used for precise DRV-KIT) is a good place to positioning in plotters, scanstart. The kit is sold by ners, automation, robotics, Acroname for $65 and conand scientific applications. tains all of the parts needed to The PIC-STEP made by J.R. make your own H-Bridge Kerr is a good example of a motor driver board. The board midrange stepper motor drivwas srcinally designed for the er. The PIC-STEP Step and OOPic controller as an accesDirection outputs can be consory, but it’s easy to adapt the Figure 3—Use this schematic to build the 5-V power supply that’s needed nected to popular stepper board for use with other conto power the joystick controller board and the optional SERVO84 board. motors and drive them with trollers. This board is designed step rates of up to 50,000 steps per Another way to achieve greater to use a National H-Bridge (included) second. It’s alsostepper suitablemotors. for use with micro-stepping
power-handling use the MIT Handyboardcapacity system is fortodriving high power motors. The board uses a Texas Instruments SN754410 quadruple half-H driver that combines the protective diodes of the L293D chip with the greater current capacity of the L293B chip. The SN754410 is a plug-and-play replacement for the L293D. The high-current H-Bridge driver is suitable for driving high-power DC motors or stepper motors. The driver is capable of driving one motor with the maximum current rating of 25 A at 3.5 V to 17 VDC. The Handyboard H-Bridge driver kit is fully assembled, tested, and available for $38. Specifications of the MIT Handyboard
that allows for 3 A of continuous current capacity. National also sells the bare PCB if you already have the separate parts. [12] The Devantech 50-V, 20-A H-Bridge motor driver (P/N: R133-MD03) is also sold by Acroname. For $77 you get a medium power motor driver, designed to supply power beyond that of any of the low power single chip H-Bridges that exist. Its main features are ease of use and flexibility. It also includes a PWM, RC mode, and an I 2C interface. Up to eight modules can be daisychained together by specifying a unique address to each. It measures 113 mm × 52 mm × 30 mm. [13] Electronic speed controllers can be found in RC electric model airplane
signals to the H-Bridge and provide serial communications to the automation controller. The motor command format should be made as simple as possible. The Dallas Personal Robotics Group (DPRG) has an interest ing HBridge design that includes a PC board. [9] The purpose of the DPRG’s H-Bridge project is to create a PC board with two H-Bridge circuits capable of driving motors with several amps of power. The board must also be able to interface similar to an L298, be able to be controlled by an on-board MCU, and allow an additional serial interface. The Seattle Robotics Society (SRS)
system are located on the Web and contain a PCB pattern and component placement diagram for a dual H-Bridge expansion board srcinally intended for the MIT Handyboard. [11] The board is based on the LMD18200 from National Semiconductor. The motor battery can be from 12 to 55 V, and the H-Bridge can supply a constant current of 3 A and a peak current of 6 A.
Small DC motors are neatly controlled using an H-Bridge or commercial boards. Again, there must be a small microcontroller driving the DIY H-Bridge to provide the neces-
magazines and they usually run between $50 and $200, depending on make, size, and model. The power efficiency and size for these types of controllers is amazing. They’re handy for controlling the small DC motors used in functional scale models. The MotorMind controller is a compact board measuring 1.6″ × 1.2″ × 0.4″. According to the specs it can handle voltages up to 30 V and continuous currents of up to 2 A using PWM. The board also includes a built-in tachometer capable of measuring up to 65,528 Hz. This controller couldbe connected to my animation system using its 2400-bps serial RS-232 interface. With a few minor changes to the
has many articles roboticsonline and electronics in theironmonthly publication called the SRS Encoder. I found an article titled “A Few Words About Motors…” that contains a design schematic for driving stepper motors with the L293D. [10]
sary PWM control signals to the HBridge and provide serial communications with the automation controller. If a commercial motor controller is used, then it should have a serial interface so it can be interfaced to the automation system.
MotorMind serial motor command output, and by specifying the window parameters used for scaling the motor commands during calibration, it should work fine with the animation system. As of now, though, I have not had a chance to try it out yet. The
H-BRIDGE CIRCUITS Plenty of designs for light and heavy duty H-Bridges can be found on the Internet. Several of these look interesting, but I have not tried them yet. Application notes from Allegro and National Semiconductor provide a few additional designs for H-Bridge motor drivers. [7, 8] I have used some of these designs for driving DC motors and stepper motors in my own projects and they have worked well for me. For this project, I needed a small microcontroller such as an AVR, PIC, or Stamp to drive the H-Bridge to provide the necessary PWM control
w w w .c ir c u it c e ll a r .c o m
DC MOTOR CONTROLLERS
® C IR C U ITC E L LA R
Issue 142
May 2002 43
board can be purchased for $30 from a number of distributors or directly from Solutions Cubed.
LARGE MOTOR CONTROLLERS Large DC motor controllers used to drive heavy-duty geared DC motors require a high current driver board or H-Bridge. Photo 6 shows how I used a 24-V MCIPC-24 motor control board in my GardenBot. I avoided purchasing a second MCIPC-24 by using two relay control cards to switch the motors’ direction and enable each motor The separately. Diverse Electronic Services MCIPC-24 costs $40. The company sells other heavy-duty PWM HBridge boards for 12- and 24-VDC motors with up to 30 A of current. The MCIPC-24 requires a motor interface card to be built or purchased from Diverse Electronics Services in order to step up the PWM voltage from the micro to the required PWM level of 4 to 8 V required by the MCIPC-24.
MOTION CONTROLLER BOARDS These boards usually include some form of PID control with a built-in tachometer for position and velocity feedback, along with the ability to specify trajectory and motion profiles (ramp, trapezoid, sine, etc.). These boards are used for CNC and automation applications that require accurate positioning and repeatability. For this reason, they are more expensive than other motor controllers. These midrange boards can cost from $130 to $200, and yet they provide the functionality of high-performance boards costing much more.
RC SERVO CONTROLLERS RC servos can be controlled by using the pulsoutfunction of a Parallax Stamp BSX microcontroller, however, you are limited to two or three servos because of the execution speedproject, of the IPBASIC interpreter. this used the SERVO84 For that was described earlier in the article to control the servos. Another option is the Mini SSC II serial servo controller designed by Scott Edwards and sold by his com-
44
Issue 142
May 2002
pany for $44. It is a compact and well-designed surface mount board that measures 1.4 ″ × 2.1 ″ and is ideal for animatronics and robotics applications such as my project. This servo controller works similarly to SERVO84 in that it accepts simple 3-byte servo position commands via the serial port from the joystick controller. The Mini SSC-II may be networked with other Mini SSC-II controllers to independently control up to 255 RC servos via the serial RS-232 interface. Each node
amount of servo travel from 0° to 90° to 0° to 180°. The board should work with the joystick controller with minor changes to the serial RC servo commands as shown in the file animate.c located with the other software for this project on the Circuit Cellar ftp site. The Mini SSC II seems to be quite popular and is being used in many interesting applications. If the Mini SSC II board is used with my animation system, small changes will need to be made to the firmware. These
has itsthe own unique address that keeps controllers from interfering with each other. Another nice feature of this controller is its ability to control the
changes will beThe described Part 2, of this article. changesinare necessary to make the command stream conform to the SSC-II’s servo command syntax.
Listing 3—This section of code shows how the joystick data is read and processed. Using C functions that I developed, the joystick can be used as a pendant to train various robots, toys, and props with a symphony of complex motion sequences. void {
Record(byte JoystickID)
JoystickButtonStateStatus_T LocalButtonStatus; //Local Button Status word i; //Local loop index //Set start address of available serial EEPROM //EEPointer = EEStartAddress; //Write animation data to EEPROM for (i = EEStartAddress; i < (MEMORY_SIZE - 6); i += 6) { //Turn on the Record button LED indicating "RECORD" RecordLED = 1; //Read both the x and y joystick pots using the RC circuit ReadJoystick(JoystickID, &XJoystickRaw[JoystickID], &YJoystickRaw[JoystickID // Read joystick #1 x and y axis counts //Scale the joystick x and y axis raw pot values ScaleJoystickReadings(JoystickID); //Display joystick status information DisplayJoystickReadings(JoystickID); //Store the latest joystick position and button state to EEPROM or send back it to the host StoreJoystickValues(JoystickID, i); //Process joystick readings //ProcessJoystickReadings(JoystickID); //Save current joystick positions and button states OldXJoystick[JoystickID] = XJoystick[JoystickID]; OldYJoystick[JoystickID] = YJoystick[JoystickID]; //Delay for sampling period during recording pause(SamplePeriod[JoystickID } ExitRecordLoop: //Turn off the Record button LED indicating "END RECORD" RecordLED = 0;
CIRCUIT CELLAR®
www.circuitcellar.com
HARDWARE IMPROVEMENTS Future hardware improvements to the animation system include using a PIC to transmit joystick information to a robot using the Sony IR remote control protocol with a 40-kHz modulated IR LED transmitter and a Sharp IR receiver. I would also like to implement an RF transmitter and receiver combined with a Holtek encoder and decoder to send remote control commands to the robot or radio-controlled prop (e.g., two RC cars could be independently controlled from each joystick). application could also be used inThis security applications for manipulating a tilt/pan camera platform. Other ideas include integrating my sensor controller board. It would work as a coprocessor to the animation system using the I2C or USART interface to provide sensory feedback to the animation system. The I2C bus may be used as a high-speed bus to communicate with the PC host or other PIC processors. This would be helpful in advanced robot designs that take advantage of multiprocessing or networked processors. On of the last improvements I’d like to make is to integrate a PIC-based relay controller board that I recently designed into the animation system so I can switch high-power relays, solenoids, valves, and muscle wire.
ANIMATING IT ALL Using the animation system described in this article, I have integrated many commercial and DIY motor controllers into my various animation projects. Although I was only experimenting with it initially, I’ve discovered that I can carry out a number of complex animations with this system. Although this series of articles will barely scratch the surface in the field of animation and special effects, I feel that this article and next month’s are a good introduction. One area that I’ve yet to explore is obtaining sensor feedback during animations. For instance, the Mattel PowerGlove provides a sense of 3D immersion for the operator using it. Contact and limit switches can also w w w .c ir c u it c e ll a r .c o m
be used to enhance animations by preventing actuators from exceeding specified travel limits. Vision systems have been used successfully in industry for automobile automation. A true tele-presence application would tightly couple the sensor or vision system with the animation system, but describing such a system is beyond the scope of this article. In Part 2, I’ll describe the details of the firmware and will also show how the animation system works (including customizing the serial command stream for variousI will commercial DIY controllers). also giveand examples of more applications using the controller. See you next month with more information on the exciting world of animatronics. I Author’s Note: Thanks to my wife, Pamela, for her time and assistance with this article. Daniel Ramirez is currently a senior software engineer with over 10 years of experience working on real-time embedded systems. His hobbies include travel, golf, treasure hunting, and robotics. You may reach him at [email protected].
REFERENCES [1] G. McComb “Robot Builder’s Bonanza,” 2nd ed., McGrawHill Professional Book Group, 2001. [2] J. Bachiochi “DC Motor Control for the I2C Bus,” Circuit Cellar 62, September 1995. [3] S. Edwards, “The Juggler’s Delight: PIC-based Controller for up to Eight Servos,” issue 51, The Computer Applications Journal, October 1994. [4] D. Ramirez, “Robot Sensor Controller Board—Part 1” Circuit Cellar 135, October 2001. [5] ———, “Robot Sensor Controller Board—Part 2,” Circuit Cellar 136, November 2001. [6] S. Bowling, “AN734: Using the PICmicro SSP for Slave I2C TM Communication,” DS00734A, Microchip Technology Inc., 2000. ® C IR C U ITC E L LA R
[7] Allegro “UCN5804: BiMOS II Unipolar Stepper-Motor Translator/Driver,” Allegro MicroSystems, Inc., 2002. At www.allegromicro.com/datafile /5804.pdf [8] National Semiconductor Corp., “LMD18200 3A, 55 V HBridge,” 1999. [9] Dallas Personal Robotics Group, H-Bridge Driver project, www.dprg.org/l298.html. [10] Seattle Robotics Society, “A Few Words About Motors…”, www.seattlerobotics.org/ encoder/sep97/motors.html. [11] Specifications of the MIT Handyboard system are located at www.mcmanis.com/~ cmcmanis/robotics/h-bridge/ h-bridge.html. [12] Magnevation motor driver kit information, app notes, schematics, and related information can be found at www. magnevation.com. [13] Devantech H-Bridge driver motor, Additional app notes and schematics, and technical support for this board can be found at www.robot-electronics. co.uk/htm/md03tech.htm.
SOURCES MotorMind Solutions Cubed www.solutionscubed.com/Products/MotorMindB/ motormindB_main.htm MCIPC-24 Diverse Electronic Services (570)-735-5053 members.tripod.com/~divelec/ hbridge.html PIC Microcontrollers Microchip Technology Inc. (800) 344-4539 www.microchip.com Basic Stamp Parallax Inc. (888) 512-1024 www.parallaxinc.com H-Bridge Drivers Allegro MicroSystems www.allegromicro.com Issue 142
May 2002 45
FEATURE ARTICLE John Taylor
Hand-Soldering FinePitch QFP Devices
s
John walks us through the basics of working by hand and explains some techniques that can be used for replacing SMT devices or installing sockets. His practice exercise shows us that most components aren’t too compact for hand soldering, at least not yet.
46
Issue 142
May 2002
urface-mount devices are typically used to minimize circuit board real estate. As a result, the boards give you little working space between components to rework anything. Component gaps are small and the leads (and lead pitches)
I want to note how important safety is before getting into the project. In addition to the normal precautions associated with doing close work, such as wearing proper eye protection, always do circuit board rework in a well-ventilated area. Prolonged exposure to solder fumes and solvents can be hazardous. And remember, if you use solvents, don’t work in areas where there are exposed sparks or flames.
EQUIPMENT LIST Doing any work well requires that you have good Based list on my experience, thetools. equipment (available to download from the Circuit Cellar web site) should give you the right tools to get started. Other materials or tools may work fine, and for other types of components you might find other tools are needed. So, feel free to substitute and experiment. I recommend using organic solder, at least in part because of familiarity. The important thing is that you use a solder that you’re comfortable with, one that will flow well and make good solder joints. Consistency is the critical factor. In addition to the basics, you’ll find it extremely useful to have a board vise to hold the circuit board steady. A dental pick, with a 90° bend, proves
are fine. If you’re developing prototypes or working in a small board shop repairing boards populated with surfacemount devices, you might not have the specialized equipment used for removing and mounting SMDs. Experience shows that you can, however, do the job by hand. All you need are basic hand-soldering skills for through-hole soldering and a set of hand-soldering equipment. It is possible to effectively replace SMT devices or install sockets and complete other reworking tasks without special manufacturing tools. In this article, I’m going to show you an example of a reworking job. The project involves the removal, cleanup, and replacement of a typical
useful in positioning loose pads and general probing. Compressed dry air or nitrogen to dry the board speeds the work. And, to provide a truly careful inspection, it’s wonderful to have an optical inspection stereo microscope of 30× to 40× magnification.
component, a thin quad flat pack (TQFP). I’ll provide a complete list of the hand-soldering equipment you’ll need and a step-by-step explanation of one way to approach the task. If you have other equipment or other skills, you might choose a different approach.
first is to mount in The some sortstep of holder or visethe as board shown in Photo 1. If you don’t have a PCB vise, you’ll need to firmly position it in some way that it is held steady while you work on it. This is extremely important considering the
CIRCUIT CELLAR®
THE JOB AT HAND The rework task breaks down into three major steps: part removal, board cleanup, and soldering in the new device. You will replace a TQFP device that has 48 pins and a 0.5-mm lead pitch. The device’s leads are configured in the standard gull wing shape associated with JEDEC-standard quad flat packs (QFP).
www.circuitcellar.com
small amount of room you’ll have to work in and the narrow margin for error with a hot soldering iron. It will prove difficult to work carefully and accurately if the board is moving around; you can do more damage than good. To finish preparations, warm up the soldering station to 700°F (370°C) and clean the solder tip. Make sure that you grounded the
melts, smoothly move the tip to the next lead, and then the next, making it a continuous process for the entire side of the IC. Be sure not to hold the heat on any one lead longer than necessary. The first lead will take the longest to heat, but this also heats the wire, which will help melt the solder on the other leads. Excessive heat can damage both the IC device
ESD matyou’ll and wrist strap. and PCB pads. need to Because be working to practice thisYou’ll technique with high heat that could get a sense of how fast you Photo 1—Securing the PCB in a board vise is the best way to hold it steady. easily damage the board or can move the soldering iron other components, it’s a good idea to ment with different lengths of wire to tip. Removing the leads on one side of practice the following procedures on a see what works best for you. Feed the a 48-pin TQFP should take about 5 s. piece of scrap before working with an wire behind and under the leads (see While you are learning, watch for expensive prototype. You’ll quickly Photo 2b) along one side of the IC, signs that you are using too much develop a sense of how fast to move and then anchor it with a solder tack heat. The most common indications the solder tip and how long it takes to are melted plastic on the IC, brown to a nearby via or component on the make the solder flow. You want to PCB (see Photo 2c). scorch marks on the circuit board, or develop a smooth touch and an intuThe wire, with one end anchored, circuit board pads begin lifting. itive sense of how quickly you need will serve as a pry bar that puts presAfter you’ve removed all of the to move the solder tip over the leads. sure on the leads as you apply heat. leads for one side, wet the leads on When you’re comfortable with the Grasp the unanchored end of the wire the next side with flux and repeat the process, begin by wetting all of the with your tweezers rather than your procedure. You’ll find it a good idea to leads with flux to enhance the initial cut off the dirty part of the wire wrap hand. The tweezers will provide more solder wicking cleanup. Now, wick up control and, besides, the wire is going wire or use a new piece for each side. as much solder as possible from the to get hot. Make sure you grasp the If you are removing a defective IC, QFP leads like you see done in Photo 2a. Be careful not to scorch the PCB with prolonged solder heat. Next, strip approximately 3 of insulation from a 12 piece of 30-gauge wire wrap wire. The actual length of the wire is not critical, because this piece will simply serve as a tool for lifting leads. However, the wire needs to be long enough so that you can handle it easily. You’ll want to experi″
″
a)
wire close to the device. Apply the soldering iron tip to the device lead that is closest to your tweezers and begin pulling the wire away from the QFP, slightly upward from the surface of the board (see Photo 3a). As the solder melts, gently continue pulling the wire away from the QFP and move the solder iron tip to the next pin away from the tweezers. The wire will pull the leads free as the solder melts. As it
or do not need to save the IC being removed, you can use a little more heat (800°F (425°C) in this example), ignoring the fact that this results in some melted plastic and missing gull wing leads. You can see this kind of damage in Photo 3b. If you want to save the IC being removed, however, then you’ll have to minimize the heat you apply to the leads to just barely enough to free the lead from the PCB.
b)
c)
Photo 2a—Apply solder flux and then wick the excess solder from the pins. b—Feed the stripped wire wrap wire behind and under the QFP leads. c—Anchor one end of the wire to a nearby component or via. w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Issue 142
May 2002 47
b)
a)
Photo 3a—Hold the tweezers close to the device and begin heating the lead closest to the tweezers. b—Removing the device quickly can damage it because of the high heat.
CLEANING UP THE PCB Even if you are careful, removing the IC leaves the PCB in a bit of a mess. Although installing an IC on a new PCB would require little more than brushing the pads with isopropyl alcohol and drying the board, with this project, you have other work to take care of first. Excess solder and flux have to be removed and any damage you’ve inadvertently done to the PCB needs to be repaired. The first step is to clean the solder pads. You want them to be flat. A clean solder pad will be a dull silver color, so you should solder wick the pads until they are flat and dull. When you’re done, inspect them carefully. You might notice some that have become loose from the PCB (see Photo 4). Here is where the dental pick comes in handy. Use a pick or some other pointed object to carefully realign the pad. A large number of loose pads or lifting of a trace indicates that you are using too much heat, leaving the soldering tip on a lead for too long a time, or are pulling too hard on the wire. Again, practice and experimentation will tell you what are doing wrong.
SOLDERING A NEW QFP
pin orientation to make sure pin 1 is in the right spot, and then align the part over the pads as accurately as you can. Now, you need to secure the package in place or it will move around while you’re soldering it. You don’t need as much heat for this operation, so first adjust the soldering station temperature down to 700°F (370°C). Put a small amount of solder on the tip of the soldering iron. Hold the aligned QFP in place by applying pressure straight down with a pick or other pointed tool, and add a small amount of solder flux to the corner leads on two opposite corners of the QFP. After that, solder just those two leads. For the moment, don’t worry about any excess solder or whether or not you have created shorts between the leads. All you want to do is carefully anchor the aligned chip with solder so that it doesn’t move. When you have the device anchored, recheck its alignment. If the device has moved, use a pick or similar tool to adjust it, or if necessary remove it and start over. Now is a good time to be fussy. Any misalignment at this point will cause problems later on. If the alignment is fine, then you are ready to solder the rest of the leads.
With the pads cleaned and aligned, you can begin aligning the new IC. Carefully place the QFP device on the PCB. You can use and a tools probe to align it ortweezers use any other that suit you. Make sure not to drop the part while you position the chip. Dropping it can easily damage the leads. Also, bear in mind the dangers of ESD on the IC. Double check the
48
Issue 142
May 2002
CIRCUIT CELLAR®
Figure 1—Keeping the iron tip parallel to the pins being soldered reduces solder bridges. www.circuitcellar.com
First, add a little more solder to the tip of the soldering iron and dispense additional flux over all the leads to get them wet. Touch the soldering iron tip to the end of each lead until solder begins to run up the lead. Holding the soldering iron tip parallel to the pins being soldered helps reduce the frequency of solder shorts, or lead-to-lead bridging (see Figure 1). But again,don’t worry if you see some solder bridging. You can clean that up later, but, of course, there will be less to clean up if you’re Photo 4—Make sure that you inspect the pads to look careful. There’s always going to be a for any that have come loose. trade-off between how you can be and how quickly youcareful want to work. As you go, periodically add small amounts of solder to the soldering iron tip. After you’ve soldered all of the leads, wet them with flux again. This will enhance the solder wicking cleanup. Use the solder wick wherever you see shorts and bridging. It’s time to inspect the board closely. You’ll need at least 4× magnification to identify shorts and marginal solder joints. A good solder joint will have a smooth melt transition between the device pin and PCB trace. Look for irregularities and rework any pins with defects. This is where it is convenient to have a 40× stereo zoom inspection station.
either available, shake off excess liquids and let the board air-dry for at least 30 min. to give the alcohol under the QFP a chance to evaporate. When dry, the QFP leads should look bright and there should be no flux residue. Clean again if any flux remains. When you’re satisfied with your cleaning job, inspect the board for workmanship. It will be easier to spot any problems on the clean board. Do any rework that appears necessary and clean the board one more time. When you are finished, your reworked IC and the surrounding PCB should look as clean and pristine as components installed in a standard manufacturing process (see Photo 5).
After the board passes the visual Don’t worry if your efforts fall a little inspection, it needs to be cleaned again. short at first, your rework will Dip the bristle brush into isopropyl improve with practice. I alcohol and wipe in the direction of the leads. Use the alcohol liberally, brushJohn Taylor graduated from ITT ing well between the device leads Technical Institute in Austin, Texas until the flux disappears. When it is with an AAS in Electronic Engineering clean, dry the board with compressed Technology. He is a product test engidry air or nitrogen. If you don’t have neering technician for Cygnal Integrated Products. His technical interests cover a wide arena. You may reach him at [email protected].
PARTS LIST To download the equipment list, go to ftp.circuitcellar.com/pub/ Circuit_Cellar/2002/142/.
SOURCE
Photo 5—When you are done cleaning, the QFP leads should be bright and shiny. w w w .c ir c u it c e ll a r .c o m
EC1201A Soldering station Weller (408) 878-9000 Fax: (408) 878-2750 www.palm.com ® C IR C U ITC E L LA R
Issue 142
May 2002 49
FEATURE ARTICLE Joseph Jones & Ben Wirz
RoCK Specifications
he Robot Conversion Kit (RoCK) is a low-cost module that can help you transform an RC car into an autonomous robot. In the previous issue, we provided a general description of the kit, covering the functions the RoCK
first version was a proof of concept prototype. We developed this version to gain familiarity with the Atmel AVR processor and to experiment with possible user interfaces. The second version became our entry into the Circuit Cellar Design Logic 2001 contest. Our entry, shown in Photo 1, was implemented using a pin through-hole (PTH) design with components mounted on both sides of the PCB. With an eye toward commercialization, we evaluated this design but decided it was too complex to be assembled by the average user and too expensive to be assembled professionally. Electrically similar to the second version, we optimized the third (cur-
performs and the top-level choices we made to implement those functions. In this article, we’ll focus on the electronic hardware and explain how we achieve the desired functionality. We kept the following three goals in mind while designing the electrical
rent) version of the RoCK for machine assembly. Version three makes extensive use of surface mount technology (SMT). Only a few PTH components are used and all but two of these components are mounted on the topside of the board. The PTH components can
Part 2: The Circuitry
t
In the second part of this project, Joe and Ben take the cover off of their prize-winning hardware and show us what makes their robot conversion kit tick. After a closer look, you’ll see why the Design Logic 2001 judges selected this project as one of the top submissions.
circuitry. For our first goal, we wanted to minimize cost and production delays by careful selection of components. Our second goal was to maximize “buildability” by simplifying connections between the RoCK and the mobility base, as well as by making the kit tolerant of common wiring mistakes. And lastly, we wanted to maximize battery life through careful attention to the power implications of design choices. During its development, the RoCK existed in three major versions. The
a)
b)
Photo 1—The RoCK enables a builder to convert an RC car or other mobility base into an autonomous robot. In the photo on the left, the RoCK implements a robot built on a base borrowed from a tracked RC car. In the photo on the right (b), the RoCK controls a scratch-built robot. The wheels, gears, and motors were salvaged from an old toy and attached to a simple polycarbonate chassis.
50
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
be wave soldered following the SMT step thus eliminating hand soldering and reducing assembly cost.
SYSTEMS OVERVIEW The RoCK’s circuitry is designed to support the ultimate goal of the project—the creation of a lowcost, high-function, autonomous mobile robot. Light sensors enable a RoCK-powered robot to follow light and source or darkto avoida light seek ness. The obstacle detector, consisting of two infrared (IR) emitters and two IR detectors, makes it possible Figure 1—At the heart of the RoCK’s circuitry is the Atmel AVR AT90S8535 microcontroller. The AVR provides a high degree of to sense obstacles and avoid processing power with substantial built-in hardware in a compact form. collision. If a collision does occur, the motor currentbased collision detector alerts the ON-BOARD INTERFACE Several channels of the AVR’s anaRoCK so corrective action can be log-to-digital converter (ADC) are used A DPDT switch controls power to taken. The motor driver provides sufto monitor the light sensors, user the RoCK. The switch enables both ficient power to operate the kinds of input, and battery voltage. The AVR’s the 9-V logic supply battery inside the motors commonly found in RC cars. comparator detects drive motor overcase and the motor battery associated The user button and potentiometer current. Timers built into the chip con- with the user-supplied mobility base. enable you to configure the kit and trol the pulse width modulation (PWM) Four I/O lines configured as outputs adjust certain parameters. The battery of the motors, generate the tones sent connect to the LED display. The LEDs voltage monitor alerts the user when to the beeper, and produce the 38-kHz are used to indicate robot status. The batteries are nearly exhausted. Four carrier signal needed by the IR obstaLED enable line (*LEDEN) makes it LEDs and a piezoelectric beeper give the RoCK the ability to inform the user of other conditions as well. The serial interface provides a high-level programming channel for the RoCK. An advanced programming header allows programming access to the microprocessor’s flash memory. The expansion header gives you a way to connect additional sensors and actuators to the RoCK. Details of our implementation are given in Table 1. Every I/O pin available on the microprocessor is assigned to a built-in sensor or is brought out to a header for user access.
possible to multiplex the lines that drive the LEDs. The beeper connects to the AVR’s PD6 line. An interrupt service routine (ISR) associated with Timer/Counter 0 is used to toggle PD6 to produce a square wave for the beeper. The time between interrupts corresponds to the half-period, H, of the desired beeper frequency. The RoCK configures Timer/ Counter 0 for eight microsecond ticks. Thus, H is related to frequency ( ƒ) by:
THE CPU
cle-detection system. Serial I/O built into the AVR is used to connect the RoCK to a host computer for highlevel programming and monitoring. Digital I/O lines drive the LEDs and detect presses of the user button. The AT90S8535 has 8 KB of flash program storage, 512 bytes of SRAM, and 512 bytes of software programmable EEPROM. The built-in tasks supplied with the RoCK are stored in flash memory; high-level programs created by users are saved in EEPROM. The AVR internally provides all of the circuitry needed to store data to the on-chip EEPROM. To enable users to delete the built-in tasks and reprogram the flash memory, an industry
The key to the highAVR functionality is the CPU—an Atmel AT90S8535 microcontroller. The AVR integrates many useful functions into one low power, low pin-count chip. The RoCK takes advantage of almost all the features that the AVR provides.
standard 2 × 5isIDC in-circuit programming header provided. The CPU gets its clock signal from an external 8-MHz ceramic resonator. The resonator, chosen forits mechanical toughness and compact size, requires no external capacitors or resistors.
Therefore, lowest the beeper can the produce is frequency ƒ = 62,500/255 = 245 Hz and the highest frequency (where H equals 1) is 62.5 kHz. The RoCK restricts the set of tones that it actually produces to those approximating the well-tempered
w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Timer/Counter 0’s 8-bit register can store a number in the range of 0 to 255.
Issue 142
May 2002 51
scale. That is, for a tone of a given base frequency (ƒ0), the nth tone of a scale (ƒn) is given by:
The RoCK uses 532 Hz for ƒ0. Given that only integer values of half periods can be stored, the chosen base frequency produces a scale whose tones closely match a well-tempered scale. Externally driven piezoelectric beepers are typically rated for a drive voltage of greater than ±10 V. The sound volume of such a beeper driven directly from a 5-V TTL output is substantially less than the volume produced when the Figure 2—The RoCK’s minimal controls provide a straightforward user interface for robot configuration and task selection. full driving voltage is applied. Gear noise from a mobile robot base can easily make er’s terminal voltage, is required. This creates a beeper excitation voltthe sound from a piezoelectric beeper With the microcontroller output age of approximately 9 V to –5 V, repdriven by this method inaudible. To driven low, Q5 is off and current resenting an increase in magnitude of combat this problem, the RoCK uses flows through R12 into the micronearly 300% over direct TTL drive. a pseudo H-Bridge driver to create a controller’s pin. Thus, the beeper’s To select a built-in or user-pro14-V PP swing. This is accomplished lower terminal is at a voltage of 0 V grammed task, you press the user butby adding a single external transistor and the upper terminal is at approxiton and adjust the user pot. The user and two resistors. The microcontroller’s output stage can be driven to ground or 5 V (see Figure 2). In order to create a negative voltage swing, an H-Bridge driver, which is capable of reversing the beep-
mately 9 V. With the output driven high, Q5 is turned on. Current flows out of the microcontroller pin through Q5 to ground. The beeper now sees 5 V at its lower pin and close to 0 V at its upper terminal.
b)
a)
pot is connected to ADC channel five, and the user button is connected to digital I/O pin PA4. Both lines are part of the AVR’s port A. Port A lines can be individually configured for either digital or analog operation.
PC transmit
PC TX
Marking
Stop
+15V –15V +15V
PC RX –15V AVR TX +5V AVR RX +15V
PC receive
PC TX –15V +5V PC RX
Marking
Stop
–15V +5V
AVR TX +5V AVR RX
Figure 3—The discrete component transceiver provides a low-cost RS-232 connection to a host PC.
52
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
The RoCK implements a novel half-duplex RS-232 level converter to enable serial communication while reducing cost and board space. Given the RoCK’s modest communication needs, the limitations imposed by half rather than full duplex are inconsequential. It’s a challenge to generate the negative TX voltage required by the RS232C specification without an expensive charge pump IC such as the venerable Maxim MAX232. We solved the problem by looping back the TX
POWER SUPPLY AND RESET
voltage fromhost’s the host serial line. The TX computer’s voltage is negative in its marking (inactive) state. For this method to work, the host must not transmit at the same time as the RoCK transmits and the host must ignore the commands it sends which are echoed back to it by the resistor R2. This scheme produces the half duplex requirement. See the signal diagram in Figure 3 for more detail. A serial speed of 9,600 bps was chosen for the RoCK’s serial link. The baud rate (in units of bits per second) is set by the UBRR register. The serial speed is given by the formula:
life. low dropout regulators are moreMost expensive than the 7805; often they require costly and sometimes scarce low ESR tantalum output capacitors. During our search we discovered the National Semiconductor LM2931AM-5.0. The LM2931 is a low
where ƒCK is the clock frequency. The ceramic resonator is specified at 8 MHz ± 0.5% at 25°C. The resonator has a temperature stability of ±0.3% over its range of operation and a 10-year aging spec of ±0.3%. In the worst case with parameters at their least favorable extremes, the resonator frequency is 8 MHz ±1.1%, or 7.912 to 8.088 MHz. Using a UBR register setting of 51, the maximum and minimum baud rates are given respectively by:
The srcinal PTH version of the RoCK used the common, inexpensive 7805 linear 5-V regulator in a TO-92 package. A 9-V battery powers the logic supply. The conversion to surface mount components in the latest version of the RoCK prompted us to survey modern SMT linear regulators. Modern linear regulators are available with dropout voltages lower than that of the 7805. Low dropout voltages are important because they translate directly into increased 9-V battery
Syst em
P o rt s / S i gn al s
On-board user interface Powerswitch Display Beeper
User potentiometer Userbutton Serial interface Obstacle detection LeftIRdetector RightIRdetector IRemitters
V
/Batt+ CC PC0–3 PD6
PA5 (ADC5) PA4 PD0–1 (RXD, TXD)
PD2 PD3 PD7(OC2)
dropout regulator that requires only a standard electrolytic capacitor for output filtering. In addition, the LM2931 offers a quiescent current lower than the 7805, is available in SO8 SMT package, and costs only about $0.35 in quantity. The RoCK provides a 5-V power supply monitor that puts the microcontroller into reset when the 5-V supply dips below an acceptable level. The reset circuit helps prevent erroneous operation of the microcontroller during low battery conditions.
LIGHT SENSORS The RoCK uses cadmium sulfide (CdS) photo-resistive elements, photocells, to detect light. Among optoelectronic devices, photocells are relatively slow to respond to changes in
D e s c r i p t io n
DPDT switch enables logic and motor power FourLEDsdisplayrobotstatus Interrupt-drivenpiezoelectricbeeperproduces tones of arbitrary frequency Parameter adjustment knob Momentarycontactselectswitch RS-232 interactive connection to host computer and high-level user programming facility 38-kHzIRreceiver 38-kHzIRreceiver Chipautomaticallygenerates38-kHzmodulation for two series-connected IR emitters
Light sensors Left photocell Rightphotocell
PA0(ADC0) PA1(ADC1)
Analoginputsenable detectionoflight
Collision detection Motor current
PB2 (AIN0)
Analogcomparator comparessetpoint with motor current to detect collision
Currentset
PB3(AIN1)
Battery monitors Motor power Logicpower
PA2(ADC2) PA3(ACD3)
Monitor for motor supplybatteryvoltage Monitorforlogicsupplybatteryvoltage
Motor output Motor PWM
PD4–5 (OC1B, A)
Chip automatically generates PWM for dualchannel motor driver
Motordirection
PB0–1
Auxiliary IO
Userdigital User analog
This is equivalent to a speed of 9,600 bps +1.3/-0.9 %, absolute worst case. These error rates are acceptable for reliable asynchronous serial operation. w w w .c ir c u it c e ll a r .c o m
PC0–7 PA6–7(ADC6–7)
Advanced programming Programming header
EightdigitalIOlinesavailable Two analogchannelsavailable
PB5–7 (MOSI, MISO, SCK) Enables user to program flash memory
Table 1—The RoCK’s major systems are implemented using on-chip hardware as summarized in the table. Labels in the Ports/Signals column follow Atmel’s convention. ® C IR C U ITC E L LA R
Issue 142
May 2002 53
illumination. Rise times for CdS cells can exceed 35 ms. However, the fact that photocells are slow to respond electrically to changes in illumination is of no consequence given that the robot is even slower to respond physically to changes in commanded velocity. The robot responds slowly because of physical limitations imposed by mass, motor torque, and so on. Photocells are two-terminal
Figure 4—The RoCK implements a low drop-out linear regulator to maximize battery life. SW2 switches power to the logic supply and motor driver. A voltage detector monitors the 5-V supply and resets the microcontroller during a low-voltage condition.
devices that their resistance inchange response to light—more light means lower resistance. Each of the RoCK’s two photocells is connected in a resistive voltage divider such that increasing illumination causes increasing voltage on the signal line. The photocells are mounted at the front of the circuit board; one is angled to the left and the other to the right. Thus, the differential signal between the left and right photocells can be used to guide the RoCK toward or away from light.
OBSTACLE DETECTION The obstacle detection system is composed of two IR emitters connected in series and two IR receiver units connected independently. Because current requirements are low, the emitters are driven directly by AVR line PD7 (OC2). The active low signals from the left and right IR receivers are connected to lines PD2 and PD3 respectively. The emitters shine IR radiation diagonally outward from the robot toward the left and right. If an obstacle is present, some of the radiation is reflected back into one or both receivers. An active signal from a receiver indicates an same obstacle is presentthat on the side of the robot as the receiver. Active signals from both detectors suggest that an obstacle is directly ahead.
54
Issue 142
May 2002
The IR receivers are the same as those used for detecting remote control signals for TVs and other consumer electronics devices. The detectors have a built-in lens, photo diode, automatic gain control amplifier, band-pass filter, and demodulator. To function properly, the IR receivers must see an infrared signal with a 38-kHz carrier modulated at around 1 kHz. AVR Timer/Counter 2 is used to generate the 38-kHz carrier signal automatically. Timer/Counter 2 is configured to count up to a number corresponding to a half period of the desired 38-kHz frequency. When the counter matches this number, line PD7 toggles and the counter resets.
loop superimposes the 1-kHz modulation on the 38-kHz carrier signal by alternately activating and deactivating the connection between Timer/Counter 2 and line PD7. The connection is switched approximately every 500 µs.
Code in the RoCK’s main software
Another goal was minimal quiescent current consumption. We wanted a device capable of being interfaced to the AVR’s internal PWM generation hardware. And, it should provide bump sensing and over-current protection. The last requirement regarded cost: less than $1.50 in 1000-unit quantities. One of the motor-driver IC favored by many hobby robot experimenters is the Unitrode/ STMicroelectronics L293D. The L293D is
MOTOR DRIVER The motor driver has been one of the more difficult design challenges presented by the project. After some experimentation, we settled on the following specifications. We required dual-channel with a maximum continuous current of 500 mA per channel. The input voltage range had to be 3–15 VDC.
appealing because can be configured as a it dual H-bridge driver, comes in a DIP16 package, and is available for less than $1.50. Also, the L293D Figure 5—A pair of IR detectors and emitters are combined to form a wide-angle collision detection sensor at the front of the robot. CdS photocells enable light level detection behaviors. requires minimal exterCIRCUIT CELLAR®
www.circuitcellar.com
nal parts. The first two versions of the RoCK utilized this chip. The main shortcoming of the L293D is quiescent current. In the worst case, quiescent current draw is 60 mA for the logic supply and 24 mA for the motor battery supply. The L293D alone would discharge a standard 9-V alkaline battery in a few hours, which we deemed unacceptable. The L293D also failed to meet our minimum motor battery voltage requirement. With the L293D ruled out, we searched for other ICs that might bet-
duce increased torque. This torque results in increased current draw in response to the additional load created by the robot pushing against the obstacle. By monitoring the total motor current draw, the RoCK can detect collisions with obstacles. Current draw is determined by measuring the voltage drop across the PTC fuse. Here’s how it works: the larger the current drawn by the motor, the higher the voltage drop across the PTC. The initial resistance of the PTC is specified to be 0.07 Ω to 0.25 Ω
ter fit the requirements for theThe commercial version of the RoCK. Vishay Siliconix Si9986 came closest, matching all of our requirements except cost—over $4 for a pair. Frustrated by the lack of an appropriate chip we decided to design a motor driver made of discrete transistors. We determined that a bipolar transistor design would be adequate for our low current requirements. A bipolar-based design would also be less expensive and avoid other complications of a MOSFET design. Details of the discrete bipolar motor driver we settled on and the process we followed to design it will be presented in a future article. The motor driver is protected from
depending on whether or not the fuse has been previously tripped. You can connect the RoCK to a variety of different-sized motors with varying current requirements. Thus, to ensure reliable collision detection, the RoCK must provide the ability to adjust the current trip point. This is accomplished by using a potentiometer voltage divider to form a user-set current trip point reference voltage. The reference voltage is connected to the negative AVR comparator input, and the voltage drop across the PTC is connected to the positive comparator input. When the current exceeds the user set point, the processor detects a collision. (Software filters out momentary over-current conditions.) Diode
to thePB6, RoCK’s memory.program Lines PB5, and flash PB6 plus *RESET are provided on the header for this purpose. We’ve now seen many of the gritty details of the RoCK’s electronics. In the next issue we’ll delve into what is perhaps the RoCK’s most distinguishing feature—its behavior-based programming scheme. I
excessive current draw by a 1.25-A positive temperature coefficient (PTC) fuse that can be reset. The fuse is over-sized to prevent nuisance trips and it protects the motor driver from two of three possible fault conditions. A fault condition opens the fuse only if the fault current flows through the fuse. This condition occurs when the motor leads are shorted together or when one of the leads is shorted to the battery positive rail while that lead is being driven low. The fuse will not open if one of the motor leads is shorted to the battery ground while it is driven high. In this case the fault current does not flow through the fuse. A shorted motor lead is the most
D11 limits the voltage present at the AVR’s input to a value no greater than a pair of diode forward voltage drops. This design protects the AVR from the higher-than-logic-level motor voltage that could damage the AVR. Resistor R42 and capacitor C12 help filter out spurious current spikes.
studied physics at MIT and received an BS in 1975 and an MS in 1978. He took a trip around the world, worked at the MIT Artificial Intelligence Lab, and is now senior roboticist at iRobot Corp. You may reach him at [email protected].
common fault condition. Thelevel chosen design provides a reasonable of protection against user faults, without excessive complexity. Total motor current is monitored to detect collisions. When the robot collides with an obstacle, the motors pro-
Expansion provided viaI/O the Auxiliary I/Oability header.isEight digital lines (PC0–PC7) and two lines that can be configured as digital I/O or analog inputs (PA6 and PA7) are present on this header. Lines PC0 through PC3 are shared with the LEDs.
w w w .c ir c u it c e ll a r .c o m
LAST ITEMS Each of the logic and motor batteries is connected in a voltage divider network. The center tap of the voltage dividers connects to lines PA2 (ACD2) and PA3 (ACD3). Code in the RoCK’s main loop polls the ADC and stores the battery voltages for other code to examine.
® C IR C U ITC E L LA R
MOT_PWR Dual-channel motor driver
PTC resettable fuse Rmin = 0.07 Ω Rmax = 0.25 Ω (Post trip)
R42
1 F
100k 5 2 2 1 1 D C M S
1
MOT_CURRENT
3 D11 2
Figure 6—The RoCK’s motor driver has built-in short circuit detection and also provides collision detection through motor current monitoring.
The Advanced Programming Header enables the experienced user
Authors’ Note: We plan to offer RoCK for sale. Please check our web site, www.wirz.com/rock/, for availability and additional information. Joseph L. Jones grew up in a small town in the Missouri Ozarks. He
Ben Wirz also grew up in a small town in the Missouri Ozarks. He studied physics and electrical engineering at Washington University in St. Louis, and graduated in 1997. He is currently employed as a senior electrical engineer by iRobot in addition to running his company, Wirz Electronics. You may reach him at [email protected].
SOURCE AVR AT90S8535 Microcontroller Atmel Corp. (408) 441-0311 Fax: (408) 436-4200 www.atmel.com Issue 142
May 2002 55
APPLIED PCs Fred Eady
Taking a Swim with Atmel’s STK500
Ready to dive in and take a closer look at a few of the ATmegaxxx offerings from Atmel, Fred found no better place to start than with the starter kit. He found that there’s plenty of processing power and before long, he was into the deep Atmel-blue realm of embedded.
l
ike a shark, I am constantly on the prowl. Sharks are at home in the water. I swim the oceans of technology hoping to find yet another interesting and useful embedded device. Shark food comes in a wrapper of scales. My sustenance is contained inside anti-static bags packed in cardboard boxes adorned with UPS and FedEx labels. If your fins and teeth look like mine and your food comes from the back of a delivery truck, you’ll definitely want to join me as I venture into Atmel-blue waters.
Issue 142
May 2002
characters You mayper be packet. thinking that I’ve lost it and that you can write code to push the message into the pipe on the fly or conjure up a code-decode data compression scheme and thus erase the buffer memory constraint. That’s nice, but keep in mind that nothing is free in the world of embedded computing. To build those dynamic messages in an SRAM-constrained microcontroller, you’ll use more program memory bytes to compensate for the lack of buffer SRAM bytes. And that’s why my eyes are on the Atmel ATmega16 and the ATmega163. Both devices contain 16 KB of selfprogrammable flash program memory and 1 KB of internal SRAM. Another feature that tickles my shark senses is the ATmega’s affinity for applications written in the C language. The ATmega16 and ATmega163 are medium-sized fish, but in deeper waters lurks the ATmega128 with 128 KB of program flash memory and 4 KB of SRAM. Right now I’m fishing with
IN THE BEGINNING Most manufacturers offer a starter kit and as the name implies, it’s a good place to start if you’re not familiar with the company’s products. It just so happens that I have an Atmel STK500 starter kit here on the Florida room bench. Since I began employing the services of small microcontrollers on the Internet, I’ve been constantly lookingamounts for microcontrollers ample of RAM and with program memory that can house a robust Cbased Internet application. A lot of people talk about how they’re able to stuff Internet protocol stacks into tiny microcontroller mem-
56
ory spaces. Even though the protocol stack can exist and work in the confined memory spaces, the dynamic data payload that’s transferred from these micro-sized protocol stack implementations is relatively small. There just isn’t enough SRAM payload buffer area to build a large dynamic message and just as little space left in the program memory to “can” a set of similar messages. The simple fact is that you need substantial microcontroller SRAM resources if you want to dynamically send more than a few
CIRCUIT CELLAR®
Photo 1—The color-coding scheme on the Atmel STK500 starter kit assumes you were present the day your kindergarten teacher taught the basic colors. Color coding the numerous sockets and programming headers eliminates some of the confusion, as the STK500 is one busy piece of electronic equipment. www.circuitcellar.com
Photo 2—The AVR Studio panel looks barren when there are no files or projects open. However, its ability to interface and control the target AVR is
the target AVRs reside. You can program a variety of AVRs in these color-coded sockets and then run the freshly programmed application without having to move the target AVR. Each family of AVRs has a different set of programming pins and possibly a different programming algorithm. To accommodate the pro-
demonstrated by its invocation of the STK500 programming window. As we modeSTK500 differences, go further, the importance and power of the AVR Studio will become obvious. gram the Atmel
development board light tackle in a johnboat, so we’ll only associates a color-coded set of proconcern ourselves with the ATmega16, gramming header pins with a similarATmega163, and AT90S8515. ly colored set of target AVR sockets. The AT90S8515 comes mounted on The STK500 board has provithe Atmel STK500 and is loaded with sions for in-circuit serial proa blink-the-LEDs test program. You gramming (ISP), high-voltage serial programming, and highmay be familiar with the AT90S8515 because it’s the microcontroller that voltage parallel programming. powers iReady’s µInternet device. High-voltage serial programMy immediate goal is to bring full ming is used on the smaller C-based Atmel microcontroller capadevices that don’t have enough bility to the table and bring you along pins to be programmed with the for the ride. As I get deeper into parallel method. The “high voltage” is actually 12 VDC and is Atmel waters, I’ll trade in the flat-bottom boat for an ocean-going model to usually applied to the RESET pin go after the really big fish. of the AVR. In addition to the
THE ATMEL STK500 The meat of my Atmel STK500 starter kit is shown in Photo 1. The AVR-supporting electronics are physically and logically separated into three distinct areas on the printed circuit board. The most colorful area is where
section thepopulated. STK500 development board isof well Without going into component-by-component detail, I can tell you that the master microcontroller is responsible for generating the VTARGET and AREF voltage
target AVR sockets, jumpers to Photo 3—The two larger ribbon cables are connecting the include or exclude target AVR LEDs and push-button switches to the AT90S8515’s I/O ports operating and reference voltages, B and D. The smaller ribbon cable enables ISP programming oscillators, and crystals are also using the AT90S8515’s internal SPI interface. found in the color-coded area. All of the AVR socket signals are levels using PWM outputs that are brought out to expansion headers in passed through low-pass filters to the case you have bigger plans than the adjust pins of a couple of LM317 linSTK500 development board ear voltage regulators. A master clock can handle on its own. for the AVR targets also srcinates in A set of eight LEDs and this area of the board. corresponding push-button The DE9 shell connectors imply switches are located at the serial communications capability, and end of the board opposite a MAX202 does the RS-232 voltage the 9-pin D shell conneclevel conversion that allows the tors. There are also headers STK500 development board to attach for target AVR I/O ports, to a desktop PC running AVR Studio. the spare RS-232 port, and Atmel likes to call AVR Studio the
Photo 4—All I needed to do was load a live file and almost all of the AVR Studio lights came on. The AVR Studio did not sense a hardware emulator or STK and automatically reverted to Simulator mode. w w w .c ir c u it c e ll a r .c o m
button bank, and the 10-pin cables are also used in high-voltage programming mode. A 6-pin jumper cable is included to patch the 6-pin ISP programming header into the AVR socket farm. The AT45D021 communicates using SPI and there are three sets of two-conductor patch cables to make that connection. The spare RS-232 channel is also a two-conductor patch. The peripherals and the master microcontroller (an AT90S8535) can be found at the end of the board that sports the DE9 shell connectors. This
the AT45D021 2-Mb Flash. A collection of Datainterconnect cables is includ ed to patch in the AVR ports and peripherals. Two 10-pin jumpers are used to connect I/O ports to the LED/push® C IR C U ITC E L LA R
front-end software. Although I’m primarily interested in getting the ATmega16 online, I decided to keep the AT90S8515 socketed and run the LED test. I pressed each of the eight push buttons and with each push got a different light Issue 142
May 2002 57
pattern on the LEDs. On my second run through the push buttons, I noticed that the seventh push button did nothing. When there’s potential trouble, it’s time to go against the grain and read the User Guide. The final pages of the guide hold the code for the LED demo, and there I found out that push button number seven is not included in the LED algorithm. Satisfied that my STK500 development board was in good working order, I went to Atmel’s
The final uploaded file location is specified in the Flash panel of the STK500 programming window. A click on the Read button in the Flash panel turns the green STK500 board status LED yellow while the contents of the ’8515 are read. The debug window containing the hex and disassembled code from the ’8515 in Photo 4 confirms that push button number seven does nothing in the blinky demo code. AVR Studio opens up memory, processor cycles, I/O states, regis-
web site andofdownloaded the latest version AVR Studio.
ters, even terminal window. and Now thata you have aI/O basic idea of how the AVR Studio and STK500 board work together, let’s move beyond blinking LEDs and assembler mnemonics and swim toward deeper water.
AVR STUDIO
As of this writing, the latest ver- Photo 5—This small program demonstrates that there is power behind sion of AVR Studio is V.3.53. The the simplest of statements. It’s obvious that real embedded programAVR Studio is an integrated devel- mers solving real-world problems wrote the ICCAVR C compiler. opment environment (IDE) that consists of an editor, a project manager, AVR Studio V.3.53 is designed to enable IMAGECRAFT AVR C COMPILER an assembler and compiler interface, a the Atmel STK500 board without the Just like many of you, I cut my simulator, and a debugger. The AVR need for any additional software. AVR embedded teeth writing assembler Studio editor is capable of being couStudio also includes firmware to update applications. Then, one day I decided pled with almost any AVR compiler the development board and AVR into try C on an important embedded and C or assembler source code can be circuit emulators when necessary. AVR project and I’ve never returned to pure edited in the debugger source window. Studio checks the attached device’s assembly coding. The problem is, with If AVR Studio recognizes anything firmware level and prompts the user if C you can choose the wrong compiler that is hanging off the PC’s serial port, a firmware upgrade is required. for your needs. With that in mind, I the program automatically puts itself I’ll use some available resources to began searching for a suitable AVR C in a mode to accommodate the serialbring AVR Studio to life and demoncompiler on the Internet. ly attached peripheral. For instance, AVR Studio can sense the presence of my Atmel STK500 development board or an emulator and act accordingly. To keep things simple, the interface for the AVR Studio simulator is identical to the hardware emulator interface.
Photo 6—The AVR Fp & Calc Tool program also calculates the value to reload into the timer count registers in case you want to generate an interval with that method. I played with the Baud Rate Calc to get an idea of how fast I could run a serial port with a 32-kHz clock.
58
Issue 142
May 2002
strate some of the concepts I’ve discussed. The larger AVR Studio panel you see in Photo 2 is the first thing you see when you invoke the AVR Studio program. At this point, my Atmel STK500 development board is connected to a PC via the RS-232 CTRL connector on the board. As you can see in Photo 3, I have also strapped the ISP6PIN header to the red SPROG3 header because the AT90S8515 resides in a red socket in the AVR target area. A mouse click on the AVR IC icon in the AVR Studio tool bar invokes the STK500 programming window. As you can see, I’ve chosen the AVR target to be the AT90S8515. I’ve strapped the STK500 development board ISP Programming mode and havefor selected that mode in the STK500 programming mode panel as well. I’m not going to program the AT90S8515. Instead, I’m going to read the demo code it contains into a file called blinky.hex. CIRCUIT CELLAR®
I wanted an AVR C compiler that could handle all of the AVR families without having to purchase extra cost modules or build kludgy workarounds. It would also be good if the AVR C compiler supported the STK500 development board directly. I don’t
Photo 7—This is really simple to use. It even includes an option to automatically program the target part after a successful compile. www.circuitcellar.com
check out what’s new at www.saelig.com!
$ 85 through ADC-216 16-bit $799—display scope, spectrum and meter simultaneously. Connect to PC parallel port and start gathering/displaying data immediately!
ADC-10 8-bit
www.drdaq.com
DrDAQ plugs into a PC for useful datalogging at school, college, industry. Built-in sensors for light, sound, temp. or add pH sensor and run one of the many suggested
• Envir oMon temperature logging/alarm system standalone or with PC.
• TH-03
tiny multitasking computer systems for quick project development. Powerful features and low prices make Tigers a number one choice for developers: super-fast development cycle, high reliability products, >100,000 instructions/s, up to 38 I/O lines, A/D, D/A, I2C, SPI, , text/graphic LCD interface, up to 50,000 lines of BASIC, RTC/watchdog timer. Easy connection and software for Expansion Modulesfor CANbus, TCP/IP for net-access, opto-I/O, 64 analog inputs, 64 digital outputs, high-current outputs, etc.
TIGER Starter Kits start from $159!
ADC-212/100
$1015!!
BIT ® power & data on two-wire control network
Industry-standard card for PC’s ISA/P-port/PCI versions 2-6V I2C bus versions • Master, Slave or Bus monitor • Control or program I2C devices
NEW! Euroquartz filters/crystals!
2-year self-contained DATALOGGERS for volts, switchclosures, events, flow, pressure, etc. See www.abidata.be for details
ICA90/93LV - PICA90/93LV PCI90/93LV
- from $299!
“ Ho
I2 C” w to . com lig
www. sae
NEW! 9p-9p K3-ISOL - $129!
BASIC Tigers are
12-bit 100Ms/S dual-ch scope adapter
• Plug directly into PC — self powered! • Drive any RS422
thermistor-
to-PC converter • TC-08 8x thermocouples
science experiments! - only $99!
or RS485 devices. • Send control and data 100s of feet! K422/K485, 25pin > 9pin . . .$69 K2 9pin > 9pin . . . . . . . . . . $69 Isolate RS232/422/485 signals K4xx-ISOL 25pin self-powered . . . . . . . . $139
NEW!!
W!
Sg GL oPg g i n
NO
• Store analog/digital /GPS or CANbus data on FlashATA cards read on your own PC! • > 100 customizable software modules— finish REALLY quickly. • 8ch 10bit A/D, 33 I/Os, 2I C, 2 x RS232, interrupts, sleepmode, pre-emptive multitasking, easy to attach LCD or keypad. • CANbus adapter—recompile or log data over huge network!
Saelig Co. Inc. 585-425-3753 • Fax: -3835
www.saelig.com • [email protected]
Customer list inc: Intel, Compaq, Philips, NEC, Kodak, Nokia, US Military, Microsoft, Dell, Xerox, Universities, T.I., Dalsa, Harris, Litton, Sony, J&J, Thomson, H-P, Agilent, etc.
by PCI/ISA/PCMCIA/PC104/ Jan z fo VME/cPCI format boards. com r all put ers Software drivers for most OS’s. CAN/Ethernet bridges, etc.
SMD PCB adapters for prototyping
USB ic’s
USB <> RS232 easily!! US232: USB <> RS232 cable $35 Saelig Company brings you unique, easy-to-use control and instrumentation products to USA, mostly from Europe, but now from worldwide. (Need USA sales help - overseas companies?) Our customers comment on our unrivalled FREE after-sales support. “Hi - I’m Alan - you can email me at [email protected] for free advice for your control or measurement problem.”
plan to delve into the 8-pin AVR devices so lack of support for those devices wasn’t a problem. I didn’t have to look far. ImageCraft’s ICCAVR supports all of the AT90Sxxx and ATmega devices including the FPSLIC, but not the tinyAVRs and ’1200, which are supported by another ImageCraft product, ICCTiny. Having used other embedded C compilers, I knew that I needed inline assembly capability and strong string handling support. Because the AVR targets will be performing bit and
Take a look at the AT90S8515 program 8515intr.c in Photo 5. At first glance, the program seems simple enough. What you don’t immediately see is the functionality packed into these seemingly simple lines of text. The first line of code is a standard include statement referencing an include file filled with AT90S8515 I/O and register definitions. What you don’t see is a reference to another include file named io8515v.h. The C header files io8515.h and io8515v.h have been designed to
The main() function simply sets up the AT90S8515’s port B, loads Timer1 with values for a 100-ms interval, enables the Timer1 Compare A interrupt, starts the timer, and runs forever. The timer() interrupt handler is called every 100 ms and simply increments the value of port B, thus producing a binary counting pattern on the STK500 development board’s LEDs. Note here that the interrupt handler function timer() is written entirely in C. Counting cycles to make delays or intervals is not one of my favorite
byte I/O operations, C compiler I chose needed to the haveAVR a good handle on that functionality as well. A robust set of AVR-specific library routines is mandatory seeing as I don’t want to write all of the standard AVR I/O routines from scratch or in assembler. As it turned out, ICCAVR offered much more than I expected. I opted for the professional version as it contains a unique Code Compressor optimizer that could come in handy when the larger AVR TCP/IP implementations come to call. The professional version also has some interesting features that are being developed for AVR Studio. These additions will be available via a maintenance upgrade when they show up online.
define consistent global names forthe interrupt vector numbers and use AVR datasheet names for clarity. For instance, Listing 1 is a definition table for the AT90S8515 interrupt vector numbers taken from the C header file io8515v.h. The second line of code,
things to doObviously, when it comes tocan pro-see gramming. as you in Photo 6, Jack Tidwell and I have something in common. Thanks to Jack, the values loaded into the compare registers to affect the 100-ms interval were not computed by hand. ICCAVR has a built-in calculation tool that does it for you. The AVR Fp & Calc Tool is shown providing the compare register values for a 100-ms interval with the STK500 board’s 3.69MHz target clock prescaled by 1024. The window you see in Photo 7 is yet another reason I chose the ICCAVR AVR C compiler. After the LEDcounting code was compiled, I clicked on Tools>In System Programmer on the ICCAVR tool bar, selected the STK500
The ImageCraft AVR C compiler has its own IDE that supports long file names and acts much like the AVR Studio IDE in that there is an integrated project manager, C editor, ANSI terminal emulator, and an application builder to generate peripheral initialization code. ICCAVR also supports symbolic debugging in the AVR Studio. The designers of ICCAVR realized the importance of efficient string handling in embedded microcontroller applications and included several flavors of the printf function to suit differing environments. The best ICCAVR feature is the price. Even the ICCAVR maintenance prices are way below sea level. I figured I would forego discussing the blinking lights as I entered ICCAVR territory, but the ICCAVR AT90S8515 demo program uses the LEDs to make its point as well. Again, I’ll use the AT90S8515 that’s already on the STK500 development board.
60
Issue 142
May 2002
#pragma interrupt_handler timer:5
generates the interrupt vector code based on the interrupt vector number found in io8515v.h. The pragma statement also declares the function timer() as an interrupt handler. Knowing that the timer function is now an interrupt handler, the AVR C compiler generates areti (return from interrupt) instead of a standard ret for the timer() function turned interrupt handler and saves and restores all of the registers the timer() function uses.
development board on COM1, clicked on Chip Erase, made sure my target hex file was listed in the “Manual Program Now!” panel and clicked on
Listing 1—Now, this is the way to handle code generation for interrupt vectors. I like the idea of using the actual datasheet names for the vectors. //Interrupt Vector Numbers #define #define #define #define #define #define #define #define #define #define #define
iv_RESET iv_INT0 iv_INT1 iv_TIMER1_CAPT iv_TIMER1_COMPA iv_TIMER1_COMPB iv_TIMER1_OVF iv_TIMER0_OVF iv_SPI_STC iv_UART_RX iv_UART_RXC
1 2 3 4 5 6 7 8 9 10 10
#define #define #define #define #define #define
iv_UART_DRE iv_UART_UDRE iv_UART_TX iv_UART_TXC iv_ANA_COMP iv_ANALOG_COMP
11 11 12 12 13 13
CIRCUIT CELLAR®
www.circuitcellar.com
Photo 8—The STK501 development board comes with a dedicated JTAG header. The STK500 development board has no such header. A 10-pin male header with pigtails comes with the JTAG ICE to allow it to be connected to the STK500 development board and to any JTAG-capable AVR. The JTAG port resides on four pins of port C on the ATmega16.
the Program FLASH/EEPROM button. A few seconds later, the AT90S8515 on the STK500 development board took control of the LEDs and the familiar binary counting pattern was blinking away.
A SURPRISE PACKAGE It looks like I have a great start toward developing embedded applications with the Atmel AVR parts, but I want to clear something up. I failed to mention the differences in the ATmega16 and the ATmega163 parts I will be using. Both parts are essentially identical with the exception of the inclusion of a JTAG interface on the ATmega16. The ATmega16 JTAG interface is IEEE standard 1149.1 compliant and includes the boundary-scan capabilities set forth in the standard. The AVR JTAG interface opens debugger access to everything internal to the ATmega16. With the right hardware, you can read and program the flash memory, EEPROM, fuses, and lockbits of the ATmega16 through the JTAG port (see Photo 8). The version of AVR Studio I downloaded earlier is designed to work hand in hand with the JTAG ICE. The JTAG ICE also directly supports the STK500 development board. I took a quick looksupport at the ICCAVR library and there are files for the ATmega16, ATmega64, and the ATmega323, all of which offer JTAG capability. JTAG ICE operation is a bit different than that of more familiar emulators. The standard microcontroller w w w .c ir c u it c e ll a r .c o m
emulator contains a special bondout device that runs the code and emulates the actual micro in hardware. Special pins and sequences allow you to extract the register, CPU, I/O, and memory debug data from the bondout device. JTAG ICE does not contain a bondout device. Instead, JTAG ICE uses the AVR on-chip JTAG port and the AVR’s built-in, on-chip debugger (OCD) to control the emulation process. With JTAG ICE, the emulation is actually code running on the target AVR microcontroller. The JTAG interface with you the AVR OCD and AVR coupled Studio gives a view into the AVR microcontroller’s inner works in real time. The JTAG ICE is an interesting piece of equipment and deserves more attention. Next month, I’ll go into detail about the JTAG ICE and cook up some AVR Internet code to show you that the union of ICCAVR, JTAG ICE, and the ATmega16 isn’t complicated, it’s embedded. I Fred Eady has more than 20 years of experience as a systems engineer. He has worked with computers and communication systems large and small, simple and complex. His forte is embedded-systems design and communications. Fred may be reached at [email protected].
RESOURCE AVR Studio Atmel Corp. www.atmel.com
SOURCES ATmega Series micros, STK500 starter kit Atmel Corp. (408) 436-4314 www.atmel.com ICCAVR C Compiler ImageCraft Creations Inc. (650) 493-9326 www.imagecraft.com iReady µInternet iReady Corp. (408) 330-4500 www.iready.org ® C IR C U ITC E L LA R
Issue 142
May 2002 61
FEATURE ARTICLE Jim Turley
Design Your Own Microprocessor
Why put a processor in an FPGA? Why not buy a real microprocessor chip and solder it down? If you’re going to use an FPGA for random logic anyway, you can eliminate the extra chip by putting the processor in the FPGA, as well. You also could experiment with different processors in your FPGA, evaluating various ones until you find the right balance of performance, size, cost, and power consumption. The most interesting prospect, of course, is modifying the processor to suit your own whims. Or, dare I say, even your own processor from designing scratch (the first CPYou)? Well, you can, and there are some good reasons why you would (or would not) want to try this at home.
A ONE-MAN SHOW For most engineers, designing your own processor architecture is a cool idea but not a practical one. A custom CPU has zero software support—no icroprocessors— tools, no compiler, no debugger, and you either love no one to turn to when bugs crop up. them or you hate You’re on your own. them. If you hate yours, Using an existing CPU, on the other it’s probably because it doesn’t do what hand, makes a lot of sense even if you want it to. Naturally, the bugs are you’re going to embed it into an FPGA the chip’s fault. Don’t you wish some- or high-volume ASIC. In fact, according one would make a processor that actuto Dataquest, the business of embed-
m
Problem with your microprocessor? Complications with micros are often the case. But, what if you designed your own that did exactly what you needed it to? Jim provides a tutorial on creating a microprocessor. The bonus: You don’t have to be Bill Gates to build it.
ally has the features you want? Ta-da! Cue Aladdin music. Your wish has been granted. Now, you can design your own microprocessor without years of studying for your doctorate in Computer Science. You can be running code on your own microprocessor before the end of this week.
ding CPUs into other chips is growing at about 25% per year and stood at about $20 billion in 2000. That’s no small potatoes. The average is 2.3 processors per intelligent ASIC (those with any programmability) and rising. There’s no shortage of processors to choose from, either. From littleknown 8-bit processors created as uniPROCESSOR FACTORY versity research projects to popular 16Although building your own foundry and 32-bit processors like the ’286, is out of reach for most engineers (it SPARC, ARM, or MIPS, the market is costs more than $1 billion just to ready and willing to supply you with upgrade an existing chip plant), it’s easy microprocessor intellectual property to make a few of your own processors (IP). Some are free (and worth every using low-cost FPGAs. Altera and penny), while others might cost you as Xilinx both encourage this behavior much as a new Mercedes. for the obvious reasons. In fact, both One high-end free core is LEON-1, a companiessoft have entered the supplying processor corebusiness designs of to encourage engineers to use more FPGA chips. Altera’s Nios (see Figure 1) and Xilinx’s MicroBlaze (see Figure 2) are both free but only work, of course, in the parent company’s chips.
62
Issue 142
May 2002
CIRCUIT CELLAR®
SPARC clone distributed by the European Space Agency. This is a real SPARC processor, created with Sun’s blessing, but without floating point capability or anywhere near the performance of Sun’s current processors. Still, SPARC has good software tools www.circuitcellar.com
(available for free) and a certain amount of appeal and prestige. LEON-1 is provided with VHDL source code (you supply the hardware compiler) and runs at 20 to 40 MHz in Xilinx or Altera FPGAs. At that speed, it would probably take you a week to boot Solaris. At the low end (and also in the free category), are 8-bit processor designs from CMOSexod and Free-IP cores. Both designs have little 8-bit processors you’ve never heard of but come with free tools to get you started. The FreeIP Project also has a 6502 core, in case
Data in
Q Instruction decoder
Program counter Effective address
Clock enable
Wait
A L U
Operand fetch
Data out 32
Q 32
Address
Read/write Control
ifetch Byte enable 4
irq
Interrupt control
irq# Reset
you’ve hankering to resurrect your oldbeen Apple II. VAutomation also sells its 8-bit V8 processor with free tools. For your money, VAutomation gives you real technical support and the warm fuzzy feeling that their processor really works. They even use the V8 in some of their own products. The company also has a 6502 as well as Z80, 8086, and ’186 cores. Now that Intel and AMD are both out of the embedded ’x86 business, soft cores like VAutomation’s may be your only way to get low-end ’x86 processors.
D 32
General-purpose processor register file
6
Clock
Figure 1—NIOS is a 16-bit processor Altera designed specifically to work in its own FPGA devices.
Any mention of the ’x86 architecture often brings up the issue of cloning. How can these knock-off processors
one? The answers are sometimes murky, but the short version is: don’t worry about it. Cloning processors is a long and honored tradition, and the ones who got there illegally generally aren’t around any more. Darwinian selection has culled the dubious ones. Legal protection on processors is a funny thing. You can’t patent an instruction set but you can copyright a processor’s mnemonics as a work of literature. Even more bizarre is the fact that it’s illegal to print a programmer’s reference manual that’s the same as, say, Pentium’s, but it’s per-
don’t violate any hardware patents, which is where Lexra, picoTurbo, Shengyu Shen, and others may have run afoul of the technology lawyers. Although you can’t patent a processor’s instructions per se, you can patent the circuits that make those instructions work. AMD, Transmeta, and other (now defunct) ’x86 clone makers have laboriously worked out different ways to get their processors to work exactly the same as Intel’s, but without using Intel’s exact circuitry. For a CPU as complex and baroque as Pentium, that’s no small feat.
exist? Are they legal? And, what liability am I exposing myself to if I use
fectly okay to make a chip that runs Pentium code. That is, as long as you
Cloning RISC processors is far easier, although not nearly as lucrative. RISC chips have, by definition, a reduced set of features so they’re naturally less complicated. That simplicity was supposed to make streamlined RISC chips faster than tangled CISC chips like Pentium, but Intel’s determination prevented that fairy tale from ever coming true. However, if you’re going to clone a processor, RISC is definitely the way to go. You can get a facsimile of a MIPS processor from OpenCores. Its “MIPSlite” core supports most MIPS instructions from a few generations back (see Figure 3). For the premier MIPS knockoff, though, you needed to go to Lexra
CLONE RANGERS
On-chip instruction memory 0–256 KB
Machine status register In s tr u c t io n b u s c o n tr o ll e r
r31 • Register file • 32 × 32 bit •
Program counter
r1
Control unit
r0 Add/ Shift/ Multiply logical subtract
Instruction buffer
On-chip data memory 0–256 KB
D a t a b u s c o n t ro ll e r
Peripherals CoreConnect OPB I/F
Interrupt
CoreConnect OPB I/F
UART
controller Off-chip memory 0–4 GB
Watchdog timer
Generalpurpose I/O
Timer/ counters
Off-chip memory 0–4 GB
Figure 2—Xilinx’s MicroBlaze, like NIOS, is an FPGA-only processor that resides in the “soft logic” of an FPGA. w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
Computing Engines. were close enough to Lexra’s the realMIPS thingcores to warrant two lawsuits from MIPS. Oddly enough though, neither suit alleged patent infringement, only copyright infringement. Until recently, Lexra dodged both suits and soldits line Issue 142
May 2002 63
of mostly MIPS-compatible cores.Now, Lexra is officially MIPS licensed and concentrates on network processors. Along those same lines, there were at least two unauthorized versions of the popular ARM architecture. A free one was available through OpenCores until last summer, when legal pressure apparently made it disappear. picoTurbo was also happy to sell you its version until it disappeared a few months ago.
YOU-BUILD-IT INSTRUCTION SETS
Photo 1—ARChitect is a program that allows engineers or programmers to design their own CPU with only a few mouse clicks.
box is a VHDL or Verilog description of the CPU. Neither company sells chips, only the recipe for the processor. Your freedom lies in your ability to adjust the recipe to suit your taste before you send your chip off to the silicon oven. You can make your chips in FPGA if you’re looking at modest volumes, or go to a big Asian foundry if you’re ready for millions of chips with your logo on them. Both ARC and Tensilica start you off with a working 32-bit RISC core that’s in the same league as ARM7,
The next giant just beyond building your ownstep processor is designing your own processor. You can start from scratch and have all the glory (and all the headaches) for yourself, or you can use one of the many do-it-yourself (DIY) kits that are available. Like Lego blocks, these DIY microprocessors can be used to build an amazing array of completely different products. The two big leaders in the area of user-configurable microprocessors are ARC International and Tensilica. ARC (not to be confused with ARM)
is the older of the two and has more customers. Tensilica is based in Silicon Valley and seems to be catching on well. There are minor differences between ARC’s ARCtangent and Tensilica’s Xtensa processors, but they’re more alike than different. Both are 32-bit processors that you can tweak, twist, and modify to create your own private custom 32-bit CPU. You don’t have to start from scratch either, because both processors work right out of the box. In this case, the
MIPS R3000, or most other mid-range 32-bit processors. These cores start out small enough to fit into all but the smallest parts from Xilinx or Altera. Both processors have the usual arithmetic (add, subtract, multiply), logical (shift, rotate, exclusive-OR), and flow-control (branch, jump, return) features that you’d expect to see. In short, they’re completely functional RISC designs that crank out about 1.1 Dhrystone MIPS per megahertz, just like any self-respecting processor should these days.
Software DOS & Web Server On-Board Royalty free TCP/IP source code provided eRTOS available for Multitasking applications Borland C/C++ in Development Kits
µFlashTCP-EP* 10Base-T Ethernet 2 Serial Ports 7-34 VDC Rugged Enclosure w/ Industry Standard Connectors Starts at $229
Ether6 * LogicFlex* 10Base-T Ethernet 46 Digital I/O’s Programmable Xilinx CPLD Hardware Clock/Calendar Expansion Bus for Peripherals Starts at $189
µFlashTCP * 10Base-T Ethernet 2 Serial Ports 10 Digital I/O’s 3.75” x 2.50” 30% smaller than PC104 Starts at $149
10Base -T Ethernet 6 Serial Ports 1MB SRAM Rugged Enclosure Optional On Board Modem & 10Base-2 Starts at $369
products based10Base-T on the Intel 386Ex&with and an Web Server software pre-installed. NE2000 compliant Ethernet DIP DOS, socketTCP/IP to accept M-Systems DiskOnChip standard. * All
JK microsystems connects you with embedded control solutions. Our cost-effective DOS based controllers are ideal for data acquisition, networking or industrial technology applications.
64
Issue 142
May 2002
1403 Fifth St., Suite D Davis, CA 95616 USA
CIRCUIT CELLAR®
Visit us on the web www.jkmicro.com Call 530-297-6073
Fax 530-297-6074
www.circuitcellar.com
But, that’s just the basics. On top of the baseline features, you get to select from a menu of predefined, pre-tested options to extend your processor. Do you want a faster multiplier? Choose that option, and your chip will get smarter (and bigger). Do you need DSP features? Yeah, that’s in there. Do you want bigger caches or more registers? Go for it. Both companies’ cores have a dozen or so
PC PC_next
d_write
extract instructions. Few of these operations appear in mainstream processors. Other times, the goal is to compress code size. RISC, by its nature, has lousy code density, but you can get some of that back by defining your own instructions. Other times, the objective has less to do with performance and more with competitive business. Custom instructions can prevent
Address Memory_ctrl
d_read
e d co p o
_ e m cru e o ms
pc_source rs_index rt_index
Mult Control alu/shift/mult_func
rd_index
t u o _ m im
ce r u o s _ a
e cr u o s _ b
e rc u o s _ c
c n u f _ h c n ra b
ALU
regular_source a_bus Regular_bank
regular_target
Bus_mux
b_bus Shifter
regular_dest
c_bus canned options you canthem reverse engineering. choose from. Selecting can disassemble codeAnyone for a all might double the size of standard microprocessor. All Figure 3—OpenCores’ contributors have developed an open-source microprocesyour basic processor core, but sor that’s similar to a MIPS core. it takes is a few minutes that’s your choice. with a logic analyzer or ROM Both firms use a familiar point-andThe end result is a processor that’s burner. But if your processor has one or click user interface to configure the part standard, part custom. Your CPU two custom instructions, disassembling processor. ARC has a program called will be binary-compatible with other code becomes much tougher. Even if ARChitect and Tensilica’s interface is ARC or Tensilica processors, but with your custom instruction is an NOP, no available through its web site (see additions you define. What would you one knows that but you and sprinkling Photo 1). In either case, you click on add to 30 years of computer architeca few of them in your software will the options you want, and after a few ture that hasn’t already been done? confuse the most diligent code spy. minutes, your custom processor Quite a lot, based on the evidence of However, if designing your own design is generated for you, complete customers who have done this. processor isn’t advanced enough for with software tools to program it. Most users look for performance you, try this out. New tools can improvements, either by collapsing design the processor for you based on OH, MY VERY OWN INSTRUCTIONS frequently used sequences of instruca vague wish list. They’re not perfect, You don’t see what you want on the tions or by designing custom instrucand they’re still at an early stage. But, menu? Now the real fun begins. Both tions that do something unusual. If we’re gradually approaching the goal
companies let you go beyond the canned options and design your own features into the processor. You don’t like the way the CPU handles overflows? Change it. Do you want to encrypt your code with a couple of funny instructions nobody can figure out? The limit is your creativity. You can extend the ARCtangent using normal Verilog or VHDL to define hardware extensions to the processor. When ARChitect configures the ARCtangent core, it stitches in your custom instructions along with it. As long as you’re familiar with either VHDL or Verilog, it’s pretty straightforward. Tensilica does essentially the same thing but uses its own language, called extensions (TIE).Tensilica With TIE,instruction you define what you want the new features to do, then upload the definition to Tensilica’s web site. Your wishes are integrated into the final design and downloaded back to you. w w w .c ir c u it c e ll a r .c o m
you’re handling packed 8-bit pixels, a set of parallel SIMD add and multiply instructions would be helpful. If you’re handling 24-bit audio samples, saturating arithmetic (math that clamps at certain levels) is a boon. Encryption guys love bit insert and
E D IF
SOFTWARE IN, HARDWARE OUT Celoxica has a hardware-design tool called Handel-C (see Figure 4). It’s a language somewhat similar to Verilog
Executable specification
External IP cores V H D L B e h a v i o ra l m o d e l
of a machine that executes the program “do what I’m thinking.”
RTL/VHDL VHDL
HDL EDIF simulator
Embedded software
DK1 Design suite E D I F
Handel-C simulator CO– simulation
Instruction set simulator CO– simulation Compiler
VHDL synthesis
Vendor place and route tools
Hardware system
Input
Figure 4—Celoxica’s Handle-C is similar to C, but instead of producing a program, it creates a circuit design. ® C IR C U ITC E L LA R
Issue 142
May 2002 67
systems handle different tasks at different times. One moment you’re decompressing audio streams, the next you’re handling an interrupt, and the next you’re accepting user input. It stands to reason that whenever one part of the circuit is working the other parts must be idle. This is often true, but there’s nothing you can do about it. Hardware systems have always been created from a superset of all the functions required over the life of the product, rolled into one. If RC takes off, that might change. For example, future of cell phones may use halfgenerations the transistors to do 10 times the work. Fewer transistors may be all that’s needed, if none are wasted on functions that aren’t required right now. Transistors would simply be on call; available for whatever was required at the moment. Programming such a beast would be a whole new challenge. How do you write code for a moving target? According to RC partisans, you don’t. In Elixent’s case, there is no software as we know it. The srcinal program was simply the input function, a way to define what you wanted. The output function was the hardware itself, which has all the program information it needs. Cue Twilight Zone music. I Jim Turley is an independent analyst, columnist, and speaker specializing in microprocessors and semiconductor intellectual property. He is the former editor of Microprocessor Report and Embedded Processor Report and host of the annual Microprocessor Forum and Embedded Processor Forum conferences. You may write to him at [email protected] or visit his web site at www.jimturley.com.
RESOURCES VAutomation ARC International (603) 882-2282 www.vautomation.com
CMOSexod www.cmosexod.com/freeip.htm Elixent Ltd. +44 117 917 5770 w w w .c ir c u it c e ll a r .c o m
Fax: +44 117 917 5779 www.elixent.com
Lexra Inc. (408) 573-1890 Fax: (408) 573-1898 www.lexra.com OpenCores www.opencores.org/projects
SOURCES ARCtangent, ARChitect ARC International (603) 882-2282 Fax: (603) 882-1587 www.arccores.com
Handel-C Celoxica (408) 626-9070 +44 (0) 1235 863 656 Fax: (408) 626-9079 Fax: + 44 (0) 1235 863 648 www.celoxica.com LEON-1 Distributed by The European Space Agency +33 1 5369 7654 Fax: +33 1 5369 7560 www.estec.esa.nl/wsmwww/leon/ ST210 Agilent Technologies (650) 752-5000 http://we.home.agilent.com STMicroelectronics (617) 225-2066 Fax: (617) 225-7918 http://us.st.com
Jazz processor Improv Systems, Inc. (978) 927-0555 Fax: (978) 927-0999 www.improvsys.com Xtensa Tensilica (408) 986-8000 Fax: (408) 986-8919 www.tensilica.com The Free-IP Project XESS, Corp. (919) 387-0076 Fax: (919) 387-1302 www.free-ip.com www.xess.com. ® C IR C U ITC E L LA R
Issue 142
May 2002 69
FROM THE BENCH Jeff Bachiochi
You’re Not Alone
directly for steady-state isolation. Opto devices work well in this scenario. An opto device does require a chunk of current to operate and the transfer ratio of input current to output current will usually require a trade-off of speed for drive current. This trade-off is not a problem until you want to transfer information at high speeds. Most opto devices have minimum TON/TOFF times in the microsecond range. A new device in the isolation flurry takes a step back into the magnetic domain. NVE Sensor Engineering uses giant (GMR) sensors tomagneto transfer resistive information using the magnetic fields produced by current in a conductor.
Dealing with Isolation
MAGNESOLATION
w
Jeff hasn’t turned into a self-help writer, but you can help yourself by following along as he outlines the challenges and effects of isolation. Knowing what the options are will help keep your next project on track.
hen I think of isolation, I think of Robinson Crusoe and Friday or in more recent times, Tom Hanks as Chuck Noland. When I think isolation in the electronics context, I think of the transformer. For years, transformers have been used to isolate signals. Magnetic properties transfer information without an electrical connection between primary and secondary windings. On most transformers, it’s the plastic bobbin that holds the primary and secondary windings separated that creates the isolation barrier. More recently, opto devices have become a popular method of obtaining isolation. As you can see in Figure 1, opto devices rely on light (or the absence of light) to transfer information between the physically separated primary (input) and secondary (output). Although the transformer is inherently a bidirectional isolation device, most isolation application requirements are unidirectional.
LIGHTSOLATION Opto devices have the advantage of operating down to DC whereas transformers are specified at some AC bandwidth. From an isolated control point of view, transformers can’t be used
70
Issue 142
May 2002
CIRCUIT CELLAR®
You may already be familiar with Hall effect devices, which can be used to measure the strength of a magnetic field. The Hall effect is the presence of a voltage produced across (x-axis) a current-carrying conductor (y-axis) as a result of exposure to a magnetic field passing through the conductor (z-axis). This differs from the GMR effect. The GMR effect is a change in a thin film nonmagnetic conductive layer’s resistance caused by an external magnetic field overcoming the parallel but opposing magnetic coupling of adjacent magnetized layers (see Figure 2). You’ll remember that the spin of electrons in a magnet are aligned to produce a magnetic moment. Magnetic layers with opposing spins (magnetic moments) impede the progress of the electrons (higher scattering) through a sandwiched conductive layer. This arrangement causes the conductor to have a higher resistance to current flow. An external magnetic field can realign all of the layers into a single magnetic moment. When this happens,
LED
Signal transmitted by photo stream
VCC
Isolated output
A 1″ Galvanic isolation by bulk dielectric Photo detector
Figure 1—Optoisolators rely on physical separation between the LED transmitter and photo detector for isolation. Data is passed via photons (or the lack of). www.circuitcellar.com
High-resistance state
a)
Magnetic moment orientation
++B++ A ••B••
No external field
Low-resistance state
b)
++B++ A ++B++ Applied external field
Figure 2—In both a and b, the A layers are the non-
deposited on a layer between the GMR sensors layers and the thick film magnetic shielding layer (see Figure 4). Current through this coil layer produce the magnetic field, which overcomes the antiferromagnetic layers thereby reducing the sensor’s resistance. NVE obtains isolation specifications of 2500-VRMS using its manufacturing process. Unlike typical microsecond TON/TOFF times of optoisolators, isoloopisolators are typically 1 ns, which is more than 1000 times faster than its light-based rival. The isoloop-isolators
VCC Planar coil
Signal transmitted by magnetic field
VCC
H
Isolated output
A
1″ Galvanic isolation by thin-film dielectric
GMR Resistors
Figure 3—In a GMR, isolator data travels via a magnetic field through a dielectric isolation to affect the resistance elements arranged in a bridge configuration.
for an isolated power supply circuit (see Figure 7). C&D Technologies makesan isolation transformer specially designed
also have identical TON/TOFF times, which produce no pulse-width distortion as is the case with many optoisolators having differing T ON/TOFF times. Propagation delays are less than10 ns with inter-channel skewing of less than 2 ns. Isoloop-isolators have up to electron flow will be less effected four channels per package in a variety (lower scattering) by the uniform spins of device direction configurations. of the adjacent ferromagnetic layers. These standard devices are great for This causes the conduction layer to bus isolation, serial ADCs and DACs, have a lower resistance to current flow. and communication isolation. Figure 5 Note that this phenomenon takes place shows typical RS-232 isolation. only when the conduction layer is thin Specialty devices include isolated RSenough (less than 5 nm) for the ferro422 and RS-485 communications magnetic layer’s electron spins to affect transceivers (see Figure 6). the conductive layer’s electron’s path. POWER ISOLATION To put this phenomenon to work, NVE uses a Wheatstone bridge configIsolation can’t be achieved using a
for the MAX253. The 78250 series and transformer is available in 1500-V 4000-V isolation from Mouser. I made prototypes of the circuits in Figures 6 and 7 to create an isolated RS-485 transceiver for use with a microcontroller. Notice the surface mount IL-485 mounted on a dip header in Photo 1. Pins 4, 5, 12, and 13 of the IL-485 are soldered to the header and the other pins are wired to the appropriate dip header pins. Using a dip header for surface mount parts makes them easier to handle and reuse elsewhere (after you get past the surgical wiring). Although the IL-485 is only available in the surface mount variety, the other devices are through-hole components. I measured typical required currents in
uration of four GMR sensors (see Figure 3). Their manufacturing process allows thick film magnetic material to be deposited over the sensor elements to provide areas of magnetic shielding or flux concentration. Various op-amp or in-amp configurations can be used to supply signal conditioning from the bridge’s outputs. This forms the basis of an isolation receiver. The isolation transmitter is simply coil circuitry
the isoloop IL-485 circuit in Figure 6 and found the isolated RS-485 side required considerably less than 50 mA without any load on the twisted pair. Using the isolated voltage to supply the termination load adds 50 mA to the load requirements of the MAX253 isolated supply. The MAX253 circuit easily supplied this current at just over 5 V after the Schottky rectifier drop, thanks to the 1:1.31 winding of the transformer. No regulator is needed because this is
magnetic conductive layer and the B layers are adjacent magnetic layers of opposing orientation. a—Layer A is high resistance because of higher scattering of electrons flowing through it. b—An applied magnetic field realigns the magnetic moments in the B layers, resulting in a lower resistance in layer A because of a decrease in electron scattering.
Field producing coil
Spin valve resistors
Isolation dielectric
IIN
Magnetic field - H (HαIIN)
Figure 4—The magnetic field produced by the field coil of the input affects the spin of electrons in the anti-ferromagnetic layers, reducing the resistance of the bridge sensors. w w w .c ir c u it c e ll a r .c o m
common power supply. This need creates a requirement for additional circuitry beyond the signal isolation. There must be a separate power supply for the circuitry on each side of the isolation barrier. Often this will be more expensive than the signal isolation. The simplest solution might be to purchase a DC-DC converter. In this case the converter is used as an isolator instead of converting from one voltage to another. Take your time choosing a converter; if you aren’t careful you can find yourself being locked into a single-source manufacturer, especially if you choose a converter with a weird pinout or physical size. An alternative might be to build one directly on-board. Both Linear Technologies Maxim specialize in power products.and Linear’s LT1424-5 is good to about 2 W. For lower currents up to a 1-W converter, take a look at Maxim’s MAX253. Few external components are required to use the MAX253 as a transformer driver ® C IR C U ITC E L LA R
Photo 1—Mounting an SMD on a DIP header makes it easy to work with. Issue 142
May 2002 71
sary. Overlooking the more obvious safety issues (such as distances between devices) in some applications increases the potential for ground loop problems.
GROUND LOOPS When equipment using different power supplies is tied together (with a common ground connection) there is a potential for ground loop currents to exist. This is an induced current in the common ground line as a result of a difference in ground potentials at each piece of equipment. (Note: improper house wiring can cause loops when the neutral side ofground the line, or the ground, is not properly grounded.) We normally think of all grounds as being of the same potential. If this were Figure 5—The IL-712 contains Z isolators, which can easily be used with a MAX-232 for serial isolation. An addiso, there would never be a ground tional IL-712 will add isolation for hardware handshaking. loop problem. Here at Circuit Cellar world headquarters, I’ve measured a within the recommended range for the a heavy RS-485 termination. Large considerable difference between the grounds of different outlets (and differIL-485 (4.5–5.5 VDC) and well below spikes were seen on the isolated side the 7-VDC absolute maximum rating. of the MAX253’s circuitry, but a series ent phases) within the same room. The 78253 transformer from C&D choke tamed them nicely (see Photo 2). There are a number of reasons that Technologies is rated at 200 mA, so Are isolation techniques necessary? could explain these findings. It doesn’t there is plenty of overhead even with In many situations, they aren’t necestake a large difference in potential to cause ground currents to flow through a common ground connection. The potentials (and currents created) are also load related, so, most of the time, these currents will not be steady state. If sensor circuitry is based on its own ground as a reference and the system ground is not the same, you can’t expect to be able to take accurate measurements. You’d think that making the common ground heavier might be the solution. But, in many cases, this only increases ground loop current. Breaking this common ground is a better solution. However, if the common ground
Photo 2—The upper trace shows 0.5-V spikes on the isolated output of the power supply. The lower trace shows the same output after a series choke.
72
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
The embedded controller that’s out of this world. When engineers NASA’s Shuttle imagined the right controller their critical payloadin experiments, theyworking turned on to the one Space supplier with more solutions thanembedded any other supplier offor embedded controllers the world — Micromint. With over 250,000 controllers in the marketplace, Micromint has been providing innovative,turn-key solutions to the OEM market for over twenty years- from design through production,as well as packaging and shipping the final product. Our broad line of embedded controllers and turn-key solutions can turn your imagination into reality.
Visit our website@ www.micromin t.com to see our complete line of OEM Solutions.
902 Waterway Place | Longwood, FL 32750 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069
connection is broken, the differential in ground potentials remains and will affect any signal between the two pieces of equipment. You need to isolate the grounds as well as the other signals, otherwise you run the risk of exceeding the maximum or minimum allowable input specs. To eliminate ground loop problems when connecting devices using
Figure 6—The IL-485 replaces the RS-485 devices when an isolated
twisted pair network is needed. grounded supplies located on different circuits, do not make a common ground connection eliminate all of the common ground between the devices you want conloop problems between sensor and nected. Although this eliminates measurement circuitry, always power ground currents from flowing between and measure sensors with the same devices, it creates a problem for the local supply. By measuring right at the signals, which are ground referenced. sensor, lengthy leads will carry digital Take communications interfaces for data (easily isolated) rather than anainstance. RS-232 circuitry must have a log data (difficult to isolate). ground connection because it is the refThe available IsoLoop products will erence for the remaining signal lines. handle most isolation problems. BeOn the other hand, RS-422/485 uses sides the speed advantage over most differential signals not referenced to optoisolators, the IsoLoop products have a latching output. Because the outground. You can use this twisted pair connection without a common ground put state is latched on magnetic field unless there is a difference of more change (controlled by the input to the than 7 V between them. The RS-485 device), even if the power is removed receivers can withstand up to a 7-V from the input side, the output side’s
ground-referenced difference before exceeding the maximum or minimum ratings. Would you gamble with circuit failure over a 7-V spread? This is where signal isolation payoff comes into play. When dealing with sensors, ground loop currents cause changes in an analog signal. These changes often look like signal noise. A ground loop can even be caused by a mechanical and electrical (if uninsulated) connection to a grounded object being sensed. To
logic state would remain latched (memorized). This would require an extra set of latches when using an optoisolator. NVE introduced its first GMR product in 1994. These days, GMR sensors compete with Hall effect devices for many magnetic sensing applications and additional research continues on the use of GMR materials for magnetoresistive random access memory (MRAM) technology. Can you say core memory? What goes around…. I Jeff Bachiochi (pronounced BAH-keyAH-key) is an electrical engineer on Circuit Cellar’s engineering staff. His background includes product design and manufacturing. He may be reached at [email protected].
SOURCE Figure 7—Maxim’s MAX253 makes a great isolation supply. C&D Technologies has a transformer specifically for use with the MAX253. w w w .c ir c u it c e ll a r .c o m
IsoLoop high-speed digital isolators Nonvolatile Electronics Inc. (952) 996-1610 www.isoloop.com ® C IR C U ITC E L LA R
Issue 142
May 2002 75
the most interesting takes on the subject was the Seiko 7660A chip I covered in 1999 (Circuit Cellar 111). Exploiting hardware protocol technology from iReady set the ’7660A apart from the software-stack crowd. Although I don’t think they’re shipping billions yet, the ’7660A has appeared in enough designs to reinforce interest in, if not prove, the hardware protocol stack concept. Frankly, I’ve been waiting for another hardware-centric shoe to drop. Wait no more. Say hello to the new chip on
SILICON UPDATE Tom Cantrell
I-Way Way the Hard(ware)
the embedded Internet the W3100 from i2Chip (seeblock, Figure 1).
MII WAY
study by ACNielsen in 2001 found that nearly half a billion people worldwide now have Internet access. Does that put more pressure on embedded devices to get on the Internet bandwagon? You bet your bippy! My opinion is
Generally speaking, the W3100 is similar to the ’7660A. Both are made up of the same four blocks: host interface, network interface, protocol processing, and buffer SRAM. However, going beyond a superficial comparison reveals that the chips are actually quite different in terms of suitability for a particular application. The most compelling difference is the choice of networking. The Seiko chip was designed for dial-up access while i2Chip targets Ethernet. The difference in network speed (i.e., 56 Kbps for a modem versus 10 or 100 Mbps
that everything with an electron moving wants to be on the Internet. Market potential is unlimited on the demand side. But, as Econ 101 reminds us, it’s only realized to the degree that the supply side delivers and the price is right. For some time now I’ve been keeping a close eye on the bleeding edge of embedded Internet technology. One of
for Ethernet) percolates through all aspects of the W3100, starting with the network interface itself. The ’3100 incorporates the 802.3u standard media-independent interface (MII). This spec srcinated with the desktop Ethernet crowd as a way to allow a single Ethernet media access controller (MAC) to work with the
a
Getting on the embedded Internet bandwagon is easy, but putting an actual product on the production line is challenging. i2Chip’s latest offering looks promising, but delivery will be everything for this newcomer.
Protocol engine *CS *WR *RD *INT ADDR(14:0) DATA(7:0)
e c fa r te In U C M
ICMP
DHCP
TCP UDP IP
ARP
DLC MAC
*RESET
MII Interface
K S ):0 L R3 CC( _ X D R X R
K E ):0 L L X K L X 3 O IS L N I CT ( CRP L _ E D* X D X S T * T
M A R P D
RESET VCC GND NC A[14] A[13] A[12] A[11] A[10] A[9] A[8] VCC GND A[7] A[6] A[5]
K ] ] ] ] L 3 [ 2 [ 1 [ 0 [ C D T _ N E D D D D C D S D R N N C X C C C X X X X X *C *R W * *I N N V G N T G T T T T T 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 48 1 47 2 3 46 4 45 44 5 6 43 7 42 41 8 9 40 10 39 11 12 13 14 15 16 17 18 19 20 ] ] ] ] [4 [3 [2 [1 A A A A
21 22 23 24 25 26 27 28 29 30 ] C D ] ] ] ] C ] ] ] [0 C N [7 [6 [5 [4 N [3 [2 [1 A V G D D D D D D D
49 COL NC RX_CLK GND RXDV/CRS RXD[3] RXD[2] RXD[1] RXD[0] NC V CC 38 37 GND 36 *LINK 35 *SERIAL 34 DPLX 33 NC 31 32 ] [0 D
Figure 1—Following the iReady/Seiko 7660A, the i2Chip W3100 is the second hardware Internet chip to hit the street.
76
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
Listing 1—Thanks to the hardware assist from the W3100, a simple web server boils down to a few pages of C. //Create and initialize 4 Channels from W3100 for(i = 0 ; i < MAX_SOCK_NUM; i++) { s[i] = socket(SOCK_STREAM,80,0); //Create and initialize HTTP Channel SSTATUS[i] = SOCK_CLOSED; //Initialize channel status variables if(INVALID_SOCKET == s[i]) goto PRG_END; //Fail to create channel, terminate program //Non Blocking Listen Command if(SOCKET_ERROR == NBlisten(s[i])) goto PRG_END; //If it is error, terminate program SSTATUS[i] = SOCK_LISTEN; //Change the channel status variable to Listen mode }//end for //Check the status of each channel while (1) { for (i = 0; i < MAX_SOCK_NUM; i++) { if(SSTATUS[i] == SOCK_ESTABLISHED) { Length = select(s[i], SEL_RECV); if(Length > 0) { Length = recv(s[i], Data_Buf, Length); Con_Type = ParseReq(Data_Buf); Length = PrintHeader(TX_Buf, Con_Type); switch (Con_Type) { case 'g': Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; case 'j': Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; case 'h': Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; case 'a': Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; case 'c': PutStringLn("EVB CONTROL"); Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; case 'x': PutStringLn("EXIT"); Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); break; default : PutStringLn("DEFAULT"); Length += DoHTML(TX_Buf + Length); Length = send(s[i], TX_Buf, Length); } if(Length == SOCKET_ERROR) { GetLastError(); goto PRG_END; //Terminate program }
w w w .c ir c u it c e ll a r .c o m
® C IR C U ITC E L LA R
various physical layer options. For example, a 10-Mbps setup can run the nibble-wide MII bus at 2.5 MHz (or alternatively, a single-bit bus at 10 MHz) while 100 M bps runs i t at 25 MHz. Note that th e clocks ar e sourced by the physical interface (PHY), so the difference is transparent to the MAC (i.e., the ’3100). I could say more about the MII, but I covered it in last month’s article on the Intellon HomePlug powerline networking chip. The merit of the scheme is reinforced by the fact that it would be just as easy to connect to it the Intellon chip as it isthe to ’3100 connect to a traditional Ethernet PHY. All of the networking horsepower passes the bandwidth buck to the ’3100 host interface and internal buffering requirements, lest they become bottlenecks. Thus, the ’3100 includes 24 KB of SRAM for on-chip buffering, versus 10 KB for the ’7600A. Because reception is always more dicey than transmission (the former can’t be scheduled), the buffer breakdown is asymmetric with 16 KB for receive and 8 KB for transmit. Similarly, the ’3100 can handle up to four sockets (i.e., a virtual fullduplex connection between a pair of IP address and port designators) whereas the ’7600A can only handle two. The difference could be key if simultaneous access by multiple clients (or a single client using multiple protocols) is required. Both the ’7600A and ’3100 use a simple byte-wide host interface. The difference is that the ’3100 offers direct addressing to the on-chip RAM and registers with a 15-line (A0–A14) address bus. Wait states shouldn’t be a problem thanks to speedy access times (22 ns for reads and a mere 10 ns for writes). By contrast, the ’7600A was able to get by with a much slower (but adequate considering modem line speed) indirect addressing scheme. Although the ’3100 runs on a 3.3-V
(continued)
supply,interface the I/O lines are 5-Vdesigns tolerant, easing to existing that use the higher voltage. Note that power consumption is a mere 2 mA (typical at 3.3 V), so Internet enabling an embedded gadget doesn’t have to bust the power budget. Contrast that Issue 142
May 2002 77
0 513 8192
16384
Control registers
512 Kb
Not used
7.5 KB
Transmission data buffer (DPRAM)
8 KB
Receiving data buffer (DPRAM)
16 KB
W3100 uses 8-bit × 512 address space for control registers and 8-bit × 24K address space for data buffers: - 0 255: Space for control registers - 256 512: Space for shadow registers - 513 8191: Not used (this space can be used by other devices) - 8192 16383: Data buffer for transmission - 16384 32767: Data buffer for receiving
Figure 2—Connecting the W3100 to a host is as easy as wiring up an SRAM chip. A full 15-bit address bus provides direct access to the on-chip registers and buffers.
32767
with higher-end alternatives (e.g., chip until I can get my hands on the embedded PCs) that can easily consume real thing. As you can see in Photo 1, 100 times that amount of power. i2Chip has successfully made the transition from paper-ware to hardware. PROTOCOL POWER TRIO The 8051-based W3100 eval kit is a
three-chip (MCU, W3100, PHY) design shown in the brochures. The MCU is a plain ’51 running at 24 MHz (i.e., 2MIPS), and the PHY is a RealTek 8201. There are a few more chips on the board, but I don’t hold that against the W3100. To make life easier, the board design includes external flash memory and SRAM chips. It’s important to note that these extra chips are a matter of easing evaluation and generally wouldn’t be necessary in a production design. Similarly, the board also throws in an RS-232 interface for
’7600A, the ’3100 real-world version of the prototype downloading and debugging. IP Like withthe TCP and UDP. Thesehandles are the foundations of the Internet upon Listing 1—Continued. which the fancier layers of alphabet soup (SMTP, HTTP, etc.) rest. As a } refresher, recall that UDP is a relative} ly simple no-connection scheme that //Check the status whether the client try to connect or not, //if client succeeded, update SSTATUS[I] to SOCK_ESTABLISHED dispenses with many of the fancier //and accept to set up network information of client features (flow control, reliable delivelse if(select(s[i],SEL_CONTROL) == SOCK_ESTABLISHED) ery, etc.) found in TCP. //Connect OK? The block diagram seems to imply { //Accept the client's connection request that the ’3100 also handles protocol if( SOCKET_ERROR == accept(s[i],&ChildAddr)) trinkets such as DHCP, ICMP, and ARP { but I found little reference to them in if(SCLOSED == GetLastError()) the documentation. As best I can tell, { PutString("Before Server accepted client, the client they might require extra software, likealready closed"); ly utilizing the so-called RAW option PutHTOA(s[i that bypasses the TCP and UDP layers. PutStringLn("th socket"); Driving the chip seems straightforgoto NEXT0; ward. Registers occupy a 512-byte chunk of the 32-KB address space (see Figure 2). Just like setting up an account with an ISP, there’s a set of registers that define the local IP, MAC and gateway addresses, and sub-net mask. The remaining registers are duplicated four times, one set for each of the four sockets. To create a socket, start by initializing the registers that define the destination IP address, port, and the protocol in use. After a socket is initialized, most of the action switches to individual command, protocol state, and interrupt status registers. When it’s time to move some data, there are transmit and receive pointers that keep track of the SRAM
} goto PRG_END; } SSTATUS[i] = SOCK_ESTABLISHED; //Update socket status variable } NEXT0: //Check the status whether client close the socket or not, //Release the allocated socket from W3100, and create and // initialize a new socket //for another client and update it to Listen mode /*else*/ if( select(s[i],SEL_CONTROL) == SOCK_CLOSED ) // If the client closed socket? { PutHTOA(i);PutStringLn("th Socket are closed by Client"); //Close the current using socket if(SOCKET_ERROR == close(s[i])) goto PRG_END; PutHTOA(s[iPutStringLn("th Socket Closed"); //Initialize socket status variable SSTATUS[i] = SOCK_CLOSED; //Reallocate a socket s[i] = socket(SOCK_STREAM,5000,0); if(s[i] == INVALID_SOCKET) goto PRG_END; if(SOCKET_ERROR == NBlisten(s[i])) goto PRG_END; //Update socket status variable to Listen mode PutHTOA(i) ; PutStringLn("th Socket Listened"); SSTATUS[i] = SOCK_LISTEN;
addresses for each socket’s packets.
PING-PONG Getting this far involves no more than a review of the documentation on i2Chip’s web site. But, I learned long ago not to get too excited about a
78
Issue 142
May 2002
}
CIRCUIT CELLAR®
www.circuitcellar.com
Photo 1—The EV kit proves that even a lowly ’51 can get on the Internet with a boost from the W3100.
Bringing the to life and is asserial easy as connecting the kit Ethernet ports to a PC. The presence of an Ethernet link LED on the board helps with the issue of crossover cables. You know you’re all set when the LED lights up. The manual recommends verifying the installation using the DOS ping command (see Photo 2) before proceeding. Naturally, it didn’t work at first. The manual makes no mention of specific PC network settings, but I figured I’d have to fiddle with them. The key is to turn off DHCP and hard-
80
Issue 142
May 2002
wire your PC’s IP address to let it reach the board (see Photo 3), then ping away. After the basic connection is proven with ping, the next step is to run a loop-back test program that shovels data from the PC to the board and back again. The EV board’s side of the program is supposedly loaded into theflash memory, but if it is, my PC couldn’t hook up with it. Time for plan B. The CD that comes with the kit contains copies of all the software (including source). So, I just changed a jumper on the board to switch program
ing to smaller files (e.g., 4 KB–32 KB) affected both the symmetry and overall throughput. The latter varied from as little as 20 kbps up to 400 kbps. I tried to explore this phenomenon, but must admit I got bogged down in the source code, especially the PC-side of things. The Microsoft toolchain generates a bunch of bloatware in dozens of files for the simplest task. After I finally found the part of the program that was actually doing something, I had to concede that the code was somewhat over my head, certainly in terms of deci-
execution from the flash-memory to the SRAM and used the mon- chip phering actual activity at the chip level. itor to download the loopback.hex program. Despite some glitches (the program prompts with an incorrect IP address) and a funky user interface, that did the trick. I experimented with the loopback program using different size files. For a huge file, the program reported a symmetric 200 kbps in and out of the chip Photo 2—The first step after connecting the EV board is to see if the PC can find it using the ping command. (see Photo 4). However, switch-
CIRCUIT CELLAR®
www.circuitcellar.com
A bit of ASM would have gone a long way to help see what was actually going on, but only the source and object files were provided and I didn’t have either of the C toolchains (Microsoft for the PC, Keil for the ’51) to go further. It’s not surprising that the characteristics of the data traffic would affect throughput, but I’m left wondering the exact nature of the relationship, nevermind the proper strategy for optimizing performance. One clue is that, along with the 200-kbps bulk throughput for the 2MIPS i2Chiprate literature also mentions a’51, 400-kbps for a Dallas (now owned by Maxim) ’51-based version of demo board. Because the Dallas chip is three times faster than the standard ’51 (i.e., 4 versus 12 clocks per instruction), it’s an indication that network throughput is heavily, but not completely, dependent on host MCU performance. That’s rather disappointing because an ostensible benefit for the hardware protocol approach would be to offload the host, and to the degree it does, decouple host and network performance. Without further investigation, my conclusion is that blinding network speed (as you might expect from a hardware solution) isn’t what the W3100 is all about. On the bright side, I envision
demonstrate the ability to shove data the other way. A simple input device, even if it’s just a DIP switch, added to the ’51 board and an upgraded demo to show how to deliver dynamic data (not just a static web page) help. The guts of the web server code are shown in Listing 1. Interestingly, I found portions of the program consisted of previously published opensource code. There’s nothing wrong with that and it gave my confidence in the W3100 a bit of a boost. Formal
THE PROOF IS IN THE SURFING
w w w .c ir c u it c e ll a r .c o m
I must say that after getting under the hood, I have mixed feelings. There’s no doubt that the overall i2Chip package and presentation is unpolished. The documentation isn’t great, the demonstration software is a little awkward, and I’m left with
NeW ion Vers
Satisfied customers - the key to our success
but rather it came from alooks plainlike, ’51 talking to athat standard browser. The example does demonstrate the ability to accept input to a browser form and use it to control the ’51 (i.e., set LEDs and display a message on a plug-in LCD). However, it does not
AND THE VERDICT IS
Frustration? No, thanks. Fun? Yes, please.
many of tomorrow’s low-cost, deeply embedded Internet applications as having minimal bandwidth requirements.
Socket-level programming is all well and good, but for most people the embedded Internet concept is all about accessing a gadget’s web page from a standard browser. The folks at i2Chip oblige with a simple web server demo. Download webserv.hex to the evaluation board, fire up your PC browser, and you’re ready to catch the wave. Admittedly, the interface isn’t much to write home about—no eye-candy, JPEGs, or multimedia. Just remember that it’s not about what the web page
verification, test suites, and the like are nice, but running somebody else’s TCP/IP software on the chip is also a valid and useful real-world test.
that´s why every new EAGLE version is based on the feedback from our customers that´s why all our customers have access to our highly acclaimed, comprehensive support, free of charge that´s why EAGLE has no hidden costs for libraries or modules which prove to be indispensable after purchasing that´s why we really want customers to enjoy working with EAGLE that´s why EAGLE is one of the top-rated programs for schematic capture and board layout
EAGLE 4.0 Schematic Capture • Board Layout Autorouter ®
for
Windows and
Version 4.0 Highlights New Library Management with Component Browser Technology and Package variants for components Design your own commands via User Language Unlimited length for component names/values Design Rules define pad/via dimensions and shapes Net Classes for Autorouter and DRC Minimum Autorouter grid: 0.02 mm SMD pads can be rounded or round Different pad shapes for Top, Bottom, or Inner layers
EAGLE 4.0 Light is Freeware!
FREE
You can use EAGLE Light for testing and for non-commercial applications without charge. The Freeware Version is restricted to boards up to half Eurocard format, with a maximum of two signal layers and one schematic sheet. All other features correspond to those of the Professional Version. Download it from our Internet Site or order our free CD. The Standard Version is suitable for boards in Eurocard format with up to 4 signal layers The Professional Version has no such limitations.
http://www.CadSoftUSA.com 800-858-8355
Prices
Light
Standard Prof essiona l
Layout
199$
399$
Layout + Schematic
398$
798$
Layout + Aut orou ter
398$
Layout + Schematic + Aut orou ter
49$
597$
798$ 1197$
Pay thedifferenceforUpgrades
CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483 Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : [email protected]
® C IR C U ITC E L LA R
Issue 142
May 2002 81
Photo 3—To get started, keep things simple. Hardwire the IP settings on your PC
almost as many (but different) questions as when I started. To be fair, i2Chip is a tiny overseas start-up (a subsidiary of South Korea’s Wiznet). I’ll cut them some slack for that reason, but the marketplace at large will
Photo 4—Transferring a 1-MB file, the W3100 delivered nearly 200-kbps throughput full duplex (i.e., it took about 40 s to send the file from the PC to the W3100 and back again.
be much giving. A less goodforchip is necessary, but by no means sufficient to guarantee business. By the same token, i2Chips deserves plenty of credit for delivering a unique solution that has the appearance of actually working. Competitors may hem and haw, but nobody can ignore the fact that i2Chip has
82
CIRCUIT CELLAR®
to allow it to reach the W3100.
Issue 142
May 2002
managed to put a plain ’51 with a tiny bit of code (webserv.hex is only 11 KB or so) on the ’N et. Pardon the pun, but I’d say that stacks up well against the typical 32-bit CPU and megs of memory solution that many others are promulgating. There isn’t, and likely never will be, one single universal embedded Internet solution. i2Chip alludes to a forthcoming higher integration solution combining MCU, W3100, and PHY on the same chip. I say bring it on and the more the merrier. Hardware? Software? A little of is: both? For now, I’d say the answer all of the above. I Tom Cantrell has been working on chip, board, and systems design and marketing for several years. You may reach him by e-mail at tom.cantrell@ circuitcellar.com.
SOURCE W3100 i2Chip, Inc. www.i2chip.com
www.circuitcellar.com
IDEA BOX THE
DIRECTORY
OF
PRODUCTS A ND
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 email [email protected]. For more information call Kevin Dows at (860) 872-3064.
Suppliers Directory now available online. Check out our web site www.circuitcellar.com to see who has what and how to get it!
phyCORE Modules: NEW GENERATION SINGLE BOARD COMPUTERS
Insert-ready sub-mini SBCs (small as 47x55 mm.) supporting the Philips8xC591 8xC591,89C51Rx2 89C51Rx2,XACx XACx, XAGx, InfineonC167Cx, MotorolaMPC555 & ST MicroelectronicST10F168 Low EMI design achieved via GND circuitry, 6 to 8 layer PCB, bypass capacitor grid and short signal traces achieved via small footprint and use of 0402 SMD passive components 32 KB to 8 MB external SRAM & Flash (controller-dependent) FlashTools enable on-board in-system (ISP) programming RS-232, RS-485,2C I& CAN interfaces; ADC; Chip-Select signals Controller signals extend to standard (2.54 mm.) or high-density Molex (0.625 mm.) header pins on two sides of the board, allowing the SBC to be plugged like a "big chip" into targets Available inRapid Development Kits including Development Board, AC adapter, serial cable and SPECTRUM CD with eval software tools (Keil, TASKING), FlashTools, electronic documentation and demos
PHYT EC America LLC 255 Ericksen Avenue Bainbridge Island, WA USA 98110
www.phytec.com
w w w . c ir c ui t c e ll a r . c o m
(800) 278-9913
® C IR C U ITC E LL A R
Issue 142
May 2002 83
84
Issue 142 May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
w w w . c ir c ui t c e ll a r . c o m
® C IR C U ITC E LL A R
Issue 142
May 2002 85
86
Issue 142 May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
w w w . c ir c ui t c e ll a r . c o m
® C IR C U ITC E LL A R
Issue 142
May 2002 87
m o c . h cPentium 4 e T m a e r D .
DESIGN YOUR DREAM P4! WITH INTEL MAIN BOARD, PROCESSOR & SOUND.
Dream P4
845s
w w
POWERFUL PENTIUM 4 ~ WITH INTEL 845WN MAIN BOARD & FAST PC/133MHz MEMORY! VALUE PRICED WITH 256MB RAM, 20GB HD, MOUSE, SOUND & MODEM!
•
0 0 8 1 3 5 3 Dream P4 0Entertainer 1 5 1 •
•
BEST BUY! INTEL 845BG MAIN BOARD WITH INTEGRATED SOUND, 60GB HD & 256MB RAM. AVAILABLE UP TO 2.2GHz!
r e m Dream a XP-Pro e r D A 0 0 8 1
• FAST & RELIABLE WITH RAMBUS MEMORY, WINDOWS XP PROFESSIONAL & MORE! •
DreamTech
88
Issue 142 May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
w w w . c ir c ui t c e ll a r . c o m
® C IR C U ITC E LL A R
Issue 142
May 2002 89
90
Issue 142 May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
Email: [email protected]
w w w . c ir c ui t c e ll a r . c o m
® C IR C U ITC E LL A R
Issue 142
May 2002 91
92
Issue 142 May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
w w w . c ir c ui t c e ll a r . c o m
® C IR C U ITC E LL A R
Issue 142
May 2002 93
ADVERTISER’S INDEX The Advertiser’s Index with links to their web sites is located at www.circuitceller.com under the current issue. Page
Page
Page
Page
Earth Computer Technologies
74
Micromint Inc.
48
ECD (Electronic Controls Design)
84
MicroSystems Development, Inc.
88
Sealevel Systems Inc.
ActiveWire, Inc.
84
EE Tools (Electronic Engineering Tools)
87
MJS Consulting
90
Senix Corp.
Advanced Transdata Corp.
82
EMAC, Inc.
66
MVS
85
Sensory, Inc.
69
All Electronics Corp.
73
ESC-Chicago
86
Mylydia Inc.
83
Signum Systems
85
Amazon Electronics
90
EVBplus.com
38
Nav Masters
87
SmartHome.com
33
American Raisonance Corp.
48
ExpressPCB
65
NetBurner
38
Softools
9 92
Amulet Technologies AP Circuits
84 89
FDI-Future Designs, Inc. Futurlec
Netmedia, Inc. OKW Electronics Inc.
23 92
Solutions Cubed Spectrum Engineering
90
Appspec Computer Tech. Corp.
84
Hagstrom Electronics
93
Ontrak Control Systems
83
Square 1 Electronics
84
Atlantic Quality Design, Inc.
80
HI-TECH Software,LLC
C2
Parallax, Inc.
24
SUMBOX
85
Bagotronix, inc.
91
HVW Technologies Inc.
83
Phytec America LLC
41
Systronix
Basic Micro
86
ICE Technology
83
Phyton, Inc.
92
TAL Technologies
81
CadSoft Computer, Inc.
87
IMAGEcraft
91
Picofab Inc.
91
Tech Systems
91
CCS-Custom Computer Services
Intec Automation, Inc.
90
Pioneer Hill Software
C3
Tech Tools
86
Cermetek Microelectronics Inc.
86
Intronics, Inc.
85
Prairie Digital Inc.
90
Techniprise Inc.
92
Conitec
68
Intuitive Circuits, LLC
15
PSoC 2002 Design Challenge
11
Connecticut mircoComputer Inc.
49
JED Microprocessors Pty Ltd.
89
Pulsar Inc.
93
Technological Arts
91
Copeland Electronics Inc.
64
JK microsystems
91
R2 Controls
88
Tern Inc.
91
Cyberpak Co.
38
JR Kerr Automation & Engineering
31
R4 Systems Inc.
84
Timeline In c.
79
Cypress MicroSystems
68
LabJack Corp.
39
Rabbit Semiconductor
83
Triangle Research Int’l Inc.
C4
Dataman Programmers, Inc.
80
Laipac Technology, Inc.
82
Radiotronix, Inc.
11
Trilogy Design
86
Dataprobe Inc.
68
Lakeview Research
85
R.E. Smith
86
Vetra Systems Corp.
86
DataRescue
89,93
Lemos International
10
Remote Processing
93
Weeder Technologies
83 89
Decade Engineering Delcom Engineering
Link Instruments Lynxmotion, I nc.
89 88
RLC Enterprises, Inc. RPA Electronics Design, LLC
91 87
Xilor Inc. Z-World
87
Designtech Engineering Co.
MaxStream
86
Rutex
85
Zanthic Technologies Inc.
91
Digital Products
89
Micro Digital Inc
59
Saelig Company
88
Dreamtech Computers
92
microEngineering Labs, Inc.
89
Scidyne
85
Abacom Technologies
10
Accutek Microcircuit Corp.
85 61,75
25,84
1
86,92
2 93 7
95 87,90
Extreme OSMC—Part 1: Open Source Motor Control Project Ultra-Low Power Flash MCU MSP430 Design Contest Winners Selecting the Best CAN Controller An Open-Source HCS Project BatMon to the Rescue— A Battery Monitor for R/C Models Behind the Scenes—Part 2: How to Build the System RoCK Specifications: The Goal of a New Machine— Part 3: Programming I Above the Ground Plane: Invisible Components I
32,72
I Applied PCs: Still Swimming with the STK500—Onto the JTAG ICE
Embedded Programming Issue 142 May 2002
CIRCUIT CELLAR®
Scott Edwards Electronics Inc.
Technologic Systems
Attention Advertisers: July Issue Deadlines Space Close: May 10 Material Due Date: May 17
Theme: Graphics & Video
From the Bench: SmartMedia File Storage—A Windows Compatible DOS File System
I Silicon Update: FPGA Power Play
94
3
IEW V E
PR 143 www.circuitcellar.com
PRIORITY INTERRUPT The Insanity of Success
l
et’s face it. As technical magazines go, Circuit Cellar is a small fish in a big publishing sea. It’s not a David and Goliath struggle, mind you. It’s more like mutual coexistence. They do their thing and we do ours. One of the things we do really well is design contests. I could claim that it is merely the ability of a small business to react quickly and tailor products to meet changing demands and interests, but the real credit goes to our involved readership. Circuit Cellar readers have an insatiable appetite for innovative ideas and relish an opportunity to exhibit them. Our design contests have evolved as a catalyst to construct those ideas and the magazine as a forum for their presentation. Design contests have always been a big deal around Circuit Cellar, and in recent years, they have evolved into a major part of our editorial strategy. What is the fundamental ingredient to doing contests well? That’s simple. We enjoy it. Most technical publishers treat contests as just another advertising endeavor. Rarely do they provide more than minimal contest management and contestant entries rarely involve physically building anything. This isn’t a failure on their part, it is merely a consequence of their business model versus ours. Certainly just treating it as advertising would be easier. There was a time when we had one design contest a year. Demand from sponsors as well as readers has increased that to two a year. In fact, it can get a little insane around here because we’re always working on three contests at a time—past, present, and future. For example, we just finished the Texas Instruments contest and are now working with winners and entrants creating follow-up articles; we’re still running the present contest with Cypress MicroSystems; and, finally, we’re negotiating the contract and creating the ’Net presentation for the fall 2002 contest. Crazier yet, we have five companies already interested in the spring 2003 slot. I once joked, “If you don’t see your favorite processor now, wait a minute, it’ll show up.” That seems to be very true now. Entrants and sponsors get a lot of value from participation. Contestants aren’t entering a lottery. Not winning isn’t the same as losing around here. Because our real motivation is editorial rather than advertising, every project entry is evaluated by our editorial staff for its potential to be turned into an article and published (we contact you separately for publishing rights). If you happened to be a winner, it’s consequential, not critical. Getting published in Circuit Cellar is based on the application value of your project, not on how it placed in a contest. If it’s a good design, I want it, period. Being a winner in a Circuit Cellar contest can be good for your career, too. Companies looking to hire good designers view our contests as an accurate test of your design credentials and your ability to finish what you start. More than a few contest entrants have received job offers. In addition, some contestants have reported that being listed among our design contest winners provided the visibility they needed to launch their product. In our most recent TI contest, for example, one winner was approached by a marketing organization and his project is now in full production. Regardless of the outcome, entering a Circuit Cellar contest can be a confidence builder. With each successive contest, we try to make it easier for you to enter. To facilitate your ability to compete, recent contests have included samples and development kits shipped free to anyplace in the world. Of course, “sampling” for our current Cypress contest takes on a whole new meaning when you realize that Cypress is providing a complete PSoC development system (worth about $50), and together with us, invested about $100,000 to put them into the right hands. We don’t want a little problem like not being able to find a PSoC in Beijing to keep you from entering. Next month, you’ll see the print announcement of the winners of our Texas Instruments MSP430 design contest. And the Cypress MicroSystems PSoC 2002 contest has another month and a half before the projects go to the judges. But, as I’ve said many times before, don’t unplug your soldering irons yet. This fall, we are planning another Microchip Technology design contest for all of you PIC fans out there. It’s our third outing with Microchip and we’ll try to make it our best yet. Reader involvement is the greatest encouragement I know. If you are enthusiastic about a PIC contest, e-mail me and I’ll let Microchip know how you all feel. Design contests have become an essential ingredient around here. With all of these present and future contests in the pipe, subscribers can count on a lot of terrific projects covering a variety of great processors in the issues to come.
[email protected]
96
Issue 142
May 2002
CIRCUIT CELLAR®
www.circuitcellar.com
STILL THE WORLD’S MOST POWERFUL $795
PORTABLE
PROGRAMMERS?
inc 4mb ram
NEW MODEL $1295
Surely not. Surely someone somewhere has developed a portable programmer that has even more features, even greater flexibility and is even better value for money. Actually, no. But don’t take our word for it. Use the feature summary below to see how other manufacturers’ products compare.
DATAMAN-48LV • Plugs straight into parallel port of PC or laptop • Programs and verifies at 2, 2.7, 3.3 & 5V
S4 GAL MODULE
• True no-adaptor programming up to 48 pin DIL devices
• Programs wide range of 20 and 24 pin logic devices from the major GAL vendors
• Free universal 44 pin PLCC adaptor
• Supports JEDEC files from all popular compilers
• Built-in world standard PSU - for goanywhere programming • Package adaptors available for TSOP, PSOP, QFP, SOIC and PLCC • Optional EPROM emulator
DATAMAN S4
• EPROM emulation as standard • Rechargeable battery power for total portability • All-in-one price includes emulation leads, AC charger, PC software, spare library ROM, user-friendly manual • Supplied fully charged and ready to use
If you do not agree that these truly are the most powerful portable programmers you can buy, simply return your Dataman product within 30 days for a full refund
SUPPORT • 3 year parts and labor warranty • Windows/DOS software included • Free technical support for life • Next day delivery - always in stock
• Programs 8 and 16 bit EPROMs, EEPROMs, PEROMs, 5 and 12V FLASH, Boot-Block FLASH, PICs, 8751 microcontrollers and more
MONEY-BACK 30 DAY TRIAL
Still as unbeatable as ever. Beware of
cheap imitations. Beware of false promises. Beware of hidden extras. If you want the best, there’s still only one choice - Dataman. Order via credit card hotline - phone today, use tomorrow. Alternatively, request more detailed information on these and other marketleading programming solutions.
Orders received by 4pm will normally be despatched same day.
Order today, get it tomorrow!
Dataman Programmers Ltd 215 East Michigan Avenue Orange City, FL 32763 Telephone (904)774-7785 Fax (904) 774-7796 Home page: http://www.datama n.com Email: [email protected]