The 4-to-20-mA Current Loop, p. 28 | Inside a Pro’s Electronics Lab, p. 50 | MIPS Chips, p. 66
THE
MAGAZINE
FOR
COMPUTER
A P P L I C AT I O N S August 2010 Issue 241
Embedded Safety and Failure Mode Analysis How to Measure a Crystal’s Properties Advanced Features of USB Explained An X10 Controller Program and Utility Control How Apps Exchange Data
PLUS THE MANY TALENTS OF AN INSTRUMENTATION ENGINEER: $7.50 U.S. ($8.50 Canada)
www.circuitcellar.com
How One Designer Uses Electronics & Embedded Technologies to Solve Real-World Problems ... on a Daily Basis
Low-cost Industrial
Serial to Ethernet Solutions t *OTUBOUMZ OFUXPSLFOBCMF BOZ TFSJBM EFWJDF t /P QSPHSBNNJOH JT SFRVJSFE GPS TFSJBM UP &UIFSOFU BQQMJDBUJPO t $VTUPNJ[F UP TVJU BOZ BQQMJDBUJPO XJUI B EFWFMPQNFOU LJU
SBL2e Chip
SBL2e 200
SBL2e 100
QPSU TFSJBMUP&UIFSOFU TFSWFS XJUI FJHIU "% DPOWFSUFS JOQVUT BOE PQUJPOBM 41* *$ $"/ QFSJQIFSBM EFWJDF TVQQPSU
QPSU TFSJBMUP&UIFSOFU TFSWFS XJUI GPVS "% DPOWFSUFS JOQVUT PQUJPOBM *$ QFSJQIFSBM TVQQPSU BOE QJO IFBEFS
QPSU TFSJBMUP&UIFSOFU TFSWFS XJUI GPVS "% DPOWFSUFS JOQVUT PQUJPOBM *$ QFSJQIFSBM TVQQPSU BOE 3+ DPOOFDUPS
SBL2e X
Hardware Features 6Q UP UISFF TFSJBM QPSUT .CQT &UIFSOFU VQ UP EJHJUBM *0 CJU "% DPOWFSUFST PQFSBUJOH UFNQFSBUVSF UP $ CJU QFSGPSNBODF
&YUFSOBM QPSU TFSJBMUP&UIFSOFU TFSWFS XJUI 34 TVQQPSU
Software Features 5$16%15FMOFU)551 NPEFT %)$14UBUJD *1 TVQQPSU XFCCBTFE PS "5 DPNNBOE DPOöHVSBUJPO Low Prices 4#-F $IJQ 2UZ L %FWJDF 1/ 4#-F$)*1*3
4#-F 2UZ %FWJDF 1/ 4#-F*3
4#-F 2UZ %FWJDF 1/ 4#-F*3
4#-F 9 2UZ %FWJDF 1/ 4#-F9*3
4#-F 9" 2UZ %FWJDF 1/ 4#-F9"*3
SBL2e XA &YUFSOBM TFSWFS XJUI VQ UP GPVS "% DPOWFSUFS JOQVUT VQ UP FJHIU EJHJUBM *0 BOE VQ UP two 6"354 (one RS-232)
Need a custom solution? /FU#VSOFS 4FSJBM UP &UIFSOFU %FWFMPQNFOU ,JUT BSF BWBJMBCMF UP DVTUPNJ[F BOZ BTQFDU PG PQFSBUJPO JODMVEJOH XFC QBHFT EBUB öMUFSJOH PS DVTUPN OFUXPSL BQQMJDBUJPOT "MM LJUT JODMVEF QMBUGPSN IBSEXBSF "/4* $$ DPNQJMFS 5$1*1 TUBDL XFC TFSWFS FNBJM QSPUPDPMT 3504 BOE /# &DMJQTF *%& Information and Sales ] TBMFT!OFUCVSOFSDPN Web ] XXXOFUCVSOFSDPN
Telephone ]
T
ASK MANAGER W
August 2010 – Issue 241
Proactive Engineering
4
orking as an embedded engineer—whether you’re a designer, programmer, or both—gets tougher each year. Technology develops at a rapid pace, protocols and standards frequently change, and many programming languages evolve as quickly as others lose relevance. And those are just the perennial issues you must deal with as a matter of course. Other troublesome issues are much less predictable. During any given month, circumstances such as macroeconomic instability, jumps in material costs, and credit tightening can “short” any design endeavor, whether big or small. So, how does a businesssavvy embedded engineer profit (both financially and intellectually) in times of good and bad? He or she gets proactive. If you want a long career in the embedded design industry, you must be driven and flexible. Learn hardware. Learn software. Work in industry. Consult on the side. Teach courses. Write articles. And most importantly: design, design, design. Think it’s impossible given your already hectic schedule? Think again. Circuit Cellar founder Steve Ciarcia did it. He designed his own applications, wrote hundreds of articles and columns, published books, built boards, launched a magazine, ran contests, and more. For another example of a proactive engineer, turn to page 8 to read about Brian Millier’s career as an implementation engineer. In addition to having worked in industry (at GE) and in a university setting, Brian also designed dozens of projects, won international design contests, and wrote articles about some of them for Circuit Cellar. His can-do approach to engineering should be an inspiration to everyone. And in case you are wondering, he has more Circuit Cellar articles in the pipeline. All the authors in this issue know that success takes more than just showing up at the office each day. The fact they design in their free time and write articles about their projects highlights their forward-thinking enterprising spirits. On page 16, George Novacek (author, PE, and former aerospace industry executive) writes about achieving embedded design safety with failure mode analysis. In “Advanced USB Design Debugging” (p. 20), Colin O’Flynn (designer and consultant) turns your attention to the many advanced features of USB technology. On page 28, Aubrey Kagan (PE and author of Excel by Example) covers the important topic of the 4-to-20-mA current loop. Next, Devlin Gualtieri (designer and experienced researcher) wraps up his series on his X10 controller (p. 36). On page 42, Ed Nisley (EE and author) describes the properties of crystals. On page 50, Robert Lacoste (designer, author, and consultant) describes his personal design lab. Following Robert, designer and author Jeff Bachiochi finishes his series on application communication (p. 58). And finally, Tom Cantrell (seasoned columnist and technology reviewer) explains why he thinks MIPS chips deserve a closer look. If they can do it, you can too. Design and prosper.
[email protected]
FOUNDER/EDITORIAL DIRECTOR Steve Ciarcia
PUBLISHER Hugo Vanhaecke
EDITOR-IN-CHIEF C. J. Abate
ASSOCIATE PUBLISHER Shannon Barraclough
WEST COAST EDITOR Tom Cantrell
CUSTOMER SERVICE Debbie Lavoie
CONTRIBUTING EDITORS Jeff Bachiochi Robert Lacoste George Martin Ed Nisley
CONTROLLER Jeff Yanco ART DIRECTOR KC Prescott GRAPHIC DESIGNERS Grace Chen Carey Penney
NEW PRODUCTS EDITOR John Gorsky PROJECT EDITORS Ken Davidson David Tweed
STAFF ENGINEER John Gorsky
ADVERTISING 800.454.3741 • 978.281.7708 • www.circuitcellar.com/advertise ADVERTISING REPRESENTATIVE Peter Wostrel Strategic Media Marketing, Inc. 1187 Washington St., Gloucester, MA 01930 USA 800.454.3741 • 978.281.7708
[email protected] • www.smmarketing.us Fax: 978.281.7706 ADVERTISING COORDINATOR Valerie Luster E-mail:
[email protected] Cover photography by Chris Rakoczy—Rakoczy Photography www.rakoczyphoto.com PRINTED IN THE UNITED STATES CONTACTS SUBSCRIPTIONS Information: www.cc-access.com, E-mail:
[email protected] Subscribe: 800.269.6301, www.cc-access.com, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 Address Changes/Problems: E-mail:
[email protected] GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail:
[email protected] Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail:
[email protected] New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail:
[email protected] AUTHORIZED REPRINTS INFORMATION 860.875.2199, E-mail:
[email protected] AUTHORS Authors’ e-mail addresses (when available) are included at the end of each article.
CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $45, Canada/Mexico $60, all other countries $63. Two-year (24 issues) subscription rate USA and possessions $80, Canada/Mexico $110, all other countries $116. All subscription orders payable in U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call 800.269.6301. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755 5650.
Circuit Cellar® makes no warranties and assumes no respons bility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of reader-assembled projects, Circuit Ce lar® disclaims any responsib lity for the safe and proper function of reader-assembled projects based upon or from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction. The reader assumes any risk of infringement iability for constructing or operating such devices. Entire contents copyright © 2010 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Ce lar, Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.
CIRCUIT CELLAR®
•
www.circuitcellar.com
What is the missing component? Electronics instructor Ollie Circuits planned to show his class of freshman electrical engineering students how to use a super capacitor as a memory back-up capacitor, but first he wanted to show how the students could make their own super capacitor and demonstrate its charge/discharge cycles with the simple circuit above. Most of the components were already on his workbench, the homemade super capacitor would be made from several layers of lemon juice-soaked paper towels interleaved between several layers of a mystery material to form a multi-layer stack.The stacked layers would then be sandwiched between the two copper-clad PC boards and held together with a rubber band. Ollie rushed to a nearby pet shop. What did he buy? Go to www.Jameco.com/teaser7 to see if you are correct and while you are there, sign-up for our free full-color catalog.
1-800-831-4242 | www.Jameco.com
241
INSIDE ISSUE August 2010
20
Advanced USB Design Debugging Colin O’Flynn
28
The 4-to-20-mA Current Loop Aubrey Kagan
36
Build an X10 Controller (Part 2) The Controller Program and Utility Devlin Gualtieri
•
Embedded Development
Advanced USB, p. 20
A Look at Crystals p. 42
Communication with a Sensor, p. 58
Lacoste’s Lab, p. 50
16 42
August 2010 – Issue 241
50
6
58 66
THE CONSUMMATE ENGINEER Embedded Safety George Novacek ABOVE THE GROUND PLANE Crystal Properties Circuit Models, Measurement, and Conversion Ed Nisley THE DARKER SIDE A Tour of the Lab (Part 1) Time Domain Measurement Equipment Robert Lacoste
4
QUESTIONS & ANSWERS Custom Instrumentation Engineering An Interview with Brian Millier C. J. Abate
8
NEW PRODUCT NEWS
12 15
TEST YOUR EQ
FROM THE BENCH Application Communication with USB (Part 3) Assembly Code Finale Jeff Bachiochi SILICON UPDATE MIPS and More Tom Cantrell
TASK MANAGER Proactive Engineering C. J. Abate
CROSSWORD INDEX OF ADVERTISERS September Preview
PRIORITY INTERRUPT Is the Internet Making Us Smarter or Dumber? Steve Ciarcia CIRCUIT CELLAR®
•
74 79 80
www.circuitcellar.com
Let your geek shine. Meet Leah Buechley, developer of LilyPad—a sew-able microcontroller—and fellow geek. Leah used SparkFun products and services while she developed her LilyPad prototype. The tools are out there, from LEDs to conductive thread, tutorials to affordable PCB fabrication, and of course Leah’s LilyPad. Find the resources you need to let your geek shine too.
»Sharing Ingenuity SP A R K F U N.C OM
©2010 SparkFun Electronics, Inc. All rights reserved.
QUESTIONS & ANSWERS Custom Instrumentation Engineering An Interview with Brian Millier Brian Millier is an instrumentation engineer in the Department of Chemistry at Dalhousie University in Halifax, Canada. He also runs Computer Interface Consultants. Circuit Cellar published 39 of Brian’s articles between 1994 and March 2010. In June 2010, I interviewed him about topics ranging from his first experience with an MCU to his most current project. — C. J. Abate, Editor-in-Chief
CJ: Tell us about yourself and your work as an instrumentation engineer. BRIAN: I work in Halifax, the capital city of Nova Scotia, on the east coast of Canada. I’m fortunate in being able to commute a short 30 minutes to my home, which is situated on a great lake-front property. My wife was the chief tech in a small X-Ray department, and we have no children. This has afforded me lots of time to pursue my hobbies of electronics, computer programming, and carpentry. We both enjoy music, and I’ve built a nice recording studio in my basement where we record a lot of music together—strictly amateur, though. I’ve been seriously involved in electronics since I was 10 years old (when my father started buying me electronics kits). There was never any doubt in my mind that I would pursue electronics as a career, although I did make some career compromises to remain in Nova Scotia, which is definitely not an electronics center. For close to 30 years now, I’ve been an instrumentation engineer in the Chemistry Department at Dalhousie University. My job involves designing, building, and programming custom instrumentation that’s used in the department, as well as maintaining the many complex instruments, such as NMR spectrometers and mass spectrometers, in the department.
August 2010 – Issue 241
CJ: How long have you been reading Circuit Cellar?
8
BRIAN: I’d like to say right from the start, but that wouldn’t be true. However, I built my first “personal computer” in the late ’70s and all of us “geeks” read Byte and Kilobaud magazines back then. Byte’s most interesting technical articles were written by Steve Ciarcia. As the PC field became “commercialized,” Byte followed that trend and Steve’s design articles disappeared. It wasn’t until 1993 when I noticed a copy of Circuit Cellar on a newsstand that I realized that Steve had started up a new magazine some years back. CJ: What was the first technology that caught your attention and excited you about electronics and electrical engineering? BRIAN: For me, that’s going a long way back! Growing up
as a teenager in the late ’60s, rock music was very influential to me. You had to play your vinyl records on your parent’s big console hi-fis in the living room, or listen to a transistor radio. So, I started building powerful stereo amplifiers and loudspeakers, which I sold to college students in residence. I was in a rock band for a while, and built most of the PA equipment that we used, since we were too young to be able to afford commercial equipment. So, I guess I would have to say that analog audio circuits using vacuum tubes were my first big influence. CJ: How long have you been working with “embedded technology,” and what was your first MCU-based design? BRIAN: When I started at Dalhousie in 1980, even though I worked in a large Chemistry Department, there was only one DEC MINC-11 minicomputer (a scientific version of DEC’s PDP-11) in the whole department. The university computer center had several large mainframes, of course. I soon started designing microprocessor-based circuitry to interface our existing scientific instruments to the newly introduced IBM PC computers—thereby replacing the analog readouts and strip-chart recorders of the day. The first working “personal computer” I ever built was an RCA COSMAC ELF, which used an RCA CDP1802 microprocessor. However, that was a Popular Electronics project designed by Joseph Weisbecker in 1977. My first MCU-based design was a dual-channel strip-chart recorder replacement, which had an analog front-end, two Analog Devices V/F converters for the ADCs, a Texas Instruments TMS370 MCU, and used the popular Epson dotmatrix printer for hardcopy. It’s easy to remember this project as it was the subject of my first Circuit Cellar article in 1994. CJ: Tell us about your training and background. BRIAN: Everyone knows that Bill Gates and Steve Jobs dropped out of college to later become billionaires. Well, so did I—except for the billionaire part! I chose to attend Acadia University, a small university in the rural area where I grew up. I was offered a full university scholarship, which was conditional upon my taking a degree program. CIRCUIT CELLAR®
•
www.circuitcellar.com
What I really wanted to pursue was Electrical Engineering, and Acadia only offered a pre-engineering diploma in conjunction with Nova Scotia’s Technical College. So, I enrolled in the BSc degree program and concurrently took the engineering courses needed to earn my Engineering diploma. However, having been doing electronics since I was 10 years old, there was very little electronics information in any of the courses that I took during those four years that I hadn’t already learnt on my own. Just before transferring to the NS Technical College to complete my Engineering degree, I was offered a great position at General Electric. I was dying to start a “real job,” so I took that position and never completed the Engineering degree. Looking back, I believe that GE is arguably the best-managed company in the world (the famous Jack Welsh was CEO when I started), and I believe I benefited greatly by starting out my career with them.
Currently, I am predominantly involved in designing lowcost instruments for our undergraduate teaching labs. While there is an increased focus on undergraduate teaching here at Dalhousie, I also see a decline in interest in the teaching lab part of the program. I strongly believe in the value of the “hands-on” experience gained in these labs, and do my best to buck that decline in interest by designing and building as much low-cost instrumentation for these teaching labs as I have time for.
CJ: You’ve written 39 articles for Circuit Cellar. How do you choose which technology to focus on during any given month?
BRIAN: I have been a very staunch believer in the importance of energy conservation for many years now. However, as an electronics enthusiast, I have to admit to having an awful lot of “gadgets” around the house which draw “phantom power.” The smart power bar was my attempt to reduce the amount of “phantom power” that my TV/home entertainment center drew continuously. While it is only a small step, it does work very well at accomplishing this. Since many of my projects involve serial data links of come kind, it was handy to have a device that could “sniff out” communications problems when I was dealing with ICs that were new to me. I can’t afford to buy a lot of specialized test equipment at work, so the Serial Sidekick was a low-cost solution to that problem.
CJ: Many of your projects are solution-oriented—meaning, you have a problem or a particular need in the university’s chemistry lab and you use your engineering skills to design solutions and handy applications. Do you actively seek out problems to solve, or do you simply design solutions on an as-needed basis? BRIAN: When I started working at Dalhousie, most all of my work involved computer interfacing of research instruments. Since the faculty were really only familiar with the mainframe computer facility, I was very proactive in promoting the use of PC computers in the research labs by designing whatever interface circuitry I could to promote that goal. At that time, I spent about 50% of my time repairing all of the electronics equipment in the labs, so I am quite oriented towards problem-solving. www.circuitcellar.com
•
CIRCUIT CELLAR®
CJ: In 1994, the time of your first Circuit Cellar article, what technologies excited you the most? And what about today? BRIAN: At that time, microprocessors had just evolved into really useful devices. For me, the big breakthrough came when microprocessors became MCUs (i.e., they contained their own program and RAM memory onboard, as well as a UART and some parallel I/O ports). Since I was doing custom work, most of my designs had to be handwired using Vector boards and wire-wrap wire. These new MCUs greatly reduced the amount of hand-wiring needed. Like anyone involved in digital electronics at that time, I was also very excited with the advent of UV-erasable EEPROM program memory, as it made the chore of firmware programming much less of a hassle. Also, at about the same time, the cost and availability of pretty decent mixed-signal ICs such as ADCs and DACs improved markedly. Today, I am less excited about any particular hardware technology than I am about advances in software/firmware. The development tools available to designers today are vastly better than what we had when I started out in the business. I’ll give you a few examples. One, for mixed-signal applications today, it is quite
August 2010 – Issue 241
BRIAN: Working in an academic environment, I have a lot of freedom when it comes to choosing how I am going to attack a design solution. I’ve never been “married” to any particular MCU family, and have switched amongst numerous MCUs over the years—generally favoring those that have the best development boards and software available at any given time. Since I started out doing analog circuitry and later moved on to digital/computer circuits, I am particularly interested in what is referred to as mixed-signal designs. Since much of the measurement done in a university research environment requires high resolution/accuracy, I tend to focus on innovative mixedsignal ICs from such companies as Analog Devices, BurrBrown (now TI), and Maxim. While I never have to worry about saving a penny here and there on components, as would be the case in commercial manufacturing, I do take a lot of pride in designing the most cost-effective project that I can, given the custom nature of the work that I do.
CJ: Let’s consider two designs that you use at home: a smart power bar for energy conservation (Circuit Cellar 230, 2009) and the bench-top “Serial Sidekick” design for troubleshooting serial data communication issues (Circuit Cellar 159, 2003). Do you build devices like these simply because you love designing? Or perhaps you’re driven to develop cost-effective alternatives to off-the-shelf solutions?
9
reasonable to expect to be able to design a complete “system on chip” (SoC) using Cypress Semiconductor’s PSoC line. The chip hardware is very sophisticated—particularly the newer PSoC3 and 5 models—but this would be a moot point were it not for some extremely powerful development software that Cypress makes available: the PSoC Designer/Creator programs. However, the existence of these very user-friendly programs would not be that useful to young designers if they cost thousands of dollars to purchase, which is often the case. Cypress provides these programs free, making it possible for young designers to create powerful designs with very little expense up-front. Two, the ARM family of MCUs is likely to become the predominant MCU family in the future. While many companies are embracing it, I have to give credit to NXP (formerly Philips) for their “mbed” project. Here they’ve taken a powerful ARM MCU, placed it on a small PCB with a DIP40 pinout, and added a “magic” custom chip to make the board look to your PC like a USB flash drive. You don’t need a chip programmer; you just drag and drop your object code file to the mbed “flash drive,” and it takes care of the programming automatically. I prefer to program in Basic, but acknowledge that most MCUs now are programmed in C. With the mbed system, you needn’t buy and configure a C compiler. A powerful C compiler, preconfigured for the ARM Cortex chip mounted on the mbed module, is available free “on the cloud.” By tapping into their really active user-group forum, you can be
designing great projects in a short time, with virtually zero start-up costs. CJ: What was your most well-received article? BRIAN: Judging by the amount of reader feedback I received, my most popular article was “Using a T6963 Controller-Based Graphics LCD panel” back in 2000 (Circuit Cellar 125). Many projects revolve around an inexpensive graphics LCD readout, and the electrical design and the graphics language I incorporated into the firmware were quite popular at the time. It was also the first significant project I did using the Atmel AVR series of MCUs, which continue to be my favorite MCU for most of my current projects. CJ: What project or projects are you working on right now? BRIAN: After 45 years in the business, I am now quickly approaching retirement. Like many people in a similar situation, I guess I suffer from a bit of “been there, done that” attitude. To combat this, I’ve recently become interested in computer numeric control (CNC), which is essentially the computer control of machining tools. I have always personally done much of the panel/cabinet work on many of my projects, both at work and as a hobby. Therefore, it seemed worthwhile to investigate a computer-controlled milling
Protocol Decoding 100 MHz MSO 8M Samples 14 bit
August 2010 – Issue 241
Used MIT, Use by Harvard, r a , Stanford, t nf IT Caltech, UCLA,, UC UCI, UCSD, Colorado UC S UCB, C o SState, Rice . . . R ce, Washington, s n gt , NorthEastern r a
10
+ Two mixed signal triggers + Protocol decoding + Spectrum analysis + Symbolic math + Custom units + Copy & paste + Signal generator + USB or Ethernet + 4 or 8M samples storage + 100 MHz sampling + Dual 10, 12 or 14 bit ADC + Ext Trigger, 8 Digital Inputs + 1 MSa/sec charting
Protocol P ot o Decoding. D Decoding c i .
Decode SPI, I2C, or RS232 based data streams 4M samples long. The decoder is fully configurable, and can save time stamped results to a text file. Write your own plug-in decoder – you can use our open source ones as a starting point.
Example: xam Capture 250 separate messages. Zoom in on any one of them. Each one is fully decoded. See our Examples page for this signal and a white paper describing how to capture it. In he USA call:
www.cleverscope.com CIRCUIT CELLAR®
•
www.circuitcellar.com
Photo 1—Brian’s latest CNC project machine that could do this sort of work. Since I also like carpentry, I thought a computerized router would be nice to have. I’ve just finished building a CNC router that will do light aluminum panel work, as well as work with wood and plastic. Finding suppliers for all of the specialized mechanical parts, and building the machine from scratch, was truly challenging and rewarding. I am hoping to publish my experience in a future Circuit Cellar article. While this is mostly a mechanical project, I also designed a remote control pod for my router, which will provide some electronics content to the article.
started Computer Interface Consultants about 15 years ago so I could bill them for such projects. Similarly, I do some repair work on scientific instruments for other institutions through Computer Interface Consultants. In reality, the “consultants” part of the name is not really applicable, as I seldom do any consulting work per se. It made for a more impressivesounding name, however. CJ: You have been involved in several Circuit Cellar contests over the years. What is the attraction? BRIAN: Working in a technical support position in academia, there isn’t too much competitive pressure. Nor is there any performance measurement system in place, or merit pay, per-se. By entering Circuit Cellar contests, I had a chance to compete with my peers, which I found quite rewarding.
I’ve had reasonably good success—my best showing being my First Prize project (Multilab) in the Zilog “Flash For Cash” contest. Win or lose, I still gain valuable experience designing with MCUs apart from the ones that I routinely use. (Plus it forces me to program in C occasionally!) CJ: Is there anyone in particular you would like to acknowledge for having helped you in your work? BRIAN: Like many people who became interested in “personal computers” in their infancy, I became overly obsessed with them in the early days. I have to thank my wife for putting up with me for all the time I spent on computers back then. On a more technical level, I am indebted to Mark Alberts who wrote the BASCOM-AVR compiler, which I have used for all of my AVR-based projects over the past 10 years. He has personally responded very promptly to all of my questions over the years. Firmware is a big part of such projects, and his support has been invaluable. I
CJ: Hatching any other plans?
Ideal for Embedded Applications with High-Speed Serial I/O Requirements
Xilinx® Virtex™-5 System-on-Module 8VHU 'HILQDEOH ,2 8VHU 0XOWL*LJDELW 6HU'HV 3DLUV 8VHU %L&RORU /('V 8S WR 0+] 2SHUDWLRQ 8S WR 0% ''5 '5$0 2SWLRQDO 0E 4'5,, 65$0 2QERDUG &RQILJXUDWLRQ )ODVK 2SHUDWHV RQ 6LQJOH 9 6XSSO\ FP [ FP )RRWSULQW PP 6WDFNLQJ +HLJKW
CJ: Tell us about Computer Interface Consultants.
MLX-1000-XC5V
BRIAN: Some of the circuits I’ve designed have been mentioned in research papers written by our faculty members. So, I sometimes receive requests from professors at other universities to build them such devices. I www.circuitcellar.com
•
CIRCUIT CELLAR®
Starting at $549 Actual Size
9LUWH[ PRGXOHV DUH FDSDEOH RI FRQQHFWLQJ WR 3&, ([SUHVV 6*0,, *LJDELW (WKHUQHW 6HULDO $7$ 86% DQG RWKHU 6HU'HV LQWHUIDFHV YLD KH 0XOWL*LJDELW 6HU'HV 7UDQVFHLYHU 3DLUV
www.modularlogix.com Performance and features vary depending on FPGA model, speed-grade, and end-user design.
August 2010 – Issue 241
BRIAN: Well, I am really a neophyte when it comes to CNC machining, which I just described. I expect it will take me some time to become proficient at it. For that matter, I am scratching my head trying to think of neat things to make with the machine at this point. I am just now finishing off a whole series of small instruments I designed for our new Material Sciences teaching lab. So, it may be six months or so before “hatching season” starts again!
11
N
S W E N CT DU R O EW P Edited by
John Gorsky
DESIGN TOOL EASES AMPLIFIER FILTER DESIGN
Leading Embedded Development Tools...
ZZZDUPFRPWRROV
ZZZNHLOFRP
August 2010 – Issue 241
For Microcontroller:
12
®
6RIWZDUH GHYHORSPHQW WRROV IRU $50 &RUWH[ DQG & 0&8V 5726 DQG PLGGOHZDUH OLEUDULHV 'HEXJ DGDSWHUV DQG HYDOXDWLRQ ERDUGV
The latest version of the popular FilterPro design tool is now available. FilterPro v3.0 offers a new-and-improved user interface and a more accurate and robust filter design engine, thanks to updates, such as the ability to adjust passive element tolerances and view response variations, scale passive component values, and view and export filter performance data to Excel. The tool allows designers to create and edit designs easily using the Filter Design Wizard. Users can design multiple feedback (MFB), Sallen-Key, low-pass, high-pass, bandpass, and band-stop filters using voltage feedback op-amps. FilterPro v3.0 is free and available for download now at Texas Instruments’s website. This new version supports design file migration from FilterPro v2.0 so that designs created in the prior version can benefit from the functionality of v3.0. It also allows designers to easily generate schematics, view frequency and time responses, and print professional design reports containing all design data and schematics to help speed time to market. FilterPro v3.0 supports Bessell, Butterworth, Chebychev, Gaussian, and linear phase filter response types and can be used to design filters from one to 10 poles, providing design flexibility. Support for low-pass, high-pass, notch/band-stop, band-pass, and all-pass phase shift/time delay filters to help ease system design is also included. FilterPro is available for free at the Texas Instruments website.
Texas Instruments, Inc. www.ti.com
For ARM Application Processors: (FOLSVHEDVHG GHYHORSPHQW WRROV IRU /LQX[ DQG $QGURLG 6XSSRUW IRU DOO $50 DSSOLFDWLRQ SURFHVVRUV +LJKSHUIRUPDQFH GHEXJ DQG WUDFH DGDSWHU
1-800-348-8051
CIRCUIT CELLAR®
•
www.circuitcellar.com
The DB9-USB-RS232 range of modules is designed to replace a DB9-based RS-232 connector on an existing board design with a USB 2.0 connector interface. The modules feature a standard USB “mini-B” type of connector in a module that fits the PCB footprint of a standard nine-pin DB-9 connector. The modules are designed to provide a fast and simple method of replacing a DB-9 RS232 interface with USB 2.0 connectivity, without the need to change an existing PCB board design. The DB9-USB-RS232 modules contain all the electronics needed to carry out the conversion between RS-232 and USB. The modules utilize the popular FTDI FT232R, USB-2.0to-serial UART converter IC. The FT232R device converts from USB to a serial UART interface, which is then level-shifted into RS-232 signal levels, within the DB9-USB-RS232 module. Power to the module is supplied by the USB 2.0 connection. The modules support a maximum transfer rate of 1 MBps. The modules are supplied complete with royalty-free drivers, which enable a device to be integrated as an additional COM (virtual) port into an existing software application, thus offering quick and easy installation without the need for custom driver development or user software redesign. The range of drivers includes Microsoft WHQL-certified drivers for Windows-based operating systems and drivers for Linux and Mac operating systems. All drivers are freely available for download from the FTDI website. The modules are available from FTDI’s distribution network or direct from FTDI. Pricing for the DB9-USB-M (male connector version) and DB9USB-F (female connector version) starts at $22.04 for single quantities.
Future Technology Devices International Limited www.ftdichip.com
NPN www.circuitcellar.com
•
CIRCUIT CELLAR®
PSoC CREATOR 1.0 BETA 4.1 PSoC Creator 1.0 Beta 4.1 is now available from Cypress Semiconductor. The big change in Beta 4.1 is the addition of a flash security feature. This allows you to set up the flash memory in the device such that it cannot be read across the debugging interface. The new resource editor displays flash memory addresses in rows, with each row of flash having 256 bytes. Each row, or group of rows, can be assigned one of four protection levels: U – unprotected (default); F – external read protect (factory upgrade); R – external write protect (field upgrade); or W – full protection. This release supports the ES1 (engineering sample 1) and ES2 revisions of PSoC 3 silicon and ES1 of PSoC 5, which will be sampling soon. It also includes free compilers in the distribution: a Cypress-specific version of the Keil C51 compiler (PK51) for PSoC 3 and the Sourcery G++ lite edition from CodeSourcery for PSoC 5. The Beta 4.1 release is an update to all previous Betas. Note that the installer supports archived releases. It defaults to Beta 4.1, but allows you to pick any previous version by selecting a custom installation. You can download it at the Cypress website.
Cypress Semiconductor Corp. www.cypress.com
August 2010 – Issue 241
USB 2.0 MODULE REPLACES DB9 RS-232 CONNECTOR
13
SOLARMAGIC CHIPSET MAKES SOLAR PANELS “SMARTER” The SM3320 SolarMagic is the solar industry’s first in-panel chipset, marking the advent of a new category of solar systems: “smart panels.” SolarMagic provides an innovative solution to long standing problems with solar arrays and their design. Real-world problems lead to mismatch in solar systems, significantly reducing the power output of an array. SolarMagic can recoup up to 71% of power lost to mismatch, regardless of the cell. Packaged as a complete board-level system or available as a chipset, the SM3320 incorporates 10 proprietary analog and mixed-signal integrated circuits, providing highly reliable digital-control combined with analog sensing and communication. Proprietary algorithms apply localized maximum power point tracking (MPPT), extracting the maximum energy available by translating the input voltage and current to the best output voltage and current pair to maximize energy flow. The SM3320 is cognitive: the system senses input voltage and current throughout the array and adjusts to achieve optimum string levels. The SM3320 includes a highly integrated, 99.5% efficient, 350-W tri-mode power converter. To achieve maximum energy harvest, the SM3320 can boost, pass through, or lower the voltage of each panel. Options include fire safety panel shutoff and a set of sophisticated safety mechanisms. The board-level system, measuring 5″ × 3.5″ × 0.5″ and weighing approximately 6.4 ounces, easily fits into a solar panel junction box. Pricing for National’s SM3320-1A1 boardlevel system and SM3320-REF chipset is based on the solar industry standard measure of dollar-per-watt. SM3320 is available now and is priced at less than $0.12 per watt, depending on volume.
National Semiconductor, Inc. www.national.com
August 2010 – Issue 241
NPN
14
CIRCUIT CELLAR®
•
www.circuitcellar.com
CIRCUIT CELLAR VO
T
)
Note that you can get any gain value—including values less than one—with this circuit, by selecting RX and RY appropriately. Note also that the input impedance of each input relative to ground is RX + RY, and the differential impedance is double this value. Answer 2—This circuit is significant because most other op-amp-based amplifier circuits are simply specializations of this one. For example, if you have a singleended source, you get an inverting configuration by applying the source to VN and grounding VP, in which case the upper pair of resistors can be replaced by a single resistor to ground with the equivalent value. Similarly, to get a noninverting configuration, you ground VN. Of course, in the latter case, most designers eliminate the upper voltage divider, replacing it with a single resistor from the source (to match bias currents), which increases the gain to:
VO
T
EQ
Edited by David Tweed
Answer 1—This is the standard four-resistor balanced amplifier circuit, in which:
RY (V − V RX P
Test Your ANSWERS for Issue 240
RY R + Y VP R X RX
However, now the circuit can’t be used for gains less than one. Other special configurations, such as “voltage follower,” can be created by unbalancing the circuit and using different values for the two RX and/or the two RY. Answer 3—Trick question! You don’t need any feedback at all in a buck regulator that’s intended to simply cut the input voltage in half—you just need to drive the switching element with a 50% duty cycle waveform. As long as you pick a coil suitable for the range of load currents expected
What’s your EQ?—The answers are posted at
www.circuitcellar.com/eq/
Answer 4—The first functional difference between these two structures comes into play when the rarely used con nue statement is invoked inside the loop. In the for loop, expr3 is executed after a con nue, but in the wh le loop, it is not. A more precise equivalence would look something like this: for (expr1; expr2; expr3) { ... if (...) continue; ... } expr1; while (expr2) { do { ... if (...) break; ... } while (0); expr3; }
Note that the body of the for loop must be wrapped in a second, inner do ... wh le(0 ; loop (which is executed only once per iteration of the outer loop), and that any continue statements must be turned into break statements instead. Furthermore, if the original for loop has break statements as well, each would need to be replaced with an explicit goto to a label outside the body of the outer while loop. The second functional difference is that in the for loop, expr2 is allowed to be empty, in which case it is assumed to be true. Thus, for (;;) { ... } is the canonical “infinite loop” in C. expr2 must exist in the corresponding wh le loop.
Contributed by David Tweed
August 2010 – Issue 241
You may contact the quizmasters at
[email protected]
(the coil current needs to be continuous), the output voltage will be 50% of the input voltage. If you use synchronous rectification—a second FET that can sink as well as source current—then it works all the way down to zero load current.
www.circuitcellar.com
•
CIRCUIT CELLAR®
15
T
HE CONSUMMATE ENGINEER
by George Novacek (Canada)
Embedded Safety Components fail. It’s your duty as a competent engineer to ensure the effects of failure are predictable and benign. Here you’ll learn to develop and implement basic failure mode analysis.
August 2010 – Issue 241
T
16
he ubiquitous embedded controller! Aircraft, cars, telephones, toys, machinery, and even coffee makers and toasters have at least one. Besides traditional microprocessors or microcontrollers, embedded controllers are built with PLDs, FPGAs, and discrete parts. With PSoCs, such as those made by Cypress Semiconductor, embedded controller design is seemingly easier than ever. Did I say seemingly? Let’s see. Imagine that an appliance manufacturer no longer wants to use traditional sequencers and relays to control a clothes dryer. Instead, he orders the engineering department to design an Electronic Control Unit (ECU)—that is, an embedded controller—to replace the electromechanical bits and pieces. The system designer issues the ECU specification with a black box diagram (see Figure 1) to define the system architecture. So why do I doubt that the ECU design shouldn’t be a piece of cake with a suitable micro or a PSoC and a few external components? While the author of the specification may have omitted to require it, responsible engineers must look at the system architecture and consider what could possibly happen if some component didn’t work the way it was intended due to a failure, misuse, or design weakness. To discharge our engineering responsibility, we must perform a Failure Mode Effects and Criticality Analysis (FMECA) and then take the necessary steps to ensure design safety. Many engineers do it subconsciously, but a formal, documented approach is well worth it, not just for product
safety, but for our piece of mind as well. This simple—yet often misunderstood and underappreciated—common-sense tool should be mandatory for every engineer to use. Commercial programs are available for this task, but a spreadsheet will do. Had an unnamed car manufacturer used it competently even in its most rudimentary form, the media wouldn’t have had stories to write about runaway cars. Let’s develop a basic failure mode analysis of our simple, imaginary system. We’ll base it on the black box diagram in Figure 1 and include the ECU subsystem in Table 1.
BLACK BOX We start by listing all the autonomous function blocks. We do not consider actual circuits at this time, just their functions. On critical systems, we might have to analyze each and every functional block down to its component level, include reliability data, but all that is unnecessary for the imaginary dryer. Under the Failure Mode header in Table 1, we identify all the imaginable failure modes. Include the unthinkable! Don’t assume a “stuck gas pedal” or any other “unlikely” failure cannot happen. Many a system failure is a tangible proof of shoddy engineering where failure analysis took second seat. Under the Effect header in Table 1, we list all the consequences of the identified failure modes. And, finally, evaluating the possible impact of the faults, we assign them criticality values. Aerospace, medical and other industries CIRCUIT CELLAR®
•
www.circuitcellar.com
Number 1
Function block Funct on se ector
2
Door sensor
3
Heater
4
Motor
5
220 V Power
ECU Subsystem 6 Power supp y
7
Contro er modu e nc ud ng I/Os
8
Heater dr ver
9
Motor dr ver
10
Status d sp ay
tr ac tr ac
Failure mode Not work ng at a Errat c work A ways c osed A ways opened Fa ed shorted Part a y shorted Fa ed opened Fa ed shorted Fa ed open
Effect Not work ng Uncommanded operat on Not work ng. Cou d operate w th the door opened Fuse b own. Not work ng May overheat and cause f re Not work ng Fuse b own. Not work ng Motor w not run. Motor or heater may overheat and cause f re
Criticality None Potent a y dangerous None Persona njury cou d resu t None Persona njury or f re cou d resu t None None Persona njury or f re cou d resu t
Fa ed bear ngs No power Undervo tage
May overheat and cause f re Not work ng ECU cou d fa , motor and heater may not work correct y
Persona njury or f re cou d resu t None Damage to the equ pment may resu t
Overvo tage
ECU cou d fa , damage to the motor and the heater
Damage to the equ pment may resu t
No output
ECU doesn’t work, the dryer doesn’t work
None
Overvo tage Undervo tage Var ous software and hardware fau ts
Potent a damage to the c rcu ts, errat c funct on of the ECU
Unpred ctab e funct ona ty of the dryer
Unpred ctab e
Potent a y dangerous
Not work ng Heater stays on Not work ng Motor stays on Incorrect status d sp ay
None Potent a f re hazard None Potent a damage Undes rab e, but potent a y not dangerous
Open Short Open Short Not work ng correct y
Table 1—This table shows the function blocks, failure mode, effects, and more. The ECU subsystem is included. www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
have their own standard levECU els of criticality. In other industries, an engineer can Heater driver Heater develop his own, as I’ve done Function selector (Triac) here in our example. The clothes dryer (system) Controller designer should have specified how faults are to be Motor driver Motor Door closed (Triac) treated. If he did not, now is sensor the time to remind him to do so. The most practical classification for our system Optional 220 VAC Status display Power supply (see text) would be fail passive: if anything goes wrong, the power is removed from the dryer. This can be best accomplished by inserting a contac- Figure 1—A black box diagram of a clothes dryer system tor driven by the ECU in the we add monitors. It is well beyond the scope of this col220-VAC input line, shown as “optional” in Figure 1. umn, but since monitoring the health of the controller Solid state relays have leakage and, therefore, are rarely block is the most important, I’ll mention a few practical acceptable. points. All critical functions in software should be handled by WHITE BOX two independent routines. The function should be exeNow we take a closer look at the ECU white box cuted only if both provide the same result. design. Our aim is to modify the circuits in such a way The most common method for monitoring a micro is a that in the end all effects in the analysis will read “syswatchdog timer (WDT). Many microcontrollers have a tem de-energized” and the criticality “none.” To do this,
17
NEED-TO-KNOW INFO
WDT already on chip. Unfortunately, the usefulness of such a WDT is very much limited. It may be able to detect software failures, but since it shares the substrate with the rest of the micro, it usually fails when the micro fails. A somewhat better option is an external WDT, often coupled with a power supply monitor IC. Such WDTs have only a single line to be toggled by the micro, so there are conceivable conditions for the failed micro to continue to reset the external WDT. A quite reliable WDT can be built in a PAL. It requires the micro to reset the WDT in a predetermined period by continually changed 4-bit nibbles. And always remember: Who watches the watchdog?
Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. To learn more about George Novacek’s design tips and projects, the Circuit Cellar editorial staff recommends the following: — Fault-Tolerant Electronic Systems by George Novacek Circuit Cellar 162, 2004 All electronic systems fail. So, to be a successful designer of embedded systems, you must prepare for system failures and glitches. Topics: Fault Tolerance, Failure, Built-in Test, Redundancy
FAILURE PREPARATION As we move toward more sophisticated, fault-tolerant, embedded controllers, the design of their functionality becomes a mere fraction of the total design effort. Every engineer knows components fail. The question is not if, but when and how? It is every engineer’s duty to ensure the failure effects are predictable and benign. If he neglects to do that, as we sadly see too often, he has no right to call himself Engineer. I
Go to: www.circuitcellar.com/magazine/162toc.htm — Time-Triggered Technology by George Novacek Circuit Cellar 155, 2003 Clearly, the older communications protocols used by the aerospace industry are becoming increasingly expensive to implement. But, as George explains, TTP technology could change the game. Topics: Time-Triggered Protocol, Data Bus, Frame
George Novacek (
[email protected]) is a professional engineer with a degree in cybernetics and closed-loop control. Now retired, he was most recently president of a multinational manufacturer for embedded control systems for aerospace applications in Canada. George wrote 26 feature articles for Circuit Cellar between 1999 and 2004.
Go to: www.circuitcellar.com/magazine/155toc.htm
Learn to make your products
Rugged • Low-Power Fast • Small Easy to Use at the only conference dedicated entirely to flash memory!
August 17-19, 2010 Santa Clara Convention Cetner Santa Clara, CA
Are you struggling with crucial Solid State Drive (SSD) decisions? Can SSDs resolve your application bottlenecks? How can you maximize SSD performance? Flash Memory Summit will explore new frontiers in enterprise storage and help you make the right choices. Summit highlights include:
August 2010 – Issue 241
“Solid state drives will be the biggest change in storage, a total game-changer, and flash will be the dominant type of SSD for the foreseeable future.” Joe Tucci, CEO, EMC
18
Flash Security Workshop SSD Fundamentals Seminar Forums and Tutorials Keynote Presentations Exhibits and Demonstrations All-Industry Reception For details visit
www.FlashMemorySummit.com Circuit Cellar readers: enter code SPGP and get a $100 discount! But don’t wait too long. Early-bird prices are available only through August 11.
CIRCUIT CELLAR®
•
www.circuitcellar.com
The Newest Products For Your Newest Designs Embed Your Innovation into the Market Place.
MRF24J40MB 2.4 GHz RF Transceiver Modu dule le mouser.com/microchipmrf24j40mb
M
USB-COM-PLUS Serial Modules mouser.com/ftdiusbcomplus
Joule-Thief™ Module mouser.com/adaptivenergy_ joule-thief
SocketEthernet IP® Device Server mouser.com/ multitechsocketethernetip
WARNING: Designing with Hot, New Products May Cause A Time-to-Market Advantage.
Wi h the newest embedded products and technologies you can get your designs to market faster. Experience Mouser’s time-to-market advantage with no minimums and same-day shipping of the newest products from more than 400 leading suppliers.
mouser.com
Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
(800) 346-6873
F EATURE
ARTICLE
by Colin O’Flynn (Canada)
Advanced USB Design Debugging As USB becomes more and more ubiquitous, you must have a solid understanding of how the technology works and how you can use it in your designs. Start by studying the advanced features of USB and then move on to working with a USB MCU.
August 2010 – Issue 241
Y
20
ou just read the title of this article, and now you’re probably saying, “Another USB article. What are those Circuit Cellar editors doing?” After all, you’ve been using an FTDI USB-to-serial chip since its introduction almost 10 years ago. And recently, you got rid of the extra chip entirely, moving the USB-to-serial interface into firmware on a USB microcontroller. You are probably in good company: for some reason, the idea that USB is just a replacement for the serial port is a popular one. Sure, you can use USB as a virtual serial port, but then you miss many of the features of USB. This article will first introduce you to some of the more advanced features of USB. I’ll then quickly cover the process of selecting a USB microcontroller, show you how to debug complex USB problems, and finally conclude with tips about where to find more information. The advanced features I’ll cover include a description of various classes, how to combine multiple classes in a single device, and using USB On The Go (OTG). If you aren’t familiar with USB, you might want to read a quick introductory article first. Jeff Bachiochi’s 2004 article “USB in Embedded Design” is a great introduction to some of the technical aspects of how USB works (Circuit Cellar 165).
and presents the microcontroller with bytes of data. This type of chip is very easy to use, and the chip’s vendor should provide drivers for interfacing on the host PC. This might be the easiest method for simply sending some bytes from a custom application to your microcontroller. You don’t need to learn about USB descriptors or transfers, just call the appropriate function on the host PC to transfer a byte. The second method is controlling a USB device peripheral from a microcontroller. This peripheral could be an external chip; but more commonly, many microcontrollers now have a built-in USB peripheral. This is slightly more complex, as the microcontroller needs to deal with USB requests. Your device, however, can appear as a variety of standard devices,
FITTING IT TOGETHER Adding USB to a microcontroller can be done in two main ways. Let’s review. The first involves using an external chip that performs all the USB actions required
Photo 1—An example of debugging a small USB device. The USB analyzer has the USBStick plugged into it. The USBStick has an In-Circuit Emulator (ICE) attached to debug the code. The GPIOs from the USBStick attach to hardware inputs on the USB analyzer. CIRCUIT CELLAR®
•
www.circuitcellar.com
new chip to a board and program it through USB. This section just provided a few examples to whet the appetite. USB provides other classes, such as audio, video, still image, and external printers. There is even the “vendor-specific” class if you have something truly special. A full description of these classes is available from the USB-IF.
giving you the ability to design a device that requires no driver installation or interfaces with third-party applications directly. In this article I’ll focus on using these standard classes with internal peripherals, as opposed to using a simple external all-in-one USB chip.
CLASS SELECTION The USB class helps define the overall function of the device. Selecting the proper class is the most important step; the correct class assures efficient data transfers and easier development on the host computer. Using the appropriate standard means your device could use generic drivers on the operating system and interface to the operating system or third-party software with less work. For example, if you had a data-logging system, you would need some way to dump the logged data. Instead of having a custom application which only runs on certain operating systems, you could have your device appear as a USB flash drive, which the end user can copy data off. The USB Implementers Forum (USB-IF) defines eighteen device classes, each of which may have multiple subclasses. The following will give an example of a handful of these classes. One of the most versatile classes is the Human Interface Device (HID) class, which despite the name could be used in many applications without humans involved. The HID class uses “reports” to send data between the computer and end device. The bandwidth for a full-speed HID device is limited to 64 KBps; the class isn’t designed for streaming video or bulky data transfer. The drivers are included with any recent operating system, and there are examples of how to interface www.circuitcellar.com
•
CIRCUIT CELLAR®
with this class for many different programming languages. Most major microcontroller manufactures include examples of using the HID class with their USB microcontrollers. Finally, certain HID devices will be recognized automatically by Windows without going through the “New Hardware Found” wizard, making the best possible user experience on install. Or perhaps your widget needs to have occasional network connectivity. Normally, you’d be forced to put an Ethernet port and associated controller on it. However, to make a small and cheap device, you could simply use a “virtual Ethernet port” over USB instead. You would have a choice of three classes to do this with. The CDC-ECM class is designed to provide actual network connectivity, such as for a USB-connected network card. The CDC-EEM class is designed for Ethernet emulation instead, basically sending Ethernet packets over USB. Finally, the RNDIS class is a Microsoft standard for sending Ethernet frames over USB. Which one to use will depend on your application and the host operating system’s support of the class. The mass storage class is used by USB flash drives. However, it can be used in a variety of different ways too, even as simple as shipping documentation about your device on the device itself. Almost any operating system won’t require any sort of driver installation, making a very simple interaction with the user. The Device Firmware Upgrade (DFU) class lets you download new firmware. Many USB microcontrollers come preprogrammed with a DFU bootloader, meaning you could just solder a brand
TWO IN ONE The previously mentioned classes all fit one specific function. But your device has multiple functions. What now? Don’t fret and think you must invoke the “vendor-specific” class; USB-IF has already thought of your plight. Your device is a “composite” device; it combines several different functions together into one device. Even if your core device doesn’t have multiple functions, there are still reasons to add another function on. For instance, imagine you had a USB wireless internet stick. When an end user plugs it in, they will require drivers. Instead of having them curse your name, since they can’t connect to the Internet to download the drivers, your USB stick could also include a mass storage interface. The user simply gets the drivers off this mass storage drive, which you have preprogrammed with everything they need. The memory to store these driver files could even be spare program flash on the USB microcontroller. For many classes, you just need a small driver information file (.INF) for Windows, which would only require a few kilobytes of space. The main code in the microcontroller won’t be accessing the files; hence you do not need any complicated FAT or other file-system access code. The code just needs to copy bytes from the USB interface to flash and back, which is a fairly simple job. When debugging code, many developers prefer to litter their code with printf statements, dumping values of variables. Rather than adding a physical serial port, the code can simply add a virtual serial port alongside another interface. Debugging can be performed by the end customer; ask them to execute a certain series of events which causes your device to re-enumerate
August 2010 – Issue 241
Photo 2—The debugging screen associated with the hardware setup from Photo 1. The tasks running in the USBStick toggle the GPIO lines, which allow seeing where USB events are occurring relative to software events. In this case, one task stops running, as the toggling stops, which results in USB requests not being handled.
21
August 2010 – Issue 241
HID
Mass storage
can be normal peripherals. They itself with a debug port. There is Name Value Description do not need to be USB OTG no extra manufacturing cost, as 0xEF bDeviceClass MISC Device Common bDeviceSubClass 0x02 peripherals specifically. That physical debug ports are not 0x01 IAD bDeviceProtocol means your tiny USB widget needed. could have a full-sized keyboard Making a composite device is Name Value Description Config plugged into it or a USB flash easy: simply string together the bLength 8 8 Bytes drive to store files. No longer descriptors for each individual bDescriptorType 0x0B IAD does text entry in small embedclass. All classes share endpoint bFirstInterface 0 Interface 0 ded devices require you to scroll 0, the control endpoint, where bInterfaceCount 2 2 Interfaces IAD bFunctionClass 0x02 CDC through every letter in the your code must process class-spebFunctionSubClass 0x02 ACM alphabet. cific requests for all classes in the bFunctionProtocol 0x01 AT Commands Interface 0 The clever Micro-AB receptadevice. Composite devices may iFunction 0 none CDC-ACM cle can accept the popular Microrequire the use of an “Interface B plug which many devices use. Association Descriptor.” This is This would be the cable used to because initially USB was CDC Class Interface 2 mass plug your device into another designed with the idea that a sinstorage USB host. The Micro-A plug also gle USB interface was associated fits in this receptacle, and when with a single USB function or Endpoint 4 Endpoint 1 Bulk-IN Interrupt-IN so fitted the device becomes a driver. Life as a USB host was USB host. Note the Mini-AB simple—if a device had two interEndpoint 5 receptacle, which you will find faces, it had two functions. Then Interface 1 Bulk-OUT CDC-Data on the Atmel AT90USBKEY some classes came along that board, for example, has been depassociated two interfaces with a Endpoint 2 recated in favor of the Micro-AB single function; for example, the Interface 3 Bulk-IN HID connector. CDC class, which the virtual Some gadgets may never be serial port uses. If you wanted Endpoint 3 Endpoint 6 connected to a computer, and two virtual serial ports in one Bulk-OUT Interrupt-IN only want to use the USB port as device, the resulting descriptor a host. In this case, the device would have four interfaces, classifies as an embedded host which had to be mapped to two dif- Figure 1—An example of using the Interface Association Descriptor is shown here. Notice how the device class is (EH), and will have a Standard-A ferent functions. To bring back changed to the IAD class. The IAD itself is inserted directly receptacle. The EH is still only peace to USB hosts everywhere, the before the two interfaces which are associated with a sinrequired to provide 8-mA current Interface Association Descriptor gle function. If the next function is a second serial port, and support a limited subset of (IAD) was designed to explicitly another IAD would be inserted before the next two interdevices. Remember, though, if group multiple interfaces together faces associated with the second serial port. plugging a standard USB periphinto one function. eral into this EH, it may expect If you wish to have a USB device much more than 8 mA of current. with multiple functions, and any of the USB OTG defines methods of negotiatStandard USB hosts must provide up to functions use more than a single intering who takes over the “host” role 100 mA of current before enumeration; face, you will require an IAD. An exam- between the two devices, swapping a standard USB peripheral may expect ple IAD is shown in Figure 1. This roles, detecting the attachment of that 100 mA. example has three functions: a serial devices without fully powering the bus, With the idea of what features are port, a mass storage interface, and an and even requesting power on the USB available in the USB specification, next HID device. Only the descriptor values bus when no power is present. we will look at how we can use them. which are modified by using an IAD are USB OTG significantly relaxes the shown to save space. requirements of the “host” device, requiring it to only support certain SELECT A USB MCU devices, and supply a minimum of 8 USB TO GO The most basic requirement when mA of current. There is no requirement designing a device is that it has One of the more exciting advanceto even support the hub class, meaning enough endpoints for your selected ments in USB is the USB On-The-Go a very simple host will only work with class. Table 1 shows some examples of (OTG) and Embedded Host (EH) supplea single directly connected device. The useful USB classes and how many endment. USB OTG is designed to allow lower minimum supply current recogpoints are required, besides the default two “peripheral” devices to connect nizes that USB OTG devices are norcontrol endpoint. For example, to comtogether without a traditional USB mally battery powered, and the 100-mA bine two HID functions, a mass storage host. For example a camera could plug current minimum required by a normal function and a printer function, in one directly into a printer, using the same host is not reasonable for these devices. device would require one endpoint for USB port that also allows the camera The supported devices themselves each HID device, two for the mass and printer to plug into a computer.
22
CIRCUIT CELLAR®
•
www.circuitcellar.com
Extra Endpoints 1 3 3 2 2 2 1 0
Interfaces 1 2 2 2 2 1 1 1
Table 1—This is just an example of a few different USB functions, and how many extra endpoints they require. The control endpoint is not included in this, as every class requires the control endpoint. storage, and a one more for the printer. This makes five unidirectional endpoints, plus a bidirectional one for the control endpoint, or six in total. Now take a look at Table 2, which has some example low-cost microcontrollers with integrated USB peripheral interfaces. Notice how many endpoints each chip gives you. This should give you a rough idea of what device could support what tasks. When comparing devices, even from the same manufacturer, be careful of various ways of representing the same information. Some chips have bidirectional endpoints, where each endpoint includes an OUT and an IN direction. Other chips only have unidirectional endpoints, where each endpoint is either an IN or an OUT endpoint. So a chip with 16 bidirectional endpoints may advertise itself as having 32 total endpoints. Remember, one of those endpoints must be used for the control endpoint, and this endpoint is always bidirectional. Another company may advertise their chips as supporting six endpoints, which is actually six unidirectional endpoints and one bidirectional endpoint dedicated for the control endpoint. The controller chips have buffers dedicated for each endpoint. For maximum speed, these should be at least double buffers; that allows you to, for instance, write to one buffer while the USB controller is reading from another buffer. Some companies quote this buffer space as separate from total RAM, while some group all the RAM together and quote that as total system memory. Also, some chips advertising “OTG” support may only support a subset of www.circuitcellar.com
•
CIRCUIT CELLAR®
OTG commands. For example, they might really only support using the device as an embedded host, and not support some of the commands which two OTG devices use to swap roles. Now that you’ve waded through the datasheets and selected a promising device, how do you get started? With an example of course! Most companies offer examples which will get you started, and a number of community examples are available as well. For the Atmel AVR microcontroller, Dean Camera’s
LUFA provides an open-source framework that has device examples for keyboard, mice, audio, serial, mass storage, Ethernet, and more. It has embedded host examples to interface with USB keyboards, mice, mass storage, serial, and still image devices. There is even an example project using LUFA which interfaces to a mobile internet USB stick from cellular providers, which gives your device Internet connectivity. The hardware to run the examples can be purchased at a low cost: Atmel’s
August 2010 – Issue 241
Function HID CDC-Serial RNDIS Ethernet CDC-ECM CDC-EEM Mass Storage Printer DFU
23
Company Atmel 8-bit AVR Atmel ARM Atmel 32-bit AVR Microchip 8-bit PIC Cypress M8C Freescale HC08S Freescale ColdFire
Part number AT90USB1287 AT90USB162 AT91SAM7S64 AT32UC3B064 PIC18F66J55 CY7C64355 MC9S08JS8CWJ MCF51JM64VLD
Cost/$100 (USD) 9.24 2.24 3.9 3.81 3.1 3.69 1.14 3.39
Flash (KB) 128 16 64 64 96 16 8 64
SRAM (B) 9024 688 16854 17344 3904 1536 768 16,384
EPs 6 4 3 6 30 8 6 30
USB Features Device + OTG Device Device Device + OTG Device Device Device Device + OTG
Table 2—This is an example of several different microcontrollers with integrated USB cores. The number of endpoints does not include the control endpoint; this is the number of spare unidirectional endpoints available. The SRAM size is available including any dedicated to USB. All these chips were chosen as they are physically in-stock at distributors, and not just a datasheet full of wishes. AT90USBKEY costs $30. Since you can program the key through the main USB interface, you don’t even need any additional hardware. Now you’ve seen the new features available in USB, learned about what supports them, and downloaded example code to see how to use them. In our fantasy design world that would be enough, we’d go home with another project done. In the real world, our computer crashes, our car doesn’t start, and the code needs debugging.
August 2010 – Issue 241
PROTOCOL ANALYZER
24
Debugging USB requires a special tool: the USB Protocol Analyzer. The initial choice for a protocol analyzer will seem to be separated into two sides: using a software USB analyzer and using a hardware USB analyzer. As shown in Figure 2, the software analyzer sniffs the traffic between the operating system and the USB host controller. This is an important distinction, as it is only possible to see the higher-level USB Request Blocks (URBs) and not the byte-level traffic. The URBs will include the data in each USB packet; however, it would not include information such as knowledge about how many retries were required before a USB operation succeeded or any malformed packets on the bus. By comparison, a hardware USB analyzer will see all the traffic as it occurs on the bus. This includes information about retries, malformed packets, and accurate timing information. When troubleshooting problems with sleep modes, the USB hardware analyzer will be required since the analysis
computer will be different from the host computer. The host computer is being put to sleep, which will make it difficult to see what is happening if the analyzer is running on that same computer! Finally, to debug USB OTG devices you will again require a hardware USB analyzer since there is no computer host. An additional benefit of hardware analyzers is they can help synchronize events within your embedded code to the USB events. This is done through hardware inputs on the analyzer, although not every analyzer supports this. The microcontroller can toggle outputs as a result of certain internal events—maybe error conditions or if a variable becomes set to an invalid value. These outputs are connected to inputs on the hardware analyzer, and it is trivial to see that immediately before the code fails a larger than expected packet is received, for example. The normal tool of choice for
User-mode software Software USB analyzer
Kernel-mode software USB Host controller
Hardware USB analyzer Device under test
Figure 2—The software USB analyzer is inserted at a higher layer than a hardware USB analyzer. When debugging problems on your device, the hardware USB analyzer is closer to your device. The software USB analyzer has additional layers separating your device and the analyzer.
microcontroller work, the in-circuit emulator, can be tricky to use when debugging USB code. The action of breaking the code flow to view variable states may result in the USB device becoming nonresponsive to the host. As an example of this, I used the Total Phase Beagle 480 protocol analyzer to debug a problem where SETUP requests on endpoint 0 were ignored. However, bulk IN requests on another endpoint were being processed; obviously the code had not stalled completely, but something was wrong. To help understand the situation, I set up the hardware in Photo 1. The small USB stick can be seen plugged into the Beagle 480. In addition, the hardware emulator connection along with the wiring to the hardware inputs of the Beagle 480 can be seen. In this case, the task which processes the SETUP requests on endpoint 0 toggles “input 1.” Photo 2 shows a screen capture of the result. You can see that processing of the task stops, and using the connected emulator to pause the code at this stage made quick work of the bug. The example problem was in fact a real one that popped up while writing this article. The analyzer simply had the proper resources to quickly eradicate this bug. Before this, I had struggled with software analyzer tools to find the cause; the intermittent nature of the bug brought much frustration. If the hardware analyzer supports a software API as well, it can be used to help debug more complex problems. This allows monitoring the hardware inputs to look for certain sequences of events, or even controlling both the hardware analyzer and the device under test with one program. And when dealing with custom classes which have no decoders available, the software API may be your only hope to make sense of the raw data. For hobbyist or unfunded student use, however, undoubtedly the price of the analyzer is the major point of interest. For these, the free analyzers simply have no competition. For business or funded student use, the problem becomes more complex. The proper tool helps save enough time to CIRCUIT CELLAR®
•
www.circuitcellar.com
quickly pay for itself. If selecting a tool for purchase, be sure to check that it supports features you do use and plan to use shortly. Also check the update policy; when I started using the Beagle 480 it only supported providing detailed information about a few USB classes such as HID and Mass Storage. A later update added support for a range of new classes, including one I was using which made debugging easier. As Total Phase seems to have free updates forever I don’t need to worry about going through the hassle of getting the appropriate license files, just download and run.
Beyond Logic has a series of articles called USB in a Nutshell. You can download the entire series at no cost in one PDF file that is only 30 pages. I Colin O’Flynn is a graduate of Dalhousie University in Nova Scotia, Canada. He has been working with electronics for years, and more recently has been consulting for projects related to 802.15.4 wireless communications. He currently lives in Edinburgh, Scotland, and may be reached at
[email protected].
RESOURCES The USB-IF defines a variety of tests for official verification. They can be downloaded from USB-IF by looking at the “Compliance” section. They include a detailed description of the test procedure which you can follow. Since you are using a proven USB controller chip, connectors, and cables, you should not have issues at the physical layer. Your biggest issues will be at a higher layer, which is easier to verify. The USB-IF makes available for free a “USB 2.0 Command Verifier.” It allows you to verify descriptors or test various class-specific commands. It switches in a special USB stack, which unfortunately means software analyzers are unable to sniff this stack. The test procedure also goes over the importance of testing your device in a range of situations: different host controllers, different topologies, and different user interactions. When verifying, remember that issues such as unreliable data transport or your code being too slow to respond to requests may be totally invisible to a software analyzer, or in fact any higher-level verification. The lower-level protocols have already dealt with data retransmissions and do not pass this information up the stack, unless there was a total failure.
USB INFO Hopefully this article brought to your attention the many interesting features available with USB. Remember that there is a variety of resources available, and you will find useful information and tools no matter what your experience, funds, or background. In order to assist you I’ve put together a few resources I found useful myself. You will find references to how long the official USB Specification is (over 600 pages), however this unfairly includes many pages of information which can be quickly glanced at such as dimensions on connectors. Even if you do not care about specific details, it does have several high-level sections that are a great read. The USB Implementers Forum also produces various tools and other documentation of great use; don’t miss out on all they have to offer. No article would be complete without mentioning Jan Axelson’s book USB Complete, which is now in its fourth edition. This goes over a wide range of information on the USB specification. Axelson’s website (www.lvr.com) has a “USB Central” section that includes links to a variety of other USB articles that I won’t list here to save space. www.circuitcellar.com
•
CIRCUIT CELLAR®
USB Specifications, USB Implementers Forum, www.usb.org/developers/docs/. J. Axelson, USB Complete, Lakeview Research, 2009. C. Peacock, “USB in a Nutshell: Making Sense of the USB Standard,” Beyondlogic.org, 2002, www.beyondlogic.org/usbnutshell/usb-in-a-nutshell.pdf.
SOURCES AT90USBKEY Demonstration board Atmel Corp. | www.atmel.com Beagle 480 protocol analyzer Total Phase, Inc. | www.totalphase.com
NEED-TO-KNOW INFO Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Colin O’Flynn’s Issue 241 article, the Circuit Cellar editorial staff highly recommends the following content: — Create a USB Virtual COM Port by Jan Axelson Circuit Cellar 217, 2008 The right firmware can make a USB device appear as a virtual COM port. Here you learn to design and program your own USB virtual COM port device. Topics: USB, COM Port, Bridge, UART, CDC Go to: www.circuitcellar.com/magazine/217.html — USB in Embedded Design by Jeff Bachiochi Circuit Cellar 165, 2004 Start educating yourself about USB technology. Serial and parallel ports may soon be things of the past. Topics: USB, Hub, Connectors, Interface, Enumeration Go to: www.circuitcellar.com/magazine/165.html
August 2010 – Issue 241
VERIFICATION
25
BOARDS, BOOKS, DVDs AND MORE AT WWW.ELEKTOR.COM/SHOP
Elektor Shop The world of electronics at your fingertips!
New! For beginners and exper
50 PIC Microcontroller projects This book contains 50 fun and exciting projects for PIC microcontrollers such as a laser alarm, USB teasing mouse, youth repellent, soundswitch, capacitive liquid level gauge, talking microcontroller and much more. You can build the projects for your own use. Several different techniques are discussed such as relay, SPI, RS232, USB, pulse width modulation, interrupts, analog-digital conversion (and the other way around), 7-segment display and even CAN bus. 440 pages • ISBN 978-0-905705-88-0 • $58.10
nd ordering at a n o ti a rm fo in Further tancelearning is /d m co r. to k le www.e
Get started quickly and proceed rapidly
Books
Python Programming and GUIs Distance Learning Course This book is aimed at people who want to inter-
Programming Embedded Microcontrollers
face PCs with hardware projects using graphic
In this course you will learn how to program an embedded microcontroller. We will start with
user interfaces. The programming language used
the absolute basics and we will go into a lot of detail. You cannot learn about software without
is Python, an object-oriented scripting language;
understanding the hardware so we will also take a close look at the components and schemat-
a higher level language than, say, C. The book
ics. Gradually the course will become more complex as we move into the more advanced
guides you through starting with Linux by way of
subjects. At the end of the course you will be able to design your own embedded applications
a free downloadable, live bootable distribution
and write the appropriate software for it. From a flashing LED to a USB controlled LCD screen,
that can be ported around different computers
from analog signals to interrupt driven high frequency sound, from frequency sampling to a
without requiring hard drive installation. Practi-
digital thermometer, you will master it all. Your course package consists of a Courseware Ring
cal demonstration circuits and downloadable, full
Binder, a CD-ROM including software and example files and a special application board. On-
software examples are presented that can be the
line support is available at the Elektor Forum.
basis for further projects.
747 pages • Art.# 15033 • $645.00
224 pages • ISBN 978-0-905705-87-3 • $47.60
Prices and item descriptions subject to change. E. & O.E
CD/DVD-ROMs
New! Elektor’s Components Database
CD ECD 5
Reign with the Sceptre
InterSceptre
ECD 5 gives instant access to data on more
This open-source & open-hardware project
Recently, Elektor introduced Sceptre, a fast
than 69,000 components! The program pack-
aims to be more than just a little board with a
prototyping system fitted with a 32-bit
age consists of eight databanks covering ICs,
big microcontroller and a few useful peripherals
microcontroller. Even on its own, this board will
transistors, diodes and optocouplers. A further
— it seeks to be a 32-bit ARM7 fast prototyping
let you produce some great results, but if we
eleven applications cover the calculation of, for
system. To justify this title, in addition to a very
add an extension board to make it easier to
example, zener diode series resistors, voltage
useful little board, we also need user-friendly
access all its peripherals, the Sceptre platform
regulators, voltage dividers and AMV’s. A col-
development tools and libraries that allow fast
becomes downright powerful. What’s more, if
our band decoder is included for determin-
implementation of the board’s peripherals. Am-
you fit this extension board into a suitable case,
ing resistor and inductor values. All databank
bitious? Maybe, but nothing should deter you
you’ll be able right from the start to develop
applications are fully interactive, allowing
from becoming Master of Embedded Systems
a prototype that you can use ‘properly’ in a
the user to add, edit and complete component
Universe with the help of the Elektor Sceptre.
installation, with no trailing wires or bits of
data.
PCB, populated and tested,
ISBN 978-90-5381-159-7 • $40.20
test software loaded Art.# 090559-91• $143.60
sticky tape holding everything together. Now that’s what you call fast, convenient prototyping! Kit of parts, contains PCB and components Art.# 100174-71 • $ 187.10
Bestseller! Embedded USB Know How
CD USB Toolbox This CD-ROM contains all the essential informaUSB interface. It includes a large collection of
www.elektor.com/shop
UniLab A power supply with adjustable output voltage and current limiting is part of the basic equip-
data sheets for specific USB components from ment of every electronics lab. However, the a wide range of manufacturers. USB Toolbox increased complexity of a switch-mode design provides information on all ICs suitable for difscares away many potential builders, even ferent applications. A sub-division has been though it actually isn’t all that complicated if made in controllers, hubs, microcontrollers you use a suitable combination of well-known and others. What is perhaps more interesting technologies. This circuit is suitable for building for many designers however, is the extremely extensive software collection which contains drivers, tools and components for Windows, Delphi and various microcontroller families. ISBN 978-90-5381-212-9 • $32.10
Elektor US PO Box 180 Vernon, CT 06066 USA Phone: 860-875-2199 Fax: 860-871-0411 E-mail:
[email protected]
a single or dual power supply. PCB and all components, less power transformer Art.# 090786-71 • $103.30
Kits & Modules
tion a designer needs to start working with the
Elektor is more than just your favorite electronics magazine. It’s your one-stop shop for Elektor Books, CDs, DVDs, Kits & Modules and much more!
F EATURE
ARTICLE
by Aubrey Kagan (Canada)
The 4-to-20-mA Current Loop The 4-to-20-mA current loop has been around for a long time, and it isn’t going anywhere despite a wide range of fieldbus options. If you design applications for industrial electronics, you’re destined to use a 4-to-20-mA interface (if you haven’t already).
I
t is now over 50 years since the 4-to-20-mA current loop was introduced as a means of transmitting an analog signal in an industrial environment. Based on the fact that new silicon is still being designed, it appears to be holding its own against challenges from the plethora of fieldbuses that purport to replace it. In my opinion, its longevity is a result of one thing—simplicity for the user. A power supply, a transmitter, a receiver, and two to four wires is all it takes. A voltmeter and a milliammeter are all that’s needed to set it up, and someone with a basic electrical background can do it. A massive installed base hasn’t hurt, I’m sure. There used to be a 20-mA digital transmission standard used in the days of teletypes (predating RS-232). It should not be confused with the 4-to-20-mA current loop, which is decidedly not the same thing. The 4-to-20-mA current loop consists of a transmitter and receiver connected by conductors. The transmitter sends an analog current where 0% of the input signal is represented by a 4-mA current flowing in the circuit. As the input signal increases through to 100%, the current linearly (in ideal circumstances) increases to a maximum of 20 mA. I have seen other ranges mentioned in the literature: 0–20 mA, 5–25 mA, and 10–50 mA. But, despite having seen scores of projects using current loops, I was asked only once for 0–20 mA. Every other one has been 4–20mA.
transmitted over any distance. Given the voltage drops at the transmitter and receiver (more of this later), the only limitation is the volt drop (= current × resistance) over the length of wire. Several hundred yards is not uncommon and can be stretched to thousands. In addition, it is also inherently resistant to induced noise because of its differential nature. In some receiver configurations (transformer-coupled, for instance), the load is nonlinear, but this does not affect the current flow. Finally, it is possible to connect receivers in series—provided the inputs are floating—which can be very convenient. For instance, you could connect a valve and meter in series (subject to voltage drop restrictions) so that it is possible to see what current is actually driving the load without affecting the load. One of the most frequently asked questions I’ve seen is why there is an offset of 4 mA (sometimes called “live zero”). The original reason appears to be that the current loop was originally intended to duplicate a pneumatic signal in which pressure below a certain minimum would be considered a
August 2010 – Issue 241
RAISON D’ÊTRE
28
I don’t know if it is the nature of the human brain or just the way electronics is taught, but we engineers seem to see the world as having a defined voltage and the current will just flow subject to Ohm’s Law. If a current-limiting effect occurs, the voltage will change. Sometimes it’s preferable to treat the world from a different perspective with a defined current with resultant voltage drops. (Ohm’s Law still applies!) The current is affected when the total voltage drop exceeds the voltage available. There are several advantages when working with a current. A current flows in a closed loop so the information can be
Figure 1—The generalized current loop system. From Kirchoff’s voltage law, V S = VT + 2 × VC + VR, where VS is the supply voltage, VT is the voltage across the current transmitter, VC is the drop over one wire length of the cable, and VR is the voltage dropped across the load (or loads). CIRCUIT CELLAR®
•
www.circuitcellar.com
a)
b)
c)
Figure 2a—This is a two-wire transmitter with a three-wire receiver. b—This is a three-wire transmitter with a two-wire receiver. c—This is a four-wire transmitter to four-wire receiver. There would have to be some form of level shifting or isolation in both the transmitter and receiver.
words, VCOMPLIANCE > (2 × VC ) + VR to guarantee system operation. Most industrial systems use 24 VDC as the system power supply. This means that there is generally a fairly large voltage range for the compliance. VT is not constant, varying to force equality in the Kirchoff voltage equation. Because VT can be quite large, there is sometimes a concern with the power dissipated in the transmitter which is given by VT max × 20 mA. Depending on the system’s compliance, there also may be a problem with devices intended for the Intrinsic Safety segment of the industry when the elevated voltage may pose a spark risk. When you look at linear application notes, current sinks are always simpler to implement than current sources. As far as any current loop is concerned, it really doesn’t matter which approach is used. However, because some receiver loads are connected to the return of the power supply, the transmitters will be current sources in the vast majority of commercial products. In the industrial world, the potential of the ground in one part of the shop floor can be many volts different to another. Generally speaking, a current loop is immune to this effect since the current will flow in a closed loop. But depending on the system configuration
(see Figure 2), there can be some interrelationship between transmitter and receiver supply voltages that can lead to system malfunction. One solution is to introduce isolation into the loop so that there is no galvanic connection from the electronics associated with the transmitter to the electronics associated with the receiver. Isolation has the additional benefits of low-pass filtering, adding surge immunity and allowing series connection of several receivers subject to the compliance constraint. An alternative to isolation could be to use a differential amplifier (like an instrumentation amplifier) so that the signal can be floating with respect to the receiver’s ground. The load in the receiver is frequently a resistor, so VR is easy to calculate. In some cases, the loop power is used to create an isolated power supply using a transformer. As a result, the transformer’s output load is reflected to the input and can be dynamic. In other cases, the voltage for the receiver’s electronics is derived by passing the current through a Zener diode, which is nominally a fixed voltage. In short (no pun intended), take care when evaluating input impedance to a receiver. It is possible to set up the 4-to-20-mA current loop in three ways that describe the signal and power line configurations.
a) zero condition. So, the 4 mA continues this benefit since it is possible to detect when the current loop is open. However, there is an even greater advantage. This 4 mA can be used to power the electronics of the transmitter or receiver and thus allow for two-wire operation with the associated cost reduction in wiring and number of power supplies.
b)
Figure 1 shows a generalized current loop system. The voltage across an ideal current transmitter VT would be zero—but as my mother always told me, this isn’t a perfect world. There is also a minimum for VT, and below this the transmitter starts to misbehave. The compliance of the system is defined as how much voltage is available for correct operation and is given by VCOMPLIANCE = VS – VT min. In other www.circuitcellar.com
•
CIRCUIT CELLAR®
Figure 3—Input Configuration. a—This is the simplest possible circuit. The ground is common throughout, so no additional receiver could be added between I– and the transmitter. b—This circuit indicates how a Zener diode can be used to power the circuitry. Note that the instrumentation amplifier (IA) must be able to work at under 2.5 V and must have a common-mode range outside its positive supply rail.
August 2010 – Issue 241
SYSTEM OPERATION
29
available in a somewhat dated 16-pin DIP package, so quite obviously most designers opt to roll their own. If desired, the initial conversion can then be isolated using a linear optocoupler, a voltage-to-frequency converter driving a digital optocoupler or a transformer, an ADC followed by digital optocouplers, or some other technique. Remembering my mother’s admonishment on the state of the world, take care to protect the inputs to the electronics against spikes, misconnections, and other mishaps even though this is not shown here.
August 2010 – Issue 241
Figure 4—Roll your own current transmitters. This is a three-wire transmitter, defining Z as (1/R5) + (1/R4) + (1/R6), X as (1/R5)/Z, and Y as (1/R4)/Z. IOUT = (VIN × A + VREF × B)/R3.
30
THREE-WIRE TRANSMITTER
If you are creating a three-wire transmitter, Figure 4 would be a good starting point for a home-made design. The input voltage is proportionally summed with a referA two-wire system relies on the 4-mA offset in the signal ence voltage in order to create the 4-mA offset. If your to power either the transmitter or receiver, or both. In a input voltage range starts at 0 V,this is fairly easy otherthree-wire system, the associated electronics needs more wise the starting value will affect the initial condition. The than 4 mA to operate and so power is carried on a third op-amp A2 adjusts its output to equalize the voltage at its wire. I suppose it is possible to create a transmitter with inputs. As a result, the current through Q2 (and Q1 as you some kind of differential output, but every case of a fourwill soon see) is VEFF/R3. VEFF is the resultant voltage at wire transmitter that I have seen has an output isolated from the power supply. In any event, a four-wire system the positive input of A2. This current is drawn from the has two power wires and two signal wires. Since electronsupply through R2 causing a volt drop from the power supics have become more “intelligent” over the years, someply. A1 acts to equalize the voltage at its inputs and mirtimes over-range and under-range conditions can be used to rors the current through R1 provided R1 equals R2. You indicate fault and alarm conditions, although there is no need to select an amplifier that can run at the desired supstandard practice on this. ply voltage, but you also need to take care of the input Obviously, the system’s accuracy and linearity depend on voltage range since the inputs to A1 will be operating near the performance of the individual components, but there the supply voltage. R1 and R2 can be used to reduce the input can be some confusion concerning the definition of linearivoltage into the range, but there is a trade-off in the power ty. It is normally the deviation of the actual reading at a dissipated in them and the transmitter’s compliance. particular output from the theoretical value based on the Calculating the component values requires setting up two given input, divided by the range of the output. But is the equations for the end conditions of 4 mA and 20 mA. If you range 20 mA or 16 mA since the system zero should be cal- choose to add trimming resistors for zero (in series with R4) ibrated at 4 mA? Obviously, using and gain (in series with R5), remem20 mA will yield better results. ber that they will be interactive and Specmanship raises its ugly head calibrating will have to be an iterayet again! The response time of 4tive process. If the transmitter is to-20-mA systems is typically very being driven by a DAC, the calibraslow, normally with a maximum of tion can done by adjusting the D/A 10 Hz, although there is no stanoutput until the desired current is dard in this regard. seen and then “remembering” those values in nonvolatile storage. The desired output is calculated proporRECEIVER tionally to the upper and lower setReceiving a 4-to-20-mA signal is tings. Often the 4-mA offset is gennormally done by passing the curerated entirely in software with the rent through a resistor and processonly disadvantage being that the ing the voltage. It is rather comdynamic range of the DAC is mon to see a 250-Ω resistor used reduced. The Excel worksheet that generates a voltage of 1 to 5 V. (three-wire transmitter) posted on Some possible input configurations Figure 5—This is a two-wire transmitter. I = (VIN LOOP the Circuit Cellar FTP site will you can be seen in Figure 3. There is × (R3/(R1 × R4))) + (VREF × (R3/(R2 × R4))). R5 help calculate the values. only one dedicated IC for this purshould be equal to the paralleled values of R1, R2, pose, the RCV420 from Texas and R3. Often a Schottky diode is connected Instruments. It merely uses an TWO-WIRE TRANSMITTER between the quasi-ground and the positive input of internal resistor connected to a dif- the op-amp (anode to ground) to protect the input The circuit for a two-wire transfrom negative voltages. ference amplifier, and it’s only mitter, shown in Figure 5, appears in CIRCUIT CELLAR®
•
www.circuitcellar.com
many places in technical literature with some minor variations, but the analysis is generally omitted. I was lucky enough to be at a Texas Instruments seminar where the details were provided. This circuit becomes easier to understand if you realize that a quasi-ground is created at the emitter of transistor. This ground will actually move up and down relative to the system ground as the current changes, but if you make your measurements relative to this point the readings make some sense. It is still a very difficult circuit to debug because it needs to be almost working before you can make any measurements using the quasi-ground as a reference point. The input voltage is relative to the quasi ground and any additional circuitry is powered from the reference voltage and the quasi-ground. Just remember that connecting the quasi-ground to system ground (the ground powering the 4-to-20-mA loop) may result in circuit destruction. This can happen inadvertently as in the case of a grounded thermocouple input or even as a result of connecting the negative lead of an oscilloscope. When it is working, the current flows though the ILOOP+ terminal and splits in part through the voltage reference and part through the transistor. Remember that you only have 4 mA to distribute and so the quiescent current
of the reference plus whatever electronics you are powering is limited to that value. The reference generates the supply voltage for the op-amp and the reference voltage for the 4-to-20-mA offset. It could also be used to power additional circuitry. The input voltage is summed with the offset using the input resistor network R1 and R2. Analysis of the circuit is best done using Kirchoff’s Law on currents (the sum of currents into a node is zero). Consider the node at the positive input of the op-amp: ( I LOOP × R 4 ) VIN VREF =0 R + R − R3 1 2
This can be rewritten as: R3 R3 I LOOP = VIN × + VREF × ( R1 × R 4 ) ( R 2 × R 4 )
Creating two sets of equations based on the initial conditions of 4 mA and 20 mA will result in two equations with four variables, allowing two degrees of freedom. Of course, if you can ensure that VIN at 4 mA is zero, it makes things simpler. Refer to the “Excel and Resistor Values” sidebar for
You can use Excel to solve the simultaneous equations with four variables to find suitable resistor values. There were three seminal events that led to my series of articles on using Excel in electronics that appeared in Circuit Cellar Online. Discovering how to use a spreadsheet (I was using Quattro Pro at the time) to solve for the resistor values in the circuit of Figure 5 was the third. The worksheet presented here was developed in Excel 2003, but the technique should work in almost any version. Before using it you will need to install the Analysis Toolpak Add-in and the Solver Add-in that are shipped with Excel. For my own historical reasons, I will explain how to generate the worksheet for the two-wire system, but I have included a worksheet for the three-wire as well. In general we tell “Solver” which cells can be changed to affect a “target” cell. These changes are subject to certain constraints that we will also create. Solver then adjusts the cells in sequence until it finds a solution (or not!). It may not be the optimal solution, but as we learn more about the system we can change the initial values to nudge the solution in the direction that we would like (see Photo 1). The formula for ILOOPMIN and ILOOPMAX only differ in the cell used for VIN in the expression for ILOOP. You can see the formula for ILOOPMAX (in cell B17) in the formula bar at the top. After data is entered, we invoke Solver (from the Tools menu). Note that the utility will try to adjust the values so that ILOOPMAX (in “Target Cell”) equals 20 mA. Only one target cell can be used, but we can work around that by adding the second as a constraint which you can see as ILOOP in the constraints window. Excel is allowed to adjust the cells associated with the resistor values of R1, R2, and R3. I wanted R4 to be a nice round (and low) value, so it was excluded from the permisPhoto 1—You can use an Excel spreadsheet to solve for sible cells to adjust. As additional constraints, the resistors are the resistor values in a circuit. You can generate a worklimited to positive values to preclude impossible solutions. sheet for exactly what you need, whether it’s for a twoClicking on the Solve button arrives at the results you can see. wire system or a three-wire system. Sometimes there may be no solution and you have to change other values to get a feel. Under the Options button are some features that may help. I initially started with VIN max at 1V, and Solver could not find a solution. I allowed the variable cells to include B8, and I soon understood where the problem was. I could then fix B8 and find the solution using only the variables that I wanted to.
www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
EXCEL AND RESISTOR VALUES
31
Manufacturer
Device
TI
XTR300
2-Wire
Vo tage or current output, source or s nk
XTR110,
Analog Devices
Vo tage nput, current output
XTR111, XTR117
Y
Vo tage nput, current output
XTR101, XTR105, XTR106, XTR108, XTR112, XTR114, XTR115, XTR116
Y
S gna cond t on ng nput, current output
AD5412, AD5422
DAC p us vo tage and current outputs
AD5750 AD421
Vo tage and current outputs, m cro conf gurab e ranges Y
AD5410, AD5420 AD5421 AD694
Analog Microelectronics
DAC p us current output, HART compat b e DAC, current output
Y
AD5422 Maxim
Comments
DAC, current output DAC p us vo tage and current outputs
Y
Current output
MAX5661
DAC p us vo tage and current outputs
MAX1365, MAX1367
D g ta pane meter w th current out, ana og n
MAX1366, MAX1368
D g ta pane meter w th current out, m cro nterface
MAX15500/1
Vo tage nput/current or vo tage output, m crocomputer con f gurab e
MAX1452
Y
S gna cond t on ng nput, current output
AM400, AM600
Y
Vo tage and current outputs, s ng e ended and d fferent a nputs
AM460, AM402, AM422, AM462, AM452
Y
S ng e ended and d fferent a nputs p us HART
August 2010 – Issue 241
Table 1—Hardware Current Transmitters. Rather than create a complex table, I have accumulated some numbers where the difference between the parts is subtle since you will have to read the datasheet closely anyway. With a little bit of thought, any 2-wire device can be made to look like a 3-wire, so there is only a notation for 2-wire capability.
32
CIRCUIT CELLAR®
•
www.circuitcellar.com
information about calculating the values with Microsoft Excel. There is an Excel worksheet (two-wire transmitter) on the Circuit Cellar FTP website to help calculate the values. Once again calibration with the use of zero and range potentiometers (in series with R1 and R2) will be interactive needing iterative calibration. Use of a micro with a loop powered transmitter should be approached with caution. The low operating currents quoted by the micro manufacturers are average currents and may not include startup current surges that occur as the unit turns on and internal peripherals are initialized. If at any stage the current draw exceeds the capability of the loop, the micro will choke and never complete start up. You cannot judge this until you have actually prototyped the micro in both hardware and firmware. I know because I had to make the same project 3 times before I found a micro that would work.
out if the current loop driver or receiver is low impedance. Some of the controllers in Table 1 claim to be HART compatible. The HART signal most likely will not pass through any isolation barriers there may be in the circuit. There are several manufacturers of HART modems that are used in parallel with the 4-to-20-mA current source. They include Maxim (DS8500), Symbios Logic (SYM20C15), SDIC (SD2015), ON Semiconductor (A519HRT), Smar Research (HT2012), and others, I am sure. The HART standard is based on the Bell 202 standard for modems. The FSK signal has no DC component and averages to 0VDC so no offset is added to the current signal. The low frequency of the current loop means that the 1,200 Hz/2,200 Hz of the FSK signal can be easily separated by filtering. When deployed on the current loop wires, the HART system is peer to peer, allowing only one-onone communication. Details of the communication are beyond the scope
of this article, mainly because I have no real experience on the topic.
STAYING POWER The failure of the different fieldbus protocols to coalesce to a unified standard and the huge installed base of 4-to-20-mA systems combined with its simplicity of use means that the current loop will be around for many more years. If you design products for the industrial electronics sector, it more a question of when you will use a 4-to-20-mA interface rather than if you will. I Aubrey Kagan is a Professional Engineer with a BSEE from the Technion-Israel Institute of Technology and an MBA from the University of the Witwatersrand. He works at Emphatec, a Toronto-based design house of industrial control interfaces and switch-mode power supplies. In addition to writing several articles for Circuit Cellar and having ideas published in other periodicals, Aubrey wrote Excel by Example: A Microsoft Excel Cookbook for Electronics Engineers (Newnes, 2004).
DEDICATED TRANSMITTERS Of course, if you don’t want to make your own transmitter, there are quite a few ICs that you can use. A partial list is shown in Table 1. Some of them have very narrow target applications like RTD sensors or bridges and may even include linearization for these sensors. There are some with a built-in DAC for direct microcomputer interfacing. There are even those with both a current and voltage output to allow designing for different outputs so that the same finished product can serve multiple market niches.
The Highway Addressable Remote Transducer (HART) protocol was developed by Rosemount in the 1980s and allows a frequency shift keying (FSK) signal to be injected onto the 4-to-20-mA signal allowing the use of the existing wire to distribute additional information without disturbing the measured value of the current loop. There needs to be some circuitry to mix the FSK and current signals since the FSK may be shorted www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
HART PROTOCOL
33
NEED-TO-KNOW INFO
PROJECT FILES
Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel.
To download the Excel files, go to ftp://ftp.circuitcellar. com/pub/Circuit_Cellar/2010/241.
RESOURCES
Circuit Cellar has published several articles by Aubrey Kagan. The editorial staff recommends the following articles: — Create a Modbus Slave by Aubrey Kagan Circuit Cellar 216, 2008 After creating a Modbus master, Aubrey created a Modbus slave on a Cypress PSoC. Here he describes three different methods of slave creation. Topics: Modbus, Packet, Data Rate, CRC
Analog Devices, “Single Channel, 12-/16-Bit, Serial Input, Current Source and Voltage Output DACs,” AD5412/AD542, 2009. M. Elgan, “Designing Programmable Logic Controller 4-20mA and Voltage I/O Modules: Techniques and Solutions,” Analog Devices Webcast, Wednesday, November 19, 2008. W. Jung and J. Wong, “Op-amp Selection Minimizes Impact of Single-Supply Design,” EDN, 1993.
Go to: www.circuitcellar.com/magazine/216.html — Hierarchical Menus in Embedded Systems by Aubrey Kagan Circuit Cellar 160, 2003 Need to use menu structures in embedded systems? With a hierarchical menu system you can reuse software for displaying and changing parameters to save ROM space and achieve maximum flexibility. Topics: Menu, Structure, User Interface, C
A. Kagan, Excel by Example: A Microsoft Excel Cookbook for Electronics Engineers, Newnes, 2004. National Semiconductor, “1989 Linear Applications Seminar.” A. O’Grady, “Adding HART Capability to the AD421,” AN-534, Analog Devices, 1999. Texas Instruments, “Advanced Linear Products 1991 Design Seminar.”
N
e
w
n
e
Go to: www.circuitcellar.com/magazine/160toc.htm
s
P
r
e
s
s
Education Never Ends. Everything you need to know to get started.
By: Michael Parker ISBN: 9781856179218 $54.95
By: Gina Smith ISBN: 9781856177061 $44.95
By: William Kafig ISBN: 9781856177047 $44.95
By: Robert Lacoste ISBN: 9781856177627 $44.95
August 2010 – Issue 241
Stop by booth 1823 at ESC West to check out these titles and more!
34
Save 20% when you buy at the show. Register for our e-news at newnespress.com www.newnespres s.com
GZXZ^kZ djg WZhi Y^hXdjcih =ZVg VWdji Wdd`h WZ[dgZ i]Zn ejWa^h] 6XXZhh id [gZZ hVbeaZ X]VeiZgh! k^YZd ijidg^Vah VcY bdgZ
CIRCUIT CELLAR®
•
www.circuitcellar.com
22
ADVANCE PROGRAM HOT CHIPS 22 A Symposium on High-Performance Chips August 22-24, 2010, Memorial Auditorium, Stanford University, Palo Alto, California
Sunday
August 22 August 23 August 24
Tuesday
Monday
HOT CHIPS brings together designers and architects of high-performance chips, software, and systems. Presentations focus on up-to-the-minute real developments. This symposium is the primary forum for engineers and researchers to highlight their leading-edge designs. Three full days of tutorials and technical sessions will keep you on top of the industry. Morning Tutorial Non-Volatile Memory
Organizing Committee
Chair Charlie Neuhauser Neuhauser Associates Vice Chair Ralph Wittig Xilinx Forging a Future in Memory Ed Dollar Micron Finance Status and Prospect for MRAM Technology Saied Tehrani Everspin HP Metal Oxide RRAM as a Future Non-Volatile Memory Paul Kirsch Sematech Lily Jow Publicity Solid-State Disks in Enterprise Systems TBD Kevin Krewell NVID IA Storage Class Memory Richard Freitas IBM Member at Large Afternoon Tutorial Optical Interconnects Allen Baum Intel Overview: VCSELs to Silicon Nanophotonics Ashok Krishnamoorthy Oracle Advertising Silicon photonics in the data center Al Davis U. of Utah, HP Labs Don Draper True Circuits Silicon photonics and memories Vladimir Stojanovic MIT Sponsorship Hybrid on-chip data networks Gil Hendry Columbia Amr Zaky Broadcom Multi-chip photonic network Frankie Liu Sun Labs, Oracle Publications Randall Neff High Performance Computing Registration Fermi GF100: A GPU For Compute, Tessellation, and Computational Graphics NVIDIA End of Scaling of Traditional Microprocessors Schlumberger, Stanford Michael Sobelman Rambus Facilities and Video Adaptive Energy Management Features of POWER7 IBM Lance Hammond Apple Keynote 1 Hartmut Neven Google Local Arrangements Searches Originating Inside and Outside of Your Head John Sell Microsoft SoCs Volunteer Coordinator Larry Lewis Apple The New Xbox 360 SoC Microsoft Production Extensions to the ARM v7-A Architecture ARM Solving 4G Challenges with Multi-Core Baseband SoCs Mindspeed M ke Albaugh GreenDroid: A Mobile Application Processor for a Future of Dark Silicon UCSD, MIT Webmaster Alice Erickson Alice Erickson Networking & the Data Center Consulting CTO A Wire-Speed Processor: 16 POWER(r) Cores with 64 Threads per Core IBM Yusuf Abdulghani Apple Smart Memory for High-Performance in Network Packet Forwarding Huawei Emeritus iMB™:Enabling Low-Power Cloud Computing and Server Virtualization Inphi Keith Diefendorff Apple
Panel: Asia: Partner or Competitor? FPGAs 28nm Generation Programmable Families Xilinx Stratix V with 28Gbps Transceivers in 28nm Altera 3D FPGA for Improved Density, Power and Performance Tier Logic Interconnects ICC:An Interconnect Controller for the Tofu Architecture Fujitsu The Hub Module in 45nm CMOS SOI : A Terabyte Interconnect Switch IBM Silicon Photonics: Optical Connectivity at 25 Gbps and Beyond Luxtera Spidergon STNoC: Network-on-Chip Gives Added System Value ST Microelectronics Keynote2 Burkhard Huhnke VW Palo Alto Lab Electronics in Cars Servers Westmere-EX: A 20-Thread Server CPU Intel Architectural Innovations in Westmere-EP Intel GS464V: A High-Performance Low-Power XPU with a 512-Bit Vector Extension
Chinese Academy of Sciences
New Processor Architectures The Next-generation System z Micro-Processor AMD's “Bulldozer” Core – Multi-Threaded Compute Performance for Maximum Efficiency and Throughput
AMD’s “Bobcat” x86 Core – Small, Efficient and Strong Please visit us on the web: or drop us a line via Email:
http://www.hotchips.org
[email protected]
IBM AMD AMD
22
Steering Committee Don Alpert Camelback Arch. Allen Baum Intel Don Draper TCMM Chair Pradeep Dubey Intel Lily Jow HP John Mashey Techviser Howard Sachs Alan Jay Smith UC Berkeley
Program Committee Program Co-Chairs Will Eatherton Juniper Jose Renau UC Santa Cruz Program Committee Krste Asanovic UC Berkeley Bevan Baas UC Davis Forest Baskett NEA Bill Dally Stanford Pradeep Dubey Intel Rick Heatherington Sun Christoforos Kozyrakis Stanford Dan Lenoski Cisco Chuck Moore AMD Alan Jay Smith UC Berkeley Ralph Wittig Xilinx
Founder Bob Stewart SRE
This is a preliminary program; changes may occur. For the most up-to-the-minute details on presentations and schedules, and for registration information, please visit our web site where you can also check out HOT Interconnects (another HOT Symposium being held following HOT CHIPS)
A Symposium of the Technical Committee on Microprocessors and Microcomputers of the IEEE Computer Society and the Solid State Circuits Society
F EATURE
ARTICLE
by Devlin Gualtieri (USA)
Build an X10 Controller (Part 2) The Controller Program and Utility You have a circuit design for your X10 controller. Now it’s time to address the firmware. This is a review of a controller program and a utility to convert a human-readable event file into serial data the X10 controller understands.
I
n the first part of this series, I presented the circuit design for my X10 controller. As with any embedded system project, there’s a firmware component. Since the controller communicates with a PC to update its event table, there’s also some software needed on the PC. I’m a Linux fan, but I realize that many of you use Windows and other operating systems. So, I designed the X10 controller to be OS-agnostic. In fact, all you need are a text editor and a serial communications program—such as HyperTerminal (Windows) or GtkTerm (Linux)—to update the controller events. The event table is a simple text file you can edit and upload to the controller. To make things easier, I wrote a complier that translates a human-readable text file into the hexadecimal text file that the controller needs. This compiler is written in ANSI C, so it compiles and executes under both Linux and Windows. There are other languages that make writing a compiler like this easier, but ANSI C is portable. Executables are provided for Windows users who haven’t purchased a C compiler. Linux people always have free compilers available, which is another reason why many technical people use Linux.
X10 commands. I should note that the codes you supply as arguments for the X10 commands in PICBasic Pro are simplified from those actually transmitted. You can instruct the compiler to use the raw codes, but the compiler codes make more sense (i.e., house code “A” is zero and not six), so I decided to use them. The PICBasic Pro source code and its compiled hex file are available on the web site, and its a simple matter to “burn” the code into the PIC using any one of a number of PIC programmers and the ICSP connector. You have the option of programming the PIC in an external program socket and then plugging it into the controller board. I used a microEngineering Labs USB Programmer and the Serial Programmer (now discontinued) in both ICSP and socket mode, but you can find schematics for less expensive programmers on the Internet.
HOW IT WORKS The event table fills the entire 256 bytes of EEPROM. Each event needs four bytes, so there are 64 possible events. These are more than enough. The controller in my house has just 18 events, some of which (Christmas lights) are not even active most of the year. Figure 1 shows the
August 2010 – Issue 241
PIC FIRMWARE
36
In the previous article, I stated my preference for microEngineering Labs’s PICBasic Pro compiler. It can be used on Microchip Technology PICs ranging from the very low-end eight-pin units through the 40-pin PIC16F877 that I used for this project. This compiler also has commands that makes programming of the X10 controller that much easier. There are commands to read and write to I2C devices (the Maxim Integrated Products DS1307 clock chip), read and write to a serial port, read analog voltages, and output
Byte–1 H10
H1
Hour as two BCD digits
Byte–2 M10
M1
Minute as two BCD digits
Byte–4
Byte–3
DEV
DOW
FN
Device and function codes as two binary nibbles
Days of week binary coded
Figure 1—The data structure of the event table. Each event occupies 4 bytes, allowing 64 events in the 256 bytes of nonvolatile memory in the PIC16F877. CIRCUIT CELLAR®
•
www.circuitcellar.com
Hex code
Command
X10 Command transmitted
XOUT Code PICBasic Pro
0 1 2 3 4 5 6 7 8 9 A B C
A _un ts_off A _ ghs_on A _ ghts_off On Off Br ght_10 (br ghten Br ght_20 (br ghten Br ght_40 (br ghten Br ght_80 (br ghten D m_10 (d m 10%) D m_20 (d m 20%) D m_40 (d m 40%) D m_80 (d m 80%)
10000 11000 10110 10100 11100 11010 11010 11010 11010 10010 10010 10010 10010
11100 10100 10000 10010 11010 10110 10110 (tw ce) 10110 (four t mes) 10110 (e ght t mes) 11110 11110 (tw ce) 11110 (four t mes) 11110 (e ght t mes)
10%) 20%) 40%) 80%)
Table 1—The event commands recognized by the X10 controller.
August 2010 – Issue 241
data structure of the event table. The hour and minute data are packed BCD digits, which make for easy readability. The times are on a twenty four hour clock. You can choose which days of the week you would like your devices to be active. In my case, I like the porch light to be on weekday mornings when I’m fumbling for my keys in the winter darkness, but I don’t need this light to be on for the weekend. The day-of-week (DOW) byte has a bit for each day of the week. If this byte is $7F (01111111), then all days are specified. A byte value of $3E (00111110) specifies just weekdays, and $41 (01000001) specifies just weekends. Whenever a minute rolls over, the event table is scanned to see whether there are any events that should happen at the new time. The table entries are scanned first for a match of minute. If that test is passed, then the hour and day of week are checked. If all match, then the device code and device command are extracted. The
38
Monitor command
Function
S T U E B H ?
Set t me Show t me Up oad event tab e Down oad event tab e Show battery vo tage Show house code L st commands
Table 2—The serial monitor commands programmed into the controller
X10 controller recognizes the commands listed in Table 1. The command codes I used are different from the actual X10 commands, and some commands make more sense than the actual X10 commands. There isn’t just a “Dim” command; rather, there are four Dim commands that allow close control of the final dimming level. There are four complementary “Bright” commands that function the same way. The controller translates these internal codes to the proper X10 commands before transmitting. The Dim and Bright commands aren’t very accurate, since these functions depend on the wattage of the lamp you are controlling. A little experimentation might be required to zero in on the desired brightness level of a particular lamp. Table 1 shows the event commands. Table 2 shows serial commands. The X10 Dim and Bright commands deserve a special mention, since they have a dual affect depending on the rate at which they are transmitted. If transmitted continuously, there are about 128 steps over the control range. The 128-step range is useful when you’re using a manual controller, since it gives a very fine adjustment of a lamp’s final state. If transmitted intermittently, as done by the controller, there are about ten or twelve steps over the full range.
OPERATION Once the PIC is programmed, the X10 controller will respond to commands at its serial port. The serial
format is 2,400 bps, 8 data bits, no parity, and one stop bit. If you’re using Windows, HyperTerminal can be used to communicate with the controller over the serial interface. Linux users can use GtkTerm, as I do, or CuteCom. Once you see the sign-on message as the controller powers-up, the controller will respond to the monitor commands listed in Table 2. The first order of business is to set the time. First, type an “S” then the time in 24 hour format with a colon separating the hours and minutes. You should always pad single digits with zeros; e.g., 08:13 is 8:13 AM. The controller will then prompt you for the day of the week. Sunday is “1” and you can count on your fingers (as I do) to get the proper number for the day. You can verify a correct time entry by typing “T.” Photo 1 shows time setting and verification in HyperTerminal, along with a battery voltage check. Photo 2 shows some menu commands in GtkTerm. The next step is to upload the event data, which is sixty four events of 4 bytes each, as summarized in Figure 1. The event data is a text file of 256 bytes in which each byte is prefixed by a dollar sign (e.g., $FF). Both HyperTerminal and GtkTerm allow transfer of text files. After typing a “U,” you send this
Photo 1—A serial communications session with the X10 controller. Typing “?” gives a display of the menu commands. In this session, the house code is checked, the time is checked and then changed, and the battery voltage is checked. CIRCUIT CELLAR®
•
www.circuitcellar.com
Photo 3—Here’s a partial dump of the controller event table in GtkTerm. Photo 2—Equal time for Linux! Here’s the controller sign-on message and a check of the house code and battery voltage in GtkTerm. text file to the controller, and the controller responds with “Done.” The controller expects to get 256 bytes of data. If it doesn’t, it will hang, so you will need to power-down and restart if this happens. Unused events are filled with “$FF” and capital letters are required in the hex numbers. You can verify the data in the event table by typing an “E.” Photo 3 shows a partial dump of the event table as received in GtkTerm. Once the events are uploaded, the controller is operational. Although its operation can be verified by just observing when your lights go on and off, the controller outputs a serial data stream of X10 events when they happen, as shown in Photo 4. Since there is no handshaking on the serial interface, this output can be ignored, and the serial cable can be disconnected after uploading the event table.
Although the data structure of the event table makes it a simple matter to edit the hex files on a text editor, you still need cheat sheets to remember which of your devices are assigned to what device numbers and the controller command set. To assist in building an event table, I wrote a compiler that translates a human-readable text file to the 256-byte hex file the controller requires. This compiler takes as its input a text file that gives names to your devices, and it uses words such as “On” and “Off” for the commands, rather than their hex codes. This compiler is written in www.circuitcellar.com
•
CIRCUIT CELLAR®
X10 TIPS
Photo 4—Log of X10 events transmitted by the controller. A record of events is sent via the serial interface. This logging stream can be ignored, or it can be captured to a file on a PC.
There are many resources available on the Internet that will help you make your X10 system work reliably. One problem commonly encountered is low signal transmittance from one phase of your household wiring to the other. Most U.S. households are wired
August 2010 – Issue 241
EVENT COMPILER
ANSI C, and its source code and executables for both Linux and Windows can be found on the Circuit Cellar FTP site. I haven’t used Windows in years, but the source code compiled without error on a very old version of Turbo C for Windows that I had. An example input file appears as Figure 2. The keyword “Device” allows you to specify your device names, and “Event” signals an X10 event. The syntax is obvious from the figure, and also from the comments in the compiler source code. Day-of-Week codes for “Every_Day,” “Weekdays,” and “Weekends” can be used. More exotic day combinations, which are rare, must be edited in the hex file. The compiler ignores most extraneous text, such as comments, and it will output some error messages when it’s confused. Figure 3 shows a portion of the compiler output for the event source code in Figure 2. The controller ignores everything that doesnt look like hexadecimal data, so the compiler outputs some informative comments and highlights errors. The controller expects 256 bytes to be uploaded as an event table, so the unused portion of the event table is padded with $FF, which can’t be confused with a valid time.
39
//X10 Event File// Device Device Device Device Device Device Device Device Device Device Device Device Device Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event Event
1 Floodlights 2 Lamp Post 3 Porch Light 4 Kitchen Sink Light 5 MBR 6 Living Room 7 Sun Room 8 Garage Door Light 9 Alarm Switch 10 Outside Xmas Lights 13 Porch Motion 14 Garage Flood 15 Beeper 16:30 16:30 16:30 06:00 16:35 02:30 16:40 23:00 06:00 06:01 06:30 16:45 00:30 16:50 23:05 22:30 23:30 10:30 03:00 16:30 22:30
Every Day Floodlights On Every Day Floodlights Dim 40 Every Day Floodlights Dim 10 Every Day Floodlights Off Every Day Lamp Post On Every Day Lamp Post Off Every Day Porch Light On Every Day Porch Light Off Weekdays Porch Light On Weekdays Porch Light Dim 40 Weekdays Porch Light Off Every Day Kitchen Sink Light On Every Day Kitchen Sink Light Off Every Day Living Room On Every Day Living Room Off Every Day Sun Room On Every Day Sun Room Off Every Day Garage Door Light On Every Day Garage Door Light Off Every Day Outside Xmas Lights On Every Day Outside Xmas Lights Off
August 2010 – Issue 241
Figure 2—The X10 event file for my house. This source file is used by the compiler to create a file suitable for uploading to the X10 controller. The keywords “Device” and “Event” signal the compiler to look for a device definition or an event statement. The compiler syntax is obvious from this example. Note that times are on a 24-hour clock padded with zeros.
40
two-phase—that is, two of the electrical system’s three phases enter your panel box. The electrician tries to equalize the loads on each phase by having about the same number of wall outlets and lights on each. Power-hungry devices (e.g., electric clothes dryers and ovens) are connected to both phases and operate at the higher voltage available that way. Remember that for the same power, higher voltage means lower current, which is always good for the connecting wires. The X10 signaler is connected to one phase only, but we need to produce signals on all phases. The typically long runs of wire to your two-phase appliances help because there’s a lot a capacitive coupling between wires. But there are devices you can buy to bridge the X10 signal between phases. The AC power line is not a benign signal environment, even at 120 kHz. From personal experience, I had a CRT monitor that interfered with the X10 signals whenever it was on. This was likely a harmonic of the horizontal oscillator feeding into the power line. Electrical devices with switching power supplies can put a lot of noise onto the power lines. In most cases, power line filters that plug between your device and the AC outlet will solve the problem. Compact fluorescent lights
could be another noise source, but I haven’t had any personal experience with these. I’ve decided to bypass this generation of energy-saving bulbs and wait for white light LEDs that are sure to hit a proper price point in the near future.
STARTING IN LINUX I’m often surprised at the many technical people who aren't using Linux. First, there’s the price—or, should I say, lack of price. Linux is available free on the Internet. Linux is also a programmer’s paradise because there are free compilers or interpreters available for nearly every language and a wealth of utility programs. These utility programs include Devices: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
floodlights lamp post porch light kitchen sink light mbr living room sun room garage door light alarm switch outside xmas lights porch motion garage flood beeper
0 $16 $30 $7F $03 //floodlights:on:every day 1 $16 $30 $7F $0B //floodlights:dim 40:every day 2 $06 $00 $7F $04 //floodlights:off:every day 3 $16 $35 $7F $13 //lamp post:on:every day 4 $02 $30 $7F $14 //lamp post:off:every day 5 $16 $40 $7F $23 //porch light:on:every day 6 $23 $00 $7F $24 //porch light:off:every day 7 $06 $00 $3E $23 //porch light:on:weekdays 8 $06 $01 $3E $2B //porch light:dim 40:week days 9 $06 $30 $3E $24 //porch light:off:weekdays 10 $16 $45 $7F $33 //kitchen sink light:on:every day 11 $00 $30 $7F $34 //kitchen sink light:off:every day 12 $16 $50 $7F $53 //living room:on:every day 13 $23 $05 $7F $54 //living room:off:every day 14 $22 $30 $7F $63 //sun room:on:every day 15 $23 $30 $7F $64 //sun room:off:every day 16 $10 $30 $7F $73 //garage door light:on:every day 17 $03 $00 $7F $74 //garage door light:off:every day 18 $16 $30 $7F $93 //outside xmas lights:on:every day 19 $22 $30 $7F $94 //outside xmas lights:off:every day 20 $FF $FF $FF $FF 21 $FF $FF $FF $FF
Figure 3—A portion of the compiler output for the event source code in Figure 2. The controller ignores everything that doesn’t look like hexadecimal data, so the compiler outputs some informative comments and highlights errors. The unused portion of the event table is padded with $FF, which can’t be confused with a valid time. CIRCUIT CELLAR®
•
www.circuitcellar.com
Open Office (www.openoffice.org ) and the GtkTerm program mentioned in this article. There are “Linux Live” CDs, also available as images on the Internet, that enable you to boot Linux from a CD without installation on your hard drive. There are images available to change a USB memory stick into a bootable Linux drive. Some of these live Linux distributions have utility programs for specialty areas, such as computer security and forensics, and they are all free. Refer to www.livecdlist.com for a listing. I Devlin Gualtieri received his PhD in Solid-State Science from Syracuse University in 1974, and worked for many years doing research for a major aerospace company. Now retired, he spends his time doing various embedded systems projects. He can be reached at
[email protected].
PROJECT FILES To download the code, go to ftp://ftp.circuitcellar.com/ pub/Circuit_Cellar/2010/241.
SOURCES PIC16F877 Microcontroller Microchip Technology, Inc. | www.microchip.com
Knowledge is power. In the computer applications industry, informed engineers and programmers don’t just survive, they thrive and excel. For more need-to-know information about topics covered in Devlin Gualtieri’s Issue 241 article, the Circuit Cellar editorial staff recommends the following content: — Electronic Scarecrow by Richard Wotiz Circuit Cellar 186, 2006 This system includes four remote stations designed around MC13192 SARD boards. When movement is detected, it generates loud sounds and runs water sprinklers. Topics: X10, RF, Wireless, Accelerometer Go to: www.circuitcellar.com/magazine/186toc.htm — Bring the Noise! The Analog Side of X10 by Ed Nisley Circuit Cellar 127, 2001 Ever experienced problems with an X10 system? Ed describes the analog side of X10. Topics: X10, RF, BandPass Filter, Signals, Analog, Noise Go to: www.circuitcellar.com/archives/backissuescd.html
August 2010 – Issue 241
PL513 X10 Module X-10 (USA), Inc. | www.x10.com
NEED-TO-KNOW INFO
www.circuitcellar.com
•
CIRCUIT CELLAR®
41
A
BOVE THE GROUND PLANE
by Ed Nisley (USA)
Crystal Properties Circuit Models, Measurement, and Conversion Understanding a crystal’s properties is key to getting oscillators working. Here you learn about a crystal’s circuit model, how to measure a crystal’s properties, and how to convert the values into parameters for the model.
T
August 2010 – Issue 241
he WWVB simulator I described in my February 2010 column “Totally Featureless Clock (Part 1): WWVB Simulator” generated a 60-kHz carrier from the output of a 12MHz crystal oscillator (Circuit Cellar 235). I picked a crystal from my assortment, but, lacking a way to measure its properties, the resulting oscillator was barely adequate to the task. In this column I’ll describe a crystal’s circuit model, how to measure the electrical properties of a crystal, and how to convert those values into parameters for the model.
42
Photo 1—A translucent quartz slab coated with silver or aluminum electrodes hides in each crystal case. Opening the sealed metal container contaminates the quartz: these crystals will never oscillate properly again.
Both you and I will have a better chance to get our next oscillators working properly!
MECHANICAL & ELECTRICAL MODELING The crystal elements shown in Photo 1 share a common structure: a thin slab of quartz with an electrode on each side. Even a cursory glance at the information found in the references demonstrates the complexity behind the seemingly simple mechanics: low-priced crystals come from a mature mass-production supply chain. The crystal in the upper-left of the photo vibrates its rectangular quartz bar in torsion mode, in contrast to the disks of the other units that vibrate in thickness mode. Both designs have an obvious capacitor formed by the electrodes plated on the quartz: two conductors separated by an insulator. That capacitor appears as Co, known as the holder capacitance, in the crystal model shown in Figure 1. Unlike most capacitors, Co is a very high-quality unit: planar electrodes on a quartz dielectric sealed in a lowpressure inert atmosphere. The electrodes and lead wires also exhibit stray capacitance to the metallic case, represented by Cc1 and Cc2 in Figure 1. Although those two capacitors need not be exactly equal, that’s the usual assumption based on the mechanical symmetry. When the crystal case is electrically floating, the two capacitors are in series with each other and in parallel with Co, which accounts for the usual practice of grounding the case. The remaining circuit elements arise from the CIRCUIT CELLAR®
•
www.circuitcellar.com
piezoelectric properties of quartz: • A voltage across the electrodes distorts the crystal structure • A crystal distortion produces a voltage across the electrodes Although a DC voltage produces a fixed distortion, an AC signal is more interesting, because the electrical frequency interacts with the crystal’s mechanical resonances. The motional inductance and capacitance—Lm and Cm, respectively—model the mechanical properties of the crystal, while the series resistance Rs models its energy dissipation. Although manufacturers can predict those parameters from a crystal’s mechanical properties, ordinary users such as you and I must measure the electrical characteristics of asreceived crystals and work backwards to produce the circuit models. Because Lm and Cm depend on mechanical properties, they do not correspond to any obvious electrical components in Photo 1. For example, Lm may be on the order of 1 H and Cm on the order of 1 fF: values exceedingly difficult to implement with ordinary electrical components. The series resistance is generally on the order of a few tens of
Figure 1—A quartz crystal is essentially a series-resonant Lm-Cm circuit with several parasitic capacitances. The motional inductance Lm also forms a parallel-resonant tank circuit with the inter-electrode stray capacitance Co. The electrodes and leads have stray capacitances Cc1 and Cc2 to the case.
ohms, not the hundreds of megohms you can measure with a DC ohmmeter. With Lm, Cm, and Rs in series, a quartz crystal forms a self-contained series-resonant circuit with a Q around 105 or 106. Even better, the resonant
frequency and Q depend on very stable mechanical properties, so oscillators built around quartz crystals exhibit much better stability than those built from ordinary inductors and capacitors. The spectrum analyzer trace in Figure 2 shows the response of a 10MHz crystal measured in the fixture I’ll describe later. The sharp peak at the center of the screen occurs at the
9.9985-MHz series-resonant crystal frequency determined by Lm and Cm. The crystal displays capacitive reactance at lower frequencies and looks like an inductor at higher frequencies, so Lm also forms a parallel-resonant tank circuit with Co. The sharp dip marks the parallel resonant frequency, only 12 kHz above the series peak, above which the crystal looks like a capacitor again. Because the model’s stray capacitances Co, Cc1, and Cc2 all correspond to actual physical parts of the crystal, you can measure them directly with a capacitance meter. However, you must derive Lm, Cm, and Rs from the crystal’s frequency response using some familiar equations. At series resonance the inductive and capacitive reactances will be equal: X
m
XCm
fS
2πfS Lm
2πf S Cm
2π LmCm
The –3 dB width of that peak determines the Q: Q
fS BW
X R
The resistance R is the sum of the crystal’s Rs and the circuit resistances at each crystal terminal. Now, to the workbench!
Figure 2—A crystal’s frequency response includes both a series-resonant peak and a parallelresonant dip, separated by a very small fraction of the crystal’s nominal frequency. The measurement used the test fixture shown in Photo 3. www.circuitcellar.com
•
CIRCUIT CELLAR®
The values of Co and the two Cc capacitors are on the order of a few picofarads, which means you can’t simply clip-lead a crystal to an ordinary capacitance meter and get trustworthy results. I made the fixture shown in Photo 2 to measure the stray capacitances of HC-49/U, HC-49/US, and UM-1 cases. A similar design will accommodate larger HC-51 cases. I used an Almost All Digital Electronics L/C Meter IIB for these measurements, as it seems to be the lowprice instrument of choice for measuring inductors and capacitors in RF applications. In addition to 1% accuracy and fourdigit resolution, it can compensate for fixture capacitance and inductance. The
August 2010 – Issue 241
MEASURE STRAY CAPACITANCE
43
August 2010 – Issue 241
Photo 2—Capacitance depends on electric fields in space and therefore requires a rigid fixture for hands-off measurement. The modified alligator clip holds the case while measuring lead-to-case capacitance and the terminal strip along the rear edge accepts the crystal leads to measure lead-tolead capacitance. The meter nulls the few picofarads of stray capacitance due to the fixture and its own internal wiring.
44
display in Photo 1 shows 6.57 pF of stray capacitance due to the meter’s internal circuitry and the external test fixture; a push of the Zero button stores that value and subtracts it from future readings. The fixture mounted on the meter’s binding posts is a simple rectangle of double-sided PCB material with a narrow slit between the terminals. I bonded the upper and lower foil layers together with copper tape soldered at the rear edges. A strip of dark-amber Kapton tape around the perimeter prevents finger gashes on upturned foil corners. A modified alligator clip clamps the crystal case to a 25-mil brass sheet soldered to the PCB. The flange around HC49 cases is about 20 mils wide, so the case rests flat against the brass sheet with the flange above the air gap. The phosphor-bronze flap near the black terminal post holds the crystal leads firmly against the PCB foil. With both leads shorted together the meter measures the parallel combination of the Cc capacitors between the leads and the case: Read ng
Cc + Cc2
2 × Cc
For all of the forty HC-49/U and HC49/US crystals I measured, this reading was very close to 1.4 pF, so each Cc
capacitor worked out to 0.7 pF. The actual value for the 10-MHz crystal I’m using as a running example was 1.22 pF, so Cc1 = Cc2 = 0.6 pF. The next measurement uses the socket strip along the rear edge of the PCB to connect the crystal leads to the meter terminals. With the crystal case floating, the meter measures Co in parallel with the two Cc capacitors in series: Read ng
Co +
Cc 2
This value depends on the specific crystal: 2.7, 3.9, 4.5, and 4.9 pF for
four lots of 10 crystals each. Subtracting 0.3 or 0.4 pF gives the corresponding Co value for the crystals, although I think you’d get sufficiently accurate results by simply truncating the reading to the next lower multiple of 0.5 pF. Indeed, the measured values are so small that any change near the meter affects the zero compensation and displayed value. I had to brace the meter case with one insulated screwdriver and poke the Zero button with another to reduce the effect of my hands on the reading. Measuring a batch of 10 capacitors often showed a progressive increase in the reading, as the zero point drifted by perhaps 0.5 pF over the course of a few minutes. Simply putting my hands in different positions on the workbench also affected the reading. As a result, the effective resolution is probably on the order of 0.2 pF and the overall accuracy won’t be much better than ±25%. Keep those values in mind as we get further into the calculations. I measured 2.69 pF for the 10 MHz example crystal, so its Co is: Co
2 69 −
06 2
2 4 pF
Measuring the capacitance turns out to be the easy part. Now, things get tricky!
MOTIONAL MEASUREMENTS I adapted K8IQY’s test fixture design (see Sources) for use with my HewlettPackard HP8591 spectrum analyzer
Photo 3—A spectrum analyzer drives this test fixture to measure the frequency response of an HC49/US crystal. The slide switch between the socket strip and trimpot simplifies measuring the crystal’s series resistance. CIRCUIT CELLAR®
•
www.circuitcellar.com
A new era, a new New tracks. New courses. New focus.
ESC
Entering into its 21st year in Boston, ESC brings together systems architects, design engineers, suppliers, analysts, and media from across the globe. With cutting edge product demonstrations, visionary keynotes, and hundreds of essential training classes, ESC is the ideal conference for the embedded design community to learn, collaborate, and recognize excellence. ESC Boston 2010 Tracks Include: • Aerospace and Military • Designing with Open Source Software, including Linux and Android • Developing for Windows Embedded • Graphics, Display and Lighting • Industrial, Automation, and Robotics • Medical • Multicore and Virtualization • Multimedia and Signal Processing • Networking, Connectivity, and Embedded Internet • Programmable Logic • Project Management • Real Time System Development • Safety and Security • Software Debugging Techniques • Systems Integration and Test Start your own personal development at ESC 2010. You can’t afford to miss it. Expo Floor Access is FREE!
Boston, MA Hynes Convention Center Conference: September 20-23, 2010 Expo: September 21-22, 2010 Register Today. www.embedded.com/boston
2108004_nisley_Layout 1 7/7/2010 10:06 AM Page 46
Vinculum VNC2 SPEED. FLEXIBILITY. PERFORMANCE. A programmable system-on-chip USB 2.0 Host / Slave controller - Dual channel USB 2.0 interface, handles all USB host and data transfer functions in single IC. - On-chip 16-bit Harvard architecture MCU core with 256 Kbyte Flash and 16kbyte RAM. - External UART, FIFO, SPI Slave, SPI Master, GPIO and PWM interfaces. - Vinculum-II software development tools available for user application development. - Multiple package size options including VNC1L backwards compatible package option. - Targeted for range of USB applications, from portable media devices and cell phones to industrial and automotive applications.
Vinculum-II evaluation modules - V2DIP1/2 - Miniature VNC2 Development Module with Single or Dual USB Connectors - V2-EVAL - Complete Evaluation & Development Kit for VNC2 - VNC2 Debug Module
Figure 3—The test fixture isolates the spectrum analyzer and tracking generator from the crystal’s impedance variations, while transforming their 50-Ω impedance down to 12.5 Ω. Adjusting the trimpot to produce the same output as the crystal’s peak response sets it equal to the crystal’s series resistance. and tracking generator, as shown in Photo 3, although you can get similar results using his precision oscillator and RF detector circuitry. Manhattanstyle construction atop a blank PCB works surprisingly well for RF projects, even if it looks somewhat fragile, so this isn’t really a kludge. The test fixture has a reasonably flat response from 100 kHz to a –3-dB rolloff at 300 MHz and shows a fraction of a dB variation between 1 and 50 MHz, which covers all the RF crystals in my collection. The fixture schematic in Figure 3 closely matches the physical layout in Photo 3. The 3-dB Tee attenuators
provide some input and output isolation from the crystal’s wide impedance variations. The DPDT slide switch substitutes the trimpot for the crystal to measure series resistance. The two transformers perform a 4:1 impedance transformation that matches the 50-Ω attenuators to the crystal series impedance. Following K8IQY’s recommendations, I wound FT37-43 ferrite toroids with twisted 28-AWG magnet wire; any similar wire gauge will work fine. The equations shown above indicate that you must measure three quantities at the series-resonant peak: the peak’s frequency (fS), the bandwidth at
August 2010 – Issue 241
USB MADE EASY
46
www.ftdichip.com
Figure 4—A very narrow frequency span around the series-resonant peak gives barely enough resolution for the bandwidth measurement. The HP8591 finds the –3 dB points automatically. CIRCUIT CELLAR®
•
www.circuitcellar.com
Figure 5—The circuit model shows a series peak at 9.995 MHz and a parallel dip at 10.011 MHz, slightly different than the actual crystal shown in Figure 2.
www.circuitcellar.com
•
CIRCUIT CELLAR®
This produces the correct result because, at the resonant peak, the inductive and capacitive reactances due to Lm and Cm are exactly equal and cancel each other. At fs the crystal acts as a pure resistance, with the value equal to Rs. As long as the trimpot is also a pure resistance (which I verified by a simple frequency sweep), its DC resistance is the same as Rs at fs. I measured Rs = 16.5 Ω for this crystal, but others in the same lot varied from 14.2 to 23.4 Ω. The ohmmeter I used reads within 0.1 Ω of the value of several 0.1% precision resistors near 10 Ω, which is also the repeatability of my trimpot adjustments. I expect the actual Rs should fall within ±0.2 Ω of the true value. Measuring fs and BW requires a
! New
$99
OSD-232+ RS-232/TTL controlled on-screen composite video character and graphic overlay in a small 28 pin dip package
Intuitive Circuits www.icircuits.com (248) 588-4400
very close look at the resonant peak to get readings with sufficient resolution. Figure 4 shows the spectrum analyzer display after several rounds of span reduction and tracking generator alignment. Each horizontal division represents 200 Hz, just 0.002% of the 10-MHz center frequency. The frequency at the peak is 9.997850 MHz, although I don’t trust that last digit. Regardless of the instruments you use, be certain you understand the difference between resolution, accuracy, precision, and the digits that appear on the front panel!
August 2010 – Issue 241
the –3 dB points (BW), and the series resistance (Rs). The overall procedure is straightforward, although getting reliable numbers requires some care. The crystal’s rated frequency, which should be printed on the case, will be close to fS. A broadband sweep may not show the peak, however, because the crystal resonance is much sharper than the spectrum analyzer’s filter response: a tall spike may display as a short bump or completely vanish. After you get the peak displayed near the center of the analyzer’s screen, a span of about 100 kHz should produce a display similar to Figure 2. Zoom the span in on the peak to get a closer view, then set the spectrum analzyer’s marker to the peak amplitude. I use the HP8591’s Marker Delta function to remember the peak and track the current scan with a second marker. To measure Rs, set the DPDT switch to substitute the trimpot for the crystal and adjust the trimpot so the trace returns to the peak value of the crystal’s series resonance. Flip the switch to put the crystal back in the circuit and measure the trimpot’s resistance with an ohmmeter: that value will equal the crystal’s Rs at resonance. I brought the trimpot terminals out to two pads near the front of the circuit board to simplify that measurement.
47
The HP8591’s automatic bandwidth measurement function identifies the peak and reports the frequency difference between the points 3 dB below that level, as shown by the magenta markers and readouts in Figure 4. The bandwidth measurement resolution depends on the span setting, so the 210 Hz bandwidth actually has a resolution of about 10 Hz. Now we have enough information to create the crystal’s circuit model.
M
Lm Lm Lm
X Cm Cm Cm Cm
9 997850 MHz 2 0 Hz
47600
Q
X R
X
QR
However, the value of R includes both Rs and the resistance of the external circuit. For the test circuit in Figure 3, the transformers present 12.5 Ω to each side of the crystal: R R
Rs + 2 × 2 5 4 5Ω
6 5 + 25
That equation shows why the test circuit includes those transformers: the effect of a 50-Ω circuit on each side of the crystal would swamp the effect of Rs. Although 12.5 Ω isn’t an exact match to the crystal Rs, it’s fairly close and acts as a reasonable termination value. The reactance of both Lm and Cm at the series-resonant peak is therefore: X
47600 × 4 5 Ω
98 MΩ
2πfS Lm X M 2π f S 98 MΩ 2π × 9 998 MHz 3 5 mH
and
Calculating the values of Co and the two Cc capacitors used only simple arithmetic and Rs was a direct measurement. Deriving Lm and Cm requires a bit more math, but you’ve already seen the equations. The center frequency and bandwidth determine the circuit’s Q:
The value of Q also determines the ratio of the circuit’s reactance to its resistance. Knowing both Q and R, we can find the reactance:
August 2010 – Issue 241
X
MEASUREMENTS TO MODELS
Q
48
the motional components:
2πfSCm 2πfS X Cm 2π × 9 998 MHz × 8 05 f F
98 MΩ
Typical values for the motional capacitance Cm are measured in femtofarads: 10–15 F. The computed Cm is three orders of magnitude smaller than the capacitors you may have used in a microcontroller’s crystal oscillator, so be careful with the units! Feeding those values into the model in Figure 1, adding a sine-wave source and 12.5-Ω terminations produces the simulation results shown in Figure 5. The series-resonant peak at 9.995 MHz is slightly lower than the actual crystal and the parallel peak at 10.011 MHz is slightly higher. Some experimentation will show that the series peak and parallel dip are exquisitely sensitive to the values of Lm and Cm, which should come as no surprise. Because the measured bandwidth directly affects Q and X, efforts spent to improve that value’s resolution will greatly improve the model’s accuracy. However, the circuit model closely matches the actual crystal behavior. Unless you have the luxury of measuring the actual crystals you’ll solder on a specific circuit board, the differences between crystals in a production lot may swamp your measurement accuracy, particularly after taking temperature and other component variations into account. With an accurate model in hand, you can now explore how the crystal interacts with the oscillator circuitry surrounding it. That, alas, is a story for another time.
CONTACT RELEASE Knowing the reactance, we can find
The K8IQY measurement setup offers CIRCUIT CELLAR®
•
www.circuitcellar.com
Introducing Pololu’s new
Ed Nisley is an EE and author in Poughkeepsie, NY. Contact him at
[email protected] with “Circuit Cellar” in the subject to avoid spam filters.
PROJECT FILES To download the schematics and simulation files, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2010/241.
RESOURCES C. Adams (K7QO), “K7QO’s QRP Laboratory Notebook,” 2.31, 2010, www.k7qo.net/lab.pdf. N. Kennedy (WA5BDU), “Crystal characterization and Crystal Filter Design: An Overview of Tools and Techniques,” 2008, http://pages. suddenlink.net/wa5bdu/ crystal_slide_show.pdf. K7QO QRP Construction techniques, Clifton Laboratories, www.cliftonlaboratories.com/Prototyping.htm. J. R. Vig, “Quartz Crystal Resonators and Oscillators: For Frequency Control and Timing Applications,” AD-A328861, 2000, www.am1.us/Papers/U11625%20VIG-TUTORIAL.PDF.
SOURCES L/C Meter IIB AADE | www.aade.com/lcmeter.htm Crystal measurement oscillator and test fixture Jim Kortge, K8IQY | www.k8iqy.com/testequipment/pvxo/pvxopage.htm Preparation T ferrite and iron-powder toroid assortment QRPme | http://qrpme.com/
NEED-TO-KNOW INFO For more need-to-know information about topics covered in Ed Nisley’s Issue 241 article, the Circuit Cellar editorial staff highly recommends the following content: — Totally Featureless Clock (Part 1) WWVB Simulator by Ed Nisley Circuit Cellar 235, 2010 Ed built a WWVB simulator. That’s mostly a simple matter of software. But there’s also the analog chain: a crystal oscillator, a steep filter, and more. Topics: Clock, WWVB, Simulation, PWM, Filter, Modulation Go to: www.circuitcellar.com/magazine/235.html — Let’s Be Crystal Clear by Robert Lacoste Circuit Cellar 215, 2008 Many electronic devices are enhanced by crystals. Robert explains why there are usually small capacitors around a crystal and more. Topics: Crystals, Cut, Series, Parallel, Piezoelectricity, Capacitors, Oscillator Go to: www.circuitcellar.com/magazine/215.html
www.circuitcellar.com
•
CIRCUIT CELLAR®
Maestro USB Servo Controllers
Conduct a symphony of servos. #1350 Micro Maestro 6-Channel $19.95 #1352 Mini Maestro 12-Channel $29.95 #1354 Mini Maestro 18-Channel $39.95 #1356 Mini Maestro 24-Channel $49 95
Pololu's 6-channel Micro Maestro and new 12-, 18-, and 24-channel Mini Maestros take serial servo controllers to the next level by incorporating native USB control for easy connection to a PC and programmability via a simple scripting language for self-contained, host controller-free applications. Whether you want the best servo controller available or a versatile, general-purpose I/O control board, these compact devices will deliver. Three control methods: USB, TTL serial, and internal scripting Free configuration and control application with motion sequencer Channels can be used for digital I/O or up to 12 analog inputs Individual servo speed and acceleration control for each channel Up to 8 KB of internal scripting memory (~3000 servo positions) 0.25 us servo pulse resolution with pulse rate up to 333 Hz
more information at www.pololu.com/maestro
August 2010 – Issue 241
some advantages over a spectrum analyzer, albeit without the luxury of nice screenshots. It should provide better resolution and short-term stability than my HP8591 if you pay attention to the construction details. You can download schematics and simulation files for this month’s column from the Circuit Cellar FTP site. I
49
T
HE DARKER SIDE
by Robert Lacoste (France)
A Tour of the Lab (Part 1) Time Domain Measurement Equipment Building a design lab is an exhilarating experience. It’s exciting to shop for parts, set up new equipment, and begin planning new projects. But it also can be a stressful endeavor, especially when you’re working on a tight budget. Here are some tips for choosing the right test equipment given your design needs and resources.
August 2010 – Issue 241
A
50
s most regular Circuit Cellar readers know, I love test instruments. Back when electronics was just my hobby, I designed and built numerous pieces of test equipment such as the DDSGEN high-frequency generator (Circuit Cellar 129–130, 2001), a tracking lab power supply (Circuit Cellar 139, 2002), and the VectorSoc network analyzer (Circuit Cellar 149, 2002). Today I’m lucky enough to run my own consulting company, which means I can do what love during work hours—and I get paid to do so. A drawback, however, is that I don’t have the time to design much test equipment other than a work-related design every so often. Fortunately, I have the means to purchase what I need for my lab (see Photo 1). Any worker, no matter the field, needs certain tools to get a job done efficiently. Clearly, a plumber shouldn’t try to find a leak with a telescope. This is also true in the field of electronics. A good piece of test equipment is invaluable. When you run into a daunting design-related problem, the right tool can really help you work out a solution. With this in mind, I want to discuss test equipment and describe my lab. There’s a lot to be said about choosing test equipment and building an efficient design lab. Thus, I’ll Photo 1—This is Alciom’s lab. It took me years to obtain all cover the topics in two articles. In this of this equipment, 90% of which I got from brokers and article, I’ll focus on other second-hand resellers.
time-domain measurement, which involves classic testing tools such as oscilloscopes, counters, and logic analyzers. I will, of course, also talk about some more exotic stuff. In my next column, I’ll present tools dedicated to the RF field—that is, tools used for working in the frequency domain. Please stay tuned. At the end of this series, I hope you’ll be able to answer a few important questions. What devices do you definitely need in your lab? What should you look for before purchasing lab equipment? How can you use your test equipment efficiently? Can you use your equipment for any unusual applications?
TOOL TIPS Before I begin, I want to make a few thing clear. My goal is not to recommend a specific brand or company. Most major suppliers (such as companies like Agilent and Tektronix) have similar products. It’s up to you to choose between Company A’s parts and Company B’s. My goal is to help you determine the proper tools for your specific needs and how to use them at best. Test equipment can be really expensive, so I assume most of you will buy used parts and tools, which usually means you’ll get them from brokers or via online auction sites. I’ve had good experiences with both (I was robbed only a few times), but you have to know that any repair service will cost you far more than what you will pay for the product. This means you must either cross your fingers and take a risk (which could be fine for cheap devices) or focus on the devices with the best reviews. A last word. Keep in mind that a 20-year-old system is usually far easier to repair that a CIRCUIT CELLAR®
•
www.circuitcellar.com
except for the very highest power ratings. Talking about power supplies, another useful POWER SUPPLIES & GENERATORS test device is an electronic load, either off the shelf or The first device you need, maybe apart homemade. Every power from the ubiquitous multimeter, is a supply should be tested. power supply. I have a recommendation: An electronic load will focus on simplicity and reliability. As allow you to draw a varione of my colleagues says, “When someable current on the power thing goes wrong, it’s the power supply nets and then easily test or the wiring.” And he is often right. the power supplies of a Your power supply must be rock-solid project up to their specifiand as clean as possible. Other features cations. It’s invaluable. are secondary, even if digital displays are One very useful feature is pleasant. Photo 2—A dynamic electronic load enables you to rigorously test to be able to quickly You will need a couple of power supa power supply. Here the load current is switched between 10 mA switch the load between plies to power up multiple-voltage sysand 1 A every 10 ms. The 1.5-V voltage drops clearly show that two preset values (or even tems. Try to vary their characteristics so some capacitors are not sized properly. to program complex load you can be as flexible as possible. Get a sure to buy a good soundcard, ideally an profiles). This enables you to measure low-power, high-current unit or two, a external one to limit PC noise. the intrinsic quality of the regulation higher-voltage model, and so forth. The The last generator that is nearly before discovering it when it is too late more the better. Buy at least one power mandatory if you are working on line(see Photo 2). supply with a settable current limit in You will also need some signal genera- powered equipment is an AC generator, order to power-up your latest project which enables you to vary the line volttors. Start with a low-frequency generawith minimal current first. This will age and frequency and even inject drops tor, particularly one with modulation drastically reduce the risks if anything or transients. Very useful, but unfortuinputs (AM, FM, etc.) if possible. Wobugoes wrong. nately very expensive, even if I am lation (meaning the capability to sweep One powerful power supply (say 20 A happy to have invested in a California between two frequencies) is also a plus or more) is also a good investment. To Instruments 751i unit. A poor man’s because it enables you to easily measure find shorted traces on a PCBs, as a last alternative would be a high-sensitivity the frequency response of any circuit on resort, limit the voltage to 1V or so and differential breaker followed by a variac an oscilloscope. Audio specialists will inject 20 A between the two tracks in focus on low-distortion equipment. Digi- and a good isolation transformer. short circuit. The smoke will indicate tal-oriented designers will prefer models the location of the highest resistance, which is usually the copper bridge. In my with a crystal-based phase-locked loop OSCILLOSCOPES for stable frequencies. A pulse generator lab, I have 10 power supplies, ranging With all these generators, your projfrom a couple of Agilent low-power units is also a good companion, especially if it ect will be powered and fed, and you is fast (less than 10 ns), flexible, and easy will need to check to see if it is workup to a 110-A, 10-V Lambda unit. Try to to use when setting low and high output avoid switch-mode power supplies ing as planned. When your multimeter voltage levels. I’m pleased is not enough, you must switch on your with a couple of 20-year-old oscilloscope—an electronic engineer’s Philips/Fluke generators. best friend. I will not insult you by To generate more complex describing an oscilloscope. I will, howwaveforms, you need an arbiever, show you some of its benefits and trary generator, which basicalapplications. ly includes RAM, a clock (or Basically, you can use an oscilloscope DDS), and a DAC. Good units to quickly check a waveform, to meascost a fortune, and cheap ones ure it, or to find an elusive problem. I can be quite limited, noisy, may be old-fashioned, but I confess I still and difficult to program. Forprefer a plain-old analog scope for checktunately, there is a nice altering waveforms, especially for quickly native, at least if you need changing signals like TV, audio, or ultraonly tens of kilohertz of bandsonics (see Photo 3). Analog scopes have width: your PC! Scilab, or other advantages. For instance, they’re even Excel, will allow you to significantly cheaper than digital scopes Photo 3—An analog scope (a Tektronix 2467A in this when you’re looking at high bandwidths instance) is useful when you want to take a quick look at rap- program your waveform and idly changing analog waveforms like this ultrasonic ringing. send it to a soundcard. Just be (greater than 250 MHz). Plus, they are www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
newfangled system full of ASICs and embedded PCs. Now let’s go for the tour.
51
August 2010 – Issue 241
Photo 4—The dual timebase feature of a good analog oscilloscope enables you to quickly estimate timing jitters. Here the scope is triggered on the rising edge of the signal, and the next edge is magnified in the bottom trace thanks to the second timebase. The jitter is clearly visible and measurable.
52
Photo 5—A digital oscilloscope is invaluable when you’re looking for a rare event. Here a Lecroy Waverunner 6050 is configured for a “drop-out trigger,” which means it triggers when a preset threshold is not crossed. Try to trigger on such an event with an analog scope or even with an entry-level digital scope.
nearly immediately operable when you press the Power button. (Have you ever waited for Windows to boot on a scope? Very boring.) An analog scope can also be invaluable when you need a quick estimation of timing jitter on signals, especially if you have a dual-timebase scope like my trusty Tektronix 2467A (see Photo 4). When it comes to bandwidth, don’t underestimate your needs. A 200-MHz scope is required to measure a 200-MHz signal, but with 3 dB of attenuation in the measured value, which is already a 30% voltage error. To reduce this error to a few percentage points, you need at least a 400-MHz scope for the same 200-MHz input signal. Similarly, you need at least a 400-MHz scope to see a rise time in the nanosecond range, which may be needed for high-speed digital designs, even if the frequencies stay quite low. There is a good application note from Agilent on that topic (see the References at the end of this article).
Even if you can use an analog scope to perform measurements, there is a point where a decent digital scope will be far easier to use. Just press a button and you will get voltage or timing measurements and even statistics. All digital scopes do that, so which one should you select after having checked the bandwidth and number of input channels (four is definitively a plus)? Some may argue that the next criterion is memory size. Of course, a large memory helps, but in my opinion it is useless to get megabytes of garbage and then spend hours trying to find what you are looking for. For me, a good digital scope must have a very flexible trigger system, with zillions of triggering modes. You may need to spend some time reading the manual and configuring the trigger to capture what you are looking for, but then you’ll get it in the middle of the screen. Photo 5 shows what I have in mind. Personally, this is why I like Lecroy’s scopes (now a Waverunner 6050), even if
Photo 6—A digital scope is handy when you need to visualize or superpose rare events. Here is an example showing the random time delay added by an ISM radio transmitter when the RF channel is free before sending a new data burst.
Photo 7—A sampling scope (an HP 83480A digital signal analyzer in this instance) reconstructs a periodic waveform through successive trigger events. Look at the waveform made of random dots. Such a scope has a timebase that can expand to 10 ps per division. It’s mainly used for applications such as high-speed digital signals and eye diagrams. CIRCUIT CELLAR®
•
www.circuitcellar.com
mode and can support hundreds of input channels on the most advanced models (see Photo 8). Of course, plenty of software features enable you to configure the inputs (polarity, threshold voltage, etc.), group them logically into buses, give them nicknames, and so on. The triggering section of a decent logic analyzer also must be very powerful, allowing multistaged triggers to capture the most difficult-to-catch event. Even old Tektronix 1240 analyzers provided very impressive triggering features. However, any real logic analyzer also supports another mode called “State Analysis.” In this mode, the clock is no longer free-running. It is one of the signals coming from the system under test. Photo 8—This is a Tektronix TLA704 logic analyzThe classic application is a microproceser with 102 probes. Never buy a logic analyzer sor with external data and an address without its probes. It’s useless without them. bus. When configured in State Analysis mode, a logic analyzer grabs the address and data for each CPU instruction and high-end competitors come close. enables you to disassemble the succesAnother advantage of a digital scope sive instructions and data bytes or even is, of course, its persistent display, get performance measurements (actual which allows you to either visualize sintime spent in each routine, etc.). gle-shot events or accumulate succesLOGIC ANALYZERS sive events like in Photo 6. Yes, I know, A logic analyzer is basically a digital Unfortunately, microcontrollers with there are fancy analog scopes with memoscilloscope without an ADC. Its an external data bus are scarce these ory that can do the same, but no one inputs are only digital signals. At each days, and microprocessors are now too can honestly say they are as easy to use clock front, the inputs are sampled and fast to allow the connection of a logic as a digital scope. stored in memory for later analysis analyzer. (The extra load will perturb Speaking of digital scopes, you may (recent units also allow you to store the transmission except with very spealso come across so-called sampling only change events along with high-res- cific and expensive differential probes.) oscilloscopes (or the equivalent “interolution timestamps to allow full waveMoreover, in-circuit debugging techleaved sampling” feature of some generform reconstruction while saving niques like JTAG are also reducing the al-purpose scopes). The idea is to measmemory). A logic analyzer working like need for external logic analyzers. That’s ure repetitive signals by digitizing only a that is in so-called “timing analysis” why there is plenty of cheap equipment. couple of points or even a sinDoes that mean you don’t gle point at each trigger event. need to try to get one on your The waveform is progressively desk? You bet not, especially if reconstructed, as long as it is you find a nice affordable unit, exactly repetitive, or if you purlike the Tektronix TLA704/7L3 posely want to superpose sucthat I got some years ago for less cessive waveforms (eye diathan $800! Just be sure to get the grams, for example). Basically, a complete set of probes with the sampling scope is always more unit. The analyzer will be usedifficult to use than a real-time less without them. digital scope, so you should What could you do with a only use them when there logic analyzer? You can use it to isn’t any other solution (like debug your latest microconwhen you need blazing speed). troller-based design, even if you Photo 7 shows a 20-GHz don’t have a formal external bus. Hewlett-Packard 83480A unit, Just write debug information to which on an Internet auction a couple of GPIO pins (that site costs hundreds less than a could be shared with other funcPhoto 9—You can use a logic analyzer for applications other than 20-GHz real-time digital scope. tions) and grab them with your monitoring a data/address bus. Here it is hooked on the MOSFET A last word on scopes: don’t driver signals of a three-phase brushless motor. logic analyzer. You can use the www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
forget the probes. It would be crazy to get a good scope only to connect it to a poor probe that will ruin its performance. A switchable 1:1/1:10 probe is usually far worse than a good 1:10 probe because its capacitance in the 1:1 position is huge. Buy good-quality 1:10 probes. If you need to get the most of your scope—in particular, to measure fast signals—then you need to switch the input impedance of the scope to 50 Ω to avoid reflections and impedance mismatches. This means you must either avoid probes (with a direct 50-Ω connection) or get an FET-based high-impedance probe—a must-buy if you can afford it. By the way, you can usually adapt an FET probe from supplier X to a scope Y as long as you built the proper power supply with the information found on the Internet. That’s how I have an Agilent 1156A probe connected on my Lecroy. Just ask me for the schematic of the adapter if you need it.
53
suppliers do propose these as firmware options, but it may be cheaper to buy dedicated PC-based devices like the Beagle series produced by Total Phase. This is at least the solution I’m using.
August 2010 – Issue 241
COUNTERS
56
Even if oscilloscopes (and logic analyzers) have builtin time-measurement features, you also should be Photo 10—The HP 5372A frequency and time interval analyzer is inspired to get a good unian impressive ultra-fast counter. Here the frequency output of a generator is plotted on the vertical axis and time is on the horizon- versal frequency meter. A tal axis. A small frequency variation (from 38.300 to 38.305 kHz) basic unit enables you to is clearly visible, and its frequency is, well, 50 Hz. With a tool like measure frequencies and this, you can quickly determine the root cause of a problem, such durations, but a better unias a noisy power supply. versal counter like my trusty Hewlett-Packard 5334B would also allow you to measure same trick to get performance measureduty cycles, relative phases, and more. ments: pulse a GPIO each time some Frequency meters can be divided into event happens (like interrupt routine three categories. Basic meters simply execution), and count them with your count the number of signal periods durlogic analyzer. Applications are endless, ing a given time. Thus, they provide especially if you need to manage a lot of only a very limited resolution for lowdifferent signals, for example when drivfrequency signals. For example, a 10-Hz ing brushless motors (see Photo 9). signal can be measured with only a 1-Hz There are now “mixed-signal” scopes resolution for a 1-s sampling duration on the market, which are standard digi(the displays shows “10”). tal scopes with some extra digital Reciprocal counters allow increased inputs, providing logic analyzer-like fearesolution for low-frequency signals. tures. I’ve never used one, but don’t think they’re the best choice. They don’t The idea is simply to measure the period (by counting a high-speed clock’s numappear to support state analysis, and ber of periods—say, 10 MHz—during their channel count stays quite low (8 or each signal period) and then calculate the 16?). So, think twice, especially as the inverse of the period to get the frequency. cost for such an option is probably highWith the same example of a 10-Hz signal er than the cost of a full-featured 100and 1-s measurement duration, the dischannel logic analyzer on the Internet. play will show “10.000000 Hz,” a 1-milHaving everything integrated in the lion-time improvement in resolution same package is a plus, but you can compared to a basic counter. always cross-trigger a scope and a logic For elusive events, reciprocal counters analyzer using the back-panel BNCs. are still limited by their main clock. Similarly, there are PC-based low-cost Even a 100-MHz clock wouldn’t enable logic analyzers around, but even though you to measure single-shot events with they can be useful, they are still quite a resolution higher than the reciprocal of limited compared to full-featured logic 100 MHz, or 10 ns. To get a higher precianalyzers for about the same investsion, the last category of counters was ment. Except if you are space limited, of developed: interpolating counters. The course! idea is to add an analog interpolator to A last word on digital signals: if you measure times shorter than a period of work on microcontrollers, your life the main clock. Think of it as a capaciwould be far easier if you got some protor charging during a fraction of a period tocol analyzers for interfaces such as and measured with a sample-and-hold SPI, UART, I2C, Ethernet, USB, and so circuit. That way the resolution is no on. Some oscilloscope or logic-analyzer
longer limited by the clock. This is how you can find devices with 10-digit resolution and 500-ps single-shot resolution like Agilent’s 53131A. One more thing on the topic of frequency measurement. I had the chance to get a quite unusual, but really impressive and useful, piece of equipment: an HP 5372A Frequency and Time Interval Analyzer (see Photo 10). This is a highrange interpolating counter, but with a specialty: it can take more than 10 million measurements per second, store them, and let you analyze the results either in the time domain (frequency or time interval versus time) or in a statistical way through histograms. I initially thought that I would use it once per year, but I’m happy to say I switch it on much more often! It is the perfect tool for measuring the FM deviation of a transmitter. It’s also useful for analyzing timing jitter, checking the statistical duration of an interrupt routine, and characterizing the start-up behavior of an oscillator (Refer to my 2008 article titled “Let’s Be Crystal Clear,” Circuit Cellar 215). If you find one that fits your budget, buy it!
EQUIPMENT TO COME Here we are. We have looked at the main time-domain equipment in my
Photo 11—A time domain reflectometer like this old Tektronix 7S12 can be very helpful for pinpointing impedance mismatches. It is sensitive enough to detect that a SMA-to-BNC adaptor is far from perfect. A little “bump” on the plot at a measurable distance from the test connector indicates this. CIRCUIT CELLAR®
•
www.circuitcellar.com
" 64# &OHJ OFFS T company’s lab. Of course, I also have some exotic stuff like a time-domain reflectometer (see Photo 11), LCR meter, VXI-based data logger, infrared thermal imager, insulation meter, BER meter, and a couple of other fun devices. In my next column, I will finish this overview with frequency-domain equipment and present an in-depth look at the spectrum analyzer and network analyzer. This will allow me to show you that RF test gear is not black magic. In the meantime, happy buying! I
#FTU'SJ FOE
5 PU BM1IBTF64#BOBM Z[FS T G FBU VS FS FBM U J NFEJ TQM BZBOE mM U FS J OHPGM J WF64#EBU B
Robert Lacoste lives near Paris, France. He has 20 years of experience working on embedded systems, analog designs, and wireless telecommunications. He has won prizes in more than 15 international design contests. In 2003, Robert started a consulting company, ALCIOM, to share his passion for innovative mixed-signal designs. You can reach him at
[email protected]. Don’t forget to write “Darker Side” in the subject line to bypass his spam filters.
REFERENCES Agilent Technologies, “Choosing an oscilloscope with the right bandwidth for your application,” Application Note 1588, 2008, http://cp.literature.agilent.com /litweb/pdf/5989-5733EN.pdf. ———, “Fundamentals of electronic counters,” Application Note 200, 1997, http://cp.literature.agilent.com/litweb/pdf/5965-7660E.pdf.
SOURCES 1156A 1-GHz Active probe and 53131A Universal counter Agilent Technologies | www.home.agilent.com
64%
#FBHM F64# 1SPU PDPM"OBM Z[FS t3FBM U J NFEJ TQM BZXJ U I 64#DM BTT M FWFMEFDPEJ OH t.POJ U PSIJ HI
G VM M
BOE M PX TQFFE64#EBU B
HP5334B Universal counter, HP5372A analyzer, and HP83480A oscilloscope Hewlett Packard | www.hp.com Waverunner 6050 digital oscilloscope Lecroy | www.lecroy.com
Beagle protocol analyzer TotalPhase | www.totalphase.com
NEED-TO-KNOW INFO For more need-to-know information about building lab equipment, the Circuit Cellar editorial staff recommends the following content: — Programmable Voltage Source by Paul Ward Circuit Cellar 209, 2007 Need a stable low-noise voltage source? Build a dual-power supply with 4.5-digit displays with two ranges. When the output relay is open, you can use the channel as a 4.5-digit voltmeter. Topic: Voltage Source, Voltmeter, Noise Go to: www.circuitcellar.com/magazine/209.html — Precision Oscillator Calibrator by Michael Griebling Circuit Cellar 210, 2007 Build a precision oscillator calibrator to quickly and accurately measures low frequencies. The system communicates with a computer, perform initial set-up tasks, and displays measured oscillator errors. Topics: Oscillator, Calibrator, Frequency Go to: www.circuitcellar.com/magazine/210.html
www.circuitcellar.com
•
CIRCUIT CELLAR®
64%
#FBHM F64# 1SPU PDPM"OBM Z[FS t3FBM U J NFEJ TQM BZXJ U I EFTDS J QU PSQBS TJ OH t.POJ U PSG VM M BOEM PX TQFFE64#EBU B
' PSBT QFD J BMEJ T D PVOU
WJ T J U XXX U PU BM QIBTF D PNPG G FS $$
* $ 41*
BOE$"/U PPM T BM T PBWBJ M BCM F
* OEVTU S Z M FBEJ OH FNCFEEFE TZTU FNTU PPM T
August 2010 – Issue 241
2467A Oscilloscope, TLA704/7L3 logic analyzer, and 7S12 TDR/sampler Tektronix | www.tek.com
57
F
ROM THE BENCH
by Jeff Bachiochi (USA)
Application Communication with USB (Part 3) Assembly Code Finale Ready for the last installment in this article series about USB communication? You understand the enumeration process and you’re familiar with the standard device descriptor. Here you learn about the two interactions that take place through the configured device’s established endpoints (EP1 and EP2).
August 2010 – Issue 241
T
58
he USB peripheral that most manufactures have added to their lineup is much more complicated than a mundane shift register or counter/timer. It’s more like a separate processor specially built to obey all the rules set down by the USB Implementers Forum’s USB specifications. This serial interface engine (SIE) really takes the heat off having to verify bus states and timing. Each manufacturer is rather tight-lipped about how its baby really works. They’ve defined the interfacing scheme and put labels on all the register bits, but they don’t do such a good job describing the entire process, other than in general terms. I think many manufacturers have found that in solving the physical design dilemma with a blackbox peripheral they’ve created another problem. Teaching a programmer how to use it becomes an educational nightmare. Much of this can be sidestepped if you provide some magic code that supports the peripheral with simple functions. C seems to be the language of choice. Programmers are happy. They can use USB without really knowing how it works, and most don’t care. Manufacturers are happy. They don’t have to explain it all. I spent a couple of months getting a USB device enumerated with only assembly code. Why? I like writing in assembly. I like knowing how things work. I feel like I’m copping out when I add a USB-to-serial chip to a circuit, especially when there is a USB peripheral available in the microcontroller. But I just don’t know how make it work with assembly language. I’m
going to conquer this for me and any reader who is willing to go along for the ride.
LIFE AFTER DOO-WOP Doo-Wop is the sound my PC makes when it accepts a USB device into the fold. To me it represents the sweet sound of compliance; but in reality, the sound doesn’t signify a task of any real importance. If you looked at the USB documents I referenced in previous columns, you realize that USB as a serial port is only one small part of what this USB umbilical cord can be used for. Except for the drivers loaded by the PC, all the devices and traffic are essentially handled the same way. The code being developed here presents itself as a virtual serial port to your PC application. This virtual serial port transfers the application’s UART configuration through a USB channel to the slave device at the other end of the connection so that its hardware can reflect the PC’s application configuration. Perhaps, it might be used to set up a hardware UART in the microcontroller for your own USB-to-UART interface. This project’s EndPoint 1 (EP1) interface allows the device to notify the host of its serial hardware status. These include all of the configuration parameters as well as error status and handshaking I/O associated with the old serial DE-9/DB-25 connections. The Configuration Descriptor included the Endpoint Descriptor requesting that the host poll the device for potential notifications every two frames as interrupt transfers. A CIRCUIT CELLAR®
•
www.circuitcellar.com
GETTING THE DATA THROUGH The exchange of application data is anticlimactic with respect to the dance of activity that must take place before a single byte can be passed. In the first part of this series, I looked into the Transaction Complete interrupt code. The SIE sets this interrupt flag when a transaction has been completed. I found that this was due to the reception of a SETUP, an IN, or an OUT token. During enumeration all of the communication began with a SETUP token through EP0, the default endpoint. With much of the code directed through the SETUP branch, we didn’t have much interaction with the IN and OUT token branches. As the SETUP token branch worked its way toward individual Standard Device Requests or Class Device Requests, we saved the request as a reminder of what was being requested. Many requests required additional packets of information to be either retrieved by the host via an IN token or set by the host via an OUT token. When an IN token was required by a request, the device had to preload the requested data into the EP0In endpoint buffer so it would be ready when the host came back with an IN token. The Transaction Complete interrupt for a data phase IN token does not need to execute any code unless the data phase requires additional packets of data, in which case the IN token path would use the request reminder to help determine what data should be preloaded into EP0IN again before releasing it. When a request requires the host to send additional information, it’s done via a data phase OUT packet. The Transaction Complete interrupt for a data phase OUT token requires the device to unload the packet and process www.circuitcellar.com
•
CIRCUIT CELLAR®
this accordingly based on the request reminder. As we learned earlier, EP0 is a special case that handles SETUP, IN, and OUT tokens through the same endpoint. Additional endpoints created through the set-up process will only handle data flowing in one direction, and thus will be only an IN or an OUT endpoint. The Transaction Complete interrupt routines become a little more complicated as we need to distinguish between IN and OUT tokens from each of the various endpoints. An IN token via EP0 will be in response to a SETUP token. An IN token from EP1 will be a poll looking for a notification from the device. An IN token from EP2 will be a poll looking for application data from the device. Therefore, the IN token and OUT token paths will need to identify the endpoint so they can branch appropriately. Since EP2In and EP2Out will be used to pass application data, it makes sense to use large buffers for this data. We also saw that the Microchip Technology PIC18F4450 has 256 bytes of dual-access RAM for the total USB interface, so “big” is a relative term here. USB specifications call out maximum packet sizes up to 1,024 bytes. We are physically limited to somewhat less with this microcontroller. If you remember the Endpoint Descriptors for EP2 call out 64byte buffers. Half of the total dual-port USB RAM is used for EP2 buffers. About one-fourth of this dual-port USB RAM is used for the five 4-byte buffer descriptors and the 8-byte endpoint buffers for EP0 and EP1. A remaining 64-byte block is used as an application buffer for this project. I want to be able to completely empty the EP2Out buffer whenever application data arrives via an OUT token to this endpoint. The ProcessOutToken branch of the transaction complete interrupt first determines the Endpoint from the EP bits of USB_USTAT. If it’s EP2 and there is room in the application buffer (its empty), I can move the application data out of EP2Out, into the application buffer, and release the buffer back to the SIE. Otherwise, I just leave, which makes the SIE NAK the OUT token, forcing the host to try again. So, you can see that keeping the application buffer empty is important to the throughput.
More on this later. The ProcessInToken branch of the transaction complete interrupt is set only once an IN token has been processed. This happens only if the EP2IN buffer has been filled with application data and the buffer has been released to the SIE (BD5STAT.7=1). Of course, once the data is ready, the SIE will still be waiting for the host to request the data by polling with an IN token. You can see that all the activity to send application data takes place outside of the ProcessInToken branch, thereby requiring no code there. However, the preloading of the EP2IN buffer does require code in the project’s main_loop. Since this project is based on how to use the hardware USB interface, it stands to reason that there won’t be too much code presented here other than that for the USB support. The main_loop consists of just two routines. The first routine checks the state of the virtual UART. The virtual UART consists of registers that hold the present state of the UART inputs, outputs, and configuration as if I had invoked the use of the hardware UART for this project. If a state has changed, I call notification routines to send this new information back to the host via its polls to EP1In. The second routine watches the application buffer. If any application data has been deposited there, it will move it to the EP2IN buffer and release the buffer to the SIE (if it is not busy), thus keeping the application buffer empty. In many cases, throughput is not a issue. Sure, we all want things to happen fast, but this is relative. Suppose you designed this as a USB-to-UART interface and the UART is running at a low data rate. There is no need for speed in getting the application data through the USB pipe as the UART is the bottleneck. However, suppose there was no slow peripheral in the system. In that case the bottleneck might actually be the transferring of data from or to a USB buffer. The next packet cannot be handled by the SIE unless you have released control of the buffer. That’s hard to do if you’re still in the process of emptying it. Pingpong buffering can be used to help relieve this potential bottleneck. As its name implies, ping-pong buffering is a
August 2010 – Issue 241
NAK (or indication of not ready) by the device to the host’s poll is a simple reply that prevents excessive traffic on the bus when there is no new information ready for the host. If the device needs to send a notification, it merely preloads the EP1In buffer with the required data and returns ownership of the Endpoint to the SIE. On the next poll, the SIE will allow the IN Token to complete. The host will then receive the notification. Notifications will continue on an as-needed basis.
59
strategy that requires an extra buffer assigned to an endpoint. Data throughput increases as it ping pongs or alternates between the two buffers. Since the SIE is its own entity, it operates on its own while the micro is executing code. The double buffering makes it all flow a little smoother. With the microcontroller’s 256-byte dual-port RAM, ping-pong buffers are iffy. If you use ping-pong buffers, there are only a few possible configurations: no ping-pong, ping-pong with all endpoints, ping-pong only with EP0Out, or ping-pong with all endpoints except EP0. The maximum size of the buffers may be severely limited by the space available. If I choose to use P/P where it is most effective, I am forced to use it on EP1 and EP2. Immediately, I must reserve 0x28 bytes for the 4-byte endpoint descriptors (instead of 0x16). The endpoint buffers for EP0In and EP0Out remain the same, but EP1In now has two buffers—EP1INOdd and EP1INEven—for a buffer total (so far) of 0x20 (instead of 0x18). This leaves 0x100-0x28-0x20 or 0xB8 bytes to share between EP2INOdd, EP2INEven, EP2OUTOdd, and EP2OUTEven. Now 0xB8 divided by four is 0x2E, or 46 decimal. So, the largest maximum buffer size would be limited to 32 bytes, instead of the 64 bytes I am now using without P/P. And I’d have to find room somewhere else for my application
buffer. In our case, there would be no beneficial increase in throughput by using P/P buffers.
OTHER USB INTERRUPTS I have not touched on any of the other potential USB interrupts associated with USB operations. In many instances, you don’t have to provide any support for them unless they are applicable to your design. The Start of Frame (SOF) interrupt can be used to monitor the frame count when using isochronous transfers. While this streaming data is delivered at a guaranteed rate, any errors—which prevent a packet from arriving or would make the data unreliable—must be accounted for. You might choose to repeat an already received packet of data to “fill in” for the bad packet. Audio data is typically sent via isochronous transfer where the loss of any single packet would not be detrimental to speech, sound, or music output. Should your application go into an inactive state, possibly due to the PC going into Standby mode, the system will turn off services to conserve power. USB activity will cease. Your device is required to recognize this condition and go into its own power conservation mode. The IDLE interrupt will be set whenever the bus has no activity for more than 3 ms. If a device does not support this, it is
limited to drawing 500 µA from the bus. ACTIVE is the complementary interrupt to IDLE. It indicates that the host has again resumed communications and the device should come out of its low-power mode and be ready to service requests. When SUSPEND and RESUME routines are used to support IDLE and ACTIVE, the current draw is limited to 2.5 mA. If a device isn’t communicating through an endpoint for some reason, the stall bit can be set in BDxSTAT.BSTALL for that endpoint buffer. The SIE would continuously return a STALL handshake for any request to that endpoint. This fact is also reflected in the endpoint control register UEPn.EPSTALL. When the SIE acknowledges with a STALL, the STALL interrupt is set. You might remember the SET:GET:CLEAR COMM FEATURE class requests available to the host. These requests allow the host to set, determine the status of this STALL, and to clear the STALL condition if it chooses. Lastly, you have the ERROR interrupt. There are a number of operations that may indicate an error condition. All of the errors are produced by the SIE and include timing or CRC errors. While there isn’t anything that needs to be done because the SIE’s action will cause a retry, they are presented as a potential debugging tool that may help determine why communication is not optimum.
August 2010 – Issue 241
I2C APP
60
Figure 1—The schematic. With the disappearance of serial ports from our PCs this simple project will make it much easier for me to communicate with those I 2C projects that I have hanging around the lab.
Originally, I wasn’t going to present a complete project here, but an opportunity presented itself. Every time I have used an I2C device, I’ve had to drag out my old laptop because it has the only RS-232 serial port left in this office. I do have a few USB-to-serial dongles, but I thought this would be a good time to update the serial-to-I2C design to a USB-to-I2C design. Up to now, I’ve been running this USB code using a PIC18F4450. I think I’ll really push this and use a much smaller device. The
CIRCUIT CELLAR®
•
www.circuitcellar.com
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
Data memory map 00h FFh 00h Bank 1
GPR
000h 05Fh 060h 0FFh 100h
GPR FFh 00h
Bank 2
GPR (DPRAM)
1FFh 200h
FFh 00h
2FFh 300h
FFh 00h
3FFh 400h
FFh 00h
4FFh 500h
FFh 00h
5FFh 600h
FFh 00h
6FFh 700h
The first 96 bytes are general-purpose RAM (from Bank 0) The second 160 bytes are special function registers (from Bank 15). When 'a' 1: The BSR specifies the bank used by the instruction.
Bank 3
Bank 4
Bank 5
Bank 6
Access bank 00h Access RAM Low
Bank 7 7FFh 800h
FFh 00h Bank 8 FFh 00h Bank 9
Unused read 00h
5Fh Access RAM High 60h (SFRs) FFh
8FFh 900h
FFh 00h
9FFh A00h
FFh 00h
AFFh B00h
FFh 00h
BFFh C00h
FFh 00h
CFFh D00h
FFh 00h
DFFh E00h
Bank 10
Bank 11
Bank 11
Bank 12
Bank 14 FFh 00h
1111
Access RAM
Bank 0
When 'a' 0: The BSR is ignored and the access bank is used.
Bank 15
Unused SFR*
FFh
SFR
EFFh F00h F53h F5Fh F60h FFFh
*SFRs occupying F53h to F5Fh address space are not in the virtual bank.
Figure 2—The Data memory map of the PIC18F14K50 shows it has 0x300 bytes of generalpurpose RAM (GPR) that is divided into 0x100 byte banks. The last bank holds the SFRs, which are all of the registers associated with the micro and its peripherals. Each instruction can use either a selected bank via the bank select register (BSR) or the (virtual) Access bank. The Access bank is a special combination of the first part of Bank 0 (0x000-0x05F) and the SFRs (0xF60-0xFFF). smallest device in Microchip’s USB line right now is a 20-pin device, the PIC18F14K50. There is an abundance of I/O for this project, as you can see in Figure 1. I use the extra pins to drive LEDs that indicate the status of various parameters. This project gets power from the USB bus. The I2C bus connector can also supply power to external circuits as long as everything remains under the maximum allowable 100 mA. The circuit’s simplicity speaks for itself. www.circuitcellar.com
•
CIRCUIT CELLAR®
The cost of parts is around $5.
PORTING THE CODE I fully expected this to be an easy port, essentially because I was just reassembling my working code for this new processor. But I was surprised when the code failed to enumerate. Thus, I had to review the files I’d copied into this new project’s folder. The USB constant file CDCdefinitions.INC needed only a few changes. The new microcontroller has a smaller
RAM area, and the dual-port RAM is moved from 0x0400 down to 0x0200. The CDCDescriptors.INC file didn’t need any changes. The only other file was USB_SS.ASM. Very little was changed in this file other than redefining the I/O pins and configuration bits that are particular to any micro. The original source file was 44 pages in length. Although there wasn’t much to change, the fact remained: it wasn’t working! I went back into debugging mode. I found the device was partially enumerating up to the point where a SET_CONFIGURATION token was received. All the device descriptors were being fetched correctly, but when the host wanted to configure the device, it wasn’t happening. In stepping through the SET_CONFIGURATION routine, all looked fine. But the UEPx special function registers (SFRs) used to define the function of each endpoint were not being written correctly. I was told the bare spot I scratched on my scalp over this issue will eventually grow back in. Refer to Figure 2. The RAM for the micros is divided into 16 banks of 256 bytes per bank. Any byte within a bank can be reached using a single instruction cycle. Banks 0 to 14 (when implemented) are general-purpose registers (GPRs). Bank 15 is reserved for SFRs. Note that the SFRs don’t require the full bank. In addition to these 16 banks, a special ACCESS bank was created containing the lower bytes of Bank 0 (x00–0x5F) and the upper bytes from Bank 15 (0x60–0xFF). Many instructions can use either the ACCESS bank or the selected bank, which is set via the bank select register, or BSR. This makes it easy to get to the SFRs and lower GPRs of Bank 0, or the selected bank (in the BSR), without having to frequently change banks via the BSR. Refer to the footnote at the bottom of Figure 2. It states that SFRs below 0x60 are not part of the ACCESS bank and must be dealt with via Bank 15. Ahh! It seems that the actual number of SFRs in this device exceeds the number of registers set aside for SFRs in the ACCESS bank! Now guess where those UEPx registers that are causing trouble reside? The only clue that led me to start
August 2010 – Issue 241
BSR<3:0>
61
August 2010 – Issue 241
looking for an anomaly was the fact that the BANK 0 RAM was receiving the values meant for the SFRs! It’s humbling to be kept on your toes by these little unsuspecting issues. To fix my code, I had to use Bank 15 (BSR = 15). And before instructions using any of the SFRs from 0x53–0x5F, I had to make sure to use the selected bank and not the ACCESS Bank. With these changes, the code enumerated properly and now the demo retransmits every character it receives. Now I can get on with the I2C application.
62
command will return: COMMAND ERROR
. An unsuccessful command will return: NO DEVICE OR I2C ERROR. You can test the I2C interface to see if it’s hung up with I2CSTATUS and get back either I2C=READY or I2C=BUSY. The use of a terminating carriage return for all commands makes it easy to locate completed strings in the ring buffer, remove them, and identify any commands. The commands are expected to contain values in a decimal format of one to three characters. If you are familiar with I2C addresses, these are always a 7-bit value that has been shifted left one bit. That makes the address always an even number. Within an I2C transfer, the first byte is this address. An even address is a command to “read” from a device. If you “or” a 1 with this address (making it odd), the command becomes a “write” to the device. The microcontroller has a hardware I2C peripheral. It is initialized to be used as an I2C master. A clock generator is based on a counter
that uses FOSC/2 as its time base. The counter is reloaded with a userdefined value each time it counts down to zero. I have set this value to give a 100-kHz clock. (It can be set up to 1-MHz, but not all devices can operate at this speed.) An I2C bus uses open-collector drivers with external pull-ups to VCC. The idle state for the bus is for the clock and data lines to be undriven—that is, pulled high by the external pull-ups. If you find that either of these lines is low while you are idle, then the bus is being held busy by a device. This is an error condition. It is legal for a slave APP CODE I2C device to hold the bus low. This The original code was designed in a way to move full 64-byte blocks of indicates that it is busy processing a code as fast as possible. The UART received command and the master buffer used by the application to store should be patient before sending or characters was not a ring buffer requesting more data. You can see that because both the UART buffer and if a slave device should lock up, this EndPoint buffer were of equal length condition will continue indefinitely. (64 bytes). A ring buffer will hold So, it’s a good idea to check the bus only the buffer length-1 characters. status before attempting to use it. This means a full 64-byte endpoint Two routines are used to determine buffer could not be handled in one the receipt of a legal command. The transfer, which really cuts first routine compares down on throughput. In input characters to string this design, the circuit constants in a Message will receive much shorter Table. These strings are pieces of data, with a maxialso used as a source of mum command length of output messages. The secabout 24 characters. This ond routine must convert means multiple commands received characters into a will fit into the 64-byte (or numeric value between 0 63-byte) buffer. The advanand 255. These can be tage that a ring buffer gives from 1 to 3 characters in is that it doesn’t have to be length. The routine clears completely emptied every UART_Temp, checks for time it is used. The adding a valid ASCII numbers and removing of characters 0x30-0x39 and subtracts can be truly independent 0x30 to get a numeric functions. value to store in The I2C commands I UART_Temp. If the next character is ASC then will use take a simple UART_Temp is multiform. To read register Y in plied by 10 before the an I2C device at address X, new value is added to use the form: I2C X RegisUART_Temp. The value ter Y. To write the Photo 1—The USB-to-I2C converter (center of the keyboard) is shown of UART_Temp must value Z to register Y in an here communicating with an ultrasonic sensor (on the right) using the never be greater than 255. I2C device at address X, Realterm terminal application running on the PC. You can see the text To cut down on string use the form: I2C X Regiscommands on the Realterm screen. On the left side of the keyboard is compares, I test the first ter Y=Z. Both comthe Beagle protocol analyzer with its supporting PC application on the character of each string. If mands will produce a left side of the screen. You can see the USB activity along with an OUT it isn’t “I” or “R,” I toss it response in the form: I2C token highlighted line that identifies the last command sent by the Realterm. Following this you can see IN token polls that contain the out and try the next charX Register Y=Z. response from the sensor board. acter. When the is An improperly formed CIRCUIT CELLAR®
•
www.circuitcellar.com
reached and nothing has been found, the response is an error message. If there are matches and legal values (string, value, string, value), I go to the I2C READ routine. If there’s a match (string, value, string, value,=,value), I go to the I2C WRITE routine. Photo 1 shows this prototype project communicating with a USB sensor board.
from its SSPBUF. Note that some slave devices may hold the clock line low, effectively requesting a delay from the master, so they have time to get the requested data into their SSPBUF register. If the slave hangs up, the bus will remain in this active state preventing further bus activity until the slave has been reset.
I2C USB IT UP If you read this entire article series, you should have a better understanding of what’s going on under the covers of USB. The enumeration process is excruciatingly painful, from preparing the USB descriptors to responding to each request from the host. However, once you’ve got through all of this, the remaining hurdles seem like a walk in the park. Keep in mind that good tools are a must, especially when working with high USB speeds. For the PIC user, MPLAB and an in-circuit debugging tool are essential. For USB work, I can’t imagine trying to sort out communication issues without a protocol analyzer like the Beagle. While this isn’t for the novice, you can get through it with a little determination. The biggest problem I found was trying to get good information out of a manufacturer. Documentation is a bit sketchy on how many of the control bits affect the SIE or are affected by it. I can appreciate that those who wish to use higher-level language may not need (or want) to know every quirk, especially when a whole USB Framework for both slave and host devices is available for free. Some of us are just gluttons for punishment. I Author’s note: I thank Dan Butler of Microchip Technology and Frank Hane of Total Phase for their encouragement. Jeff Bachiochi (pronounced BAH-key-AH-key) has been writing for Circuit Cellar since 1988. His background includes product design and manufacturing. You can reach him at jeff.bachiochi @imaginethatnow.com or at www.imaginethatnow.com.
PROJECT FILES To download an additional file, go to ftp://ftp.circuitcellar. com/pub/Circuit_Cellar/2010/241.
RESOURCES USB Class Specifications, www.usb.org/developers/dev class_docs#approved. USB Implementers’ Forum, “Language Identifiers (LANGIDs),” 2000, www.usb.org/developers/docs/ USB_LANGIDs.pdf.
SOURCES PIC18F14K50 USB Microcontroller Microchip Technology, Inc. | www.microchip.com Beagle USB 480 Protocol analyzer Total Phase, Inc. | www.totalphase.com
August 2010 – Issue 241
Writing to a byte-registered I2C slave device is straightforward. The I2C peripheral gives you feedback at each step of the process so you can go away and do other things while each step is completed automatically (since this process is slow compared to execution times). Rather than use interrupts, I remained in the process and just waited for it to be done. After all, that was the main point of the application, and any important USB activity would interrupt this process. To begin an I2C write (or read), check for bus activity. If none, initiate a start bit. When the start bit has finished (SSPCON.SEN=0), place the address (even) into the SSPBUF register and the data will be clocked out by the peripheral. When clocking the byte is finished (PIR1.SSPIF=1), look for an acknowledge from the slave (SSPCON2.ACKSTAT=0, the slave has pulled the data line low). If there isn’t one, exit with an error. Repeat this (minus the start bit) with the register number and then the data value. Then end it up by initiating a stop bit. That’s it. Any slave on the bus will look for its address after every start bit it sees. If the address doesn’t match, it remains inactive for the rest of the bus activity. Should the (even) address match, a byte-registered device will update its pointer with the next byte received, and the following byte of data will be placed according to the pointer. Reading from a byte-registered I2C slave device requires two operations: a write and a read. Since the byte-registered slave uses a pointer, you must make sure it is pointing at the register you want to read from or you will get data from its present position. To begin an I2C read, start with a write. That is, perform the aforementioned steps, but write no data byte to the slave and use the restart bit instead of the stop bit. When the restart bit has finished (SSPCON.SEN=0), place the read address (odd) into the SSPBUF register and the data is clocked out by the peripheral. When finished (PIR1.SSPIF=1), look for an acknowledge from the slave (SSPCON2.ACKSTAT=0); otherwise, exit with an error. Now initiate a read mode (SSPCON2.RCEN=1 tells the peripheral to clock data into the SSPBUF) and then end it by initiating a stop bit. That’s it. Any slave on the bus will look for its address after every start bit it sees. If the address doesn’t match, it remains inactive for the rest of the bus activity. Should the (even) address match, a byte-registered device will update its pointer with the next byte received. The restart bit resets the slave and it again looks for an address match. Should the (odd) address match, a byte-registered device will use the present pointer value to load its SSPBUF with a byte of data and allow the master to clock out this data. When the master has received the data (PIR1.SSPIF=1), it fetches it
65
S
ILICON UPDATE
by Tom Cantrell (USA)
MIPS and More When it comes to 32-bit MCUs, no doubt ARM-based parts are on a roll. So, is the story over? Not so fast, say major players. Microchip Technology, for one, is going all-in with chips based on the MIPS architecture. Their latest parts are a reminder there’s more to a successful embedded design than an instruction set.
August 2010 – Issue 241
I
66
n the history of computing, how many different instruction set architectures have come out of the lab? Surely, hundreds have achieved some commercial success—and the number is more like thousands if you count the one-hit-wonder PhD dissertations and such. Talk about fad and fashion, computer architectures are seemingly like hemlines. What’s old is new until it’s old again. There was a time it mattered—for example, in the days of assembly language programming. And compatibility, at least on the surface, still matters when you’re talking about a PC or video game (i.e., something that needs to run last year’s binaries). But the fact is that strict object code compatibility is no longer an issue for most embedded designs. A lot of things do matter, such as toolchain compatibility and the availability of “canned” code, but the “flavor” of an instruction set isn’t one of them. As silicon continues to suck the functionality of an entire system into a single chip, what designers need is a chip that has all the memory, peripherals, and glue logic needed. Plus, it must consume less power and come with good tools, adequate support, and the right price. That’s not to say a particular architecture isn’t better than another for a certain class of application. Indeed, it’s interesting to see how architectures originally designed for “computers”—such as ARM and MIPS—continue to
devolve to better fit the needs of embedded “controller” applications. Better late than never, the “computer” guys finally get it when it comes to issues like code density, low-power consumption, and fast, deterministic interrupt response.
WIRED No doubt MIPS is playing catch-up to ARM in the MCU race; but with a heavy hitter like Microchip on their side, the gap is closing. Consider the new PIC32 ’5xx/6xx/7xx parts that in one fell swoop bring Ethernet, USB, and CAN applications into the fold. Under the hood, the action centers on the PIC32 core I covered a couple of years ago (“MIPS for the Masses,” Circuit Cellar 216, 2008). With a five-stage pipeline, this is a relatively high-performance alternative compared to, for example, the ubiquitous ARM Cortex-M3 parts. Just keep in mind that performance differences at this level are as much about bragging rights as real-world impact. To wit, Microchip claims 1.5 DMIPs/MHz for the PIC32, while Cortex-M3 is said to deliver 1.25 DMIPs/MHz. As is usually the case with 32-bit MCUs, flash memory access time is a performance limiter with up to two wait states required for topspeed (80 MHz) PIC32 operation. Also, as usual, a wide (128-bit) bus with cache and prefetch techniques are used to mitigate the “flash bottleneck.” CIRCUIT CELLAR®
•
www.circuitcellar.com
Alternatively, there’s the 0-wait state alternative of executing out of on-chip RAM. It’s all the more viable an option considering the ’5xx parts include 64 KB of RAM and selected members of the ’6xx/’7xx line feature up to 128 KB. Just remember that contention between code and data access will impose delays. As well, flash has plenty of elbow room for your code with 256 or 512 KB (plus 12 KB for boot code) on tap. Peripheral-wise, the new parts come with a full quiver of I/O (see Figure 1). The ’5xx/6xx/7xx numbering scheme designates the mix of the big-ticket USB, CAN, and Ethernet features. The ’5xx parts have one USB 2.0 and one
CAN (2.0b) module, while the ’6xx parts combine the USB module with a 10/100 Ethernet MAC. The ’7xx goes all the way with USB, Ethernet, and two CAN modules. Turning to the usual I/O suspects, the parts follow the trend of meeting diverse application needs with brute force. We’re talking five 16-bit counter/timers, two pairs of which can be combined to act as 32-bit units. Subject to package size (64- and 100-pin options) and some pin-sharing considerations, you’ve got up to six UARTs, four SPIs, and five I2C ports to work with. On the analog side, there’s a 16channel multiplexer fronting a 10-bit 1-MSPS ADC and two analog com-
parators. Beyond the MCU’s ability to fly solo, there’s also an expansion bus capability with 8- or 16-bit data and 16-bit address busses, plus two Chip Select lines. Keeping all the data flowing are eight general-purpose DMA channels, supplemented with four (’5xx/’6xx) or eight (’7xx) dedicated channels. The original circa 1980s MIPS chips were notable for carrying the “Reduced” aspect of RISC to the extreme when it came to interrupts. Essentially, in response to an interrupt they would stack the PC and status register, otherwise leaving a bunch of handholding to software. When it comes to such extreme minimalism,
VCAP/VDDCORE
OSC2/CLKO OSC1/CLKI
OSC/SOSC Oscillators
Power-up timer
FRC/LPRC Oscillators
VDDVSS *MCLR
Oscillators start-up timer
Voltage regulator
PLL Power-on reset
Precision band gap reference
Dividers USBCLK
Watchdog timer
SYSCLK PBCLK
Brown-out reset
PLL-USB Timing generation
Peripheral bus clocked by SYSCLK
CN1-22
PORTA Timer1-5 Priorityinterrupt controller
EJTAG
INT
PORTB USB
CAN1, Ethernet CAN2
DMAC
ICD
MIPS32 M4K CPU Core
PORTC
IS
DS 32
32
32
32
32
32
32
32 PORTD
Bus matrix 32
32
32
PWM OC1-5
Peripheral bus clocked by PBCLK
JTAG BSCAN
IC1-5
SPI1, 1A, 2A, 3A
I2C1, 2, 1A, 2A, 3A
32
PORTE
32 Prefetch module
Data RAM
Peripheral bridge PMP 10-bit ADC
PORTF
UART1A, 1B, 2A, 2B, 3A, 3B 128-bit-wide Program Flash memory
PORTG
Flash controller
RTCC Comparators
Figure 1—Thanks to big-ticket I/O (e.g., Ethernet, USB, and CAN), the latest PIC32 parts give Microchip and MIPS a fighting chance in the high-stakes battle for 32-bit MCU supremacy. www.circuitcellar.com
•
CIRCUIT CELLAR®
August 2010 – Issue 241
128
67
Photo 1—Considering ARM’s headstart, MIPS has a lot of catching up to do. The new Microchip PIC32 parts with built-in Ethernet, USB, and CAN are a big step in closing the gap. there’s an argument that it’s possible to have too little of a good thing. With that in mind, PIC32 includes a fullfunction programmable priority/vector interrupt controller and an alternate register set for fast interrupt response and speedy context switching. And don’t overlook what can otherwise be budget-busting glue logic such as watchdog timer, low-voltage detect, voltage regulator, main/peripheral/real-time clocks, etc. Integrating these features makes all the difference when it comes to turning PIC32 from a “computer” chip into one that’s actually viable for “controller” applications.
support advanced code optimizations, but that’s clearly not the case with the compiler I received as you’ll see in the next section. Perhaps what actually comes with the kit is the so-called “Evaluation” version said to support all the compiler features, but only for 60 days. With its architecture rooted in “computers,” the PIC32 is well-suited for managing the PC-centric Ethernet and USB interfaces. Let’s take a look at a few of the demo programs and you’ll see what I mean. While Microchip has offered a
measure of networking software for their smaller PIC chips over the years, PIC32 ups the ante with a fullfeatured, and free, Berkeley Software Distribution (BSD) TCP/IP network stack. It comes with all the trimmings, including web services, sockets, and the usual alphabet soup of protocols: DHCP, UDP, ICMP, ARP, etc. With the ’795 chip’s 512 KB of on-chip flash memory, there’s plenty of room for eye-candy and the simple demo program included let’s you surf over to the starter board and grab a taste (see Photo 2). The USB support is welcome, but is a bit of a mixed bag, starting with the “On the Go” (OTG) feature. This refers to the capability of a device to dynamically switch between functioning as a USB device or USB host. The classic use case is said to be a printer that can act as a USB device when connected to a PC, but as well serve as a USB host to a connected camera. Every USB chip seems to have OTG these days, but maybe it should be called “On the Gone” since I’ve never had occasion to encounter any gadget that actually switches hats in this way. While the split personality aspect of OTG may not be so useful, it does allow the PIC32 to serve more conventional (i.e., single-minded) USB applications as either a device or host—make that “embedded host”
August 2010 – Issue 241
STARTING GATES
68
As usual, Microchip makes it real easy, and inexpensive, to evaluate their silicon. The PIC32 Ethernet Starter Kit (see Photo 1) is just $72 and comes with everything you need to get wired. Although called the “Ethernet” starter kit, the kit is equipped with a top of the line ’795 MCU and supports that chips USB features as well. The kit also includes Microchip’s MPLAB IDE featuring a “Lite” version of the GCC compiler. The documentation seemed a bit contradictory in terms of what exactly the “Lite” aspects of the compiler entail. It implied the “Lite” version doesn’t
Photo 2—When retro-marketing a “computer” chip as a “controller,” it’s true that getting rid of excess baggage is a challenge. On the other hand, there are some benefits of the “computer” heritage that can be exploited, such as the free BSD TCP/IP stack shown in action here. CIRCUIT CELLAR®
•
www.circuitcellar.com
24th International Trade Fair New Munich Trade Fair Centre 09–12 November 2010
Register online and enjoy the benefits: www.electronica.de/en/tickets
egnahc means exploring new paths.
Boards
Software
Microcontrollers
Virtualisation
DSPs
Forum
Time for embedded. Time for the future. The entire range of key technologies and forward-looking innovations. Visit electronica and the embedded Forum and experience their incomparable significance to the entire industry—with today’s solutions for tomorrow’s applications.
electronica 2010 embedded
Parallel event: hybridica. Trade fair for hybrid-component production. www.hybridica.de
get the whole picture
www.electronica.de/embedded
August 2010 – Issue 241
70
advances in optimizing compilers. You may recall how the “RISC” acronym was said by some to stand for “Relegate the Impossible Stuff to the Compiler.” However, one gotcha with compilers that are too smart for their own good becomes apparent at debug time. As the PIC32 “C” compiler manual quaintly puts it, be advised debugging optimized code “may occasionally produce surprising results.” For instance, variables and code will disappear if the compiler decides you don’t really need them. Let’s say you declare a variable and then have a statement that assigns a constant to it, followed sometime later by use of the variable in a calculation. Don’t think you’re going crazy when the compiler “disappears” the variable and assignment statement. It’s just being Photo 3—Another software freebie is USB drivers for both device and host applications. smarter than you and will simply use Operation as a USB host with the included FAT filesystem software is demonstrated here by the constant in the calculation. accessing the directory of a USB thumb drive. Or how about when you hit STEP at a conditional branch and the curwhich in USB-speak has some limitayour thing you’ll need to come to sor moves to the next instruction? tions compared to a “standard host” your own conclusions as to whether Does that mean the condition failed? like a PC. Furthermore, the PIC32 the PIC32 is up to snuff. Not necessarily. Remember that a chip itself, understandably, doesn’t “feature” (dubious in my opinion) of supply the VBUS power (100–500 mA) OPTI-MISER MISERY the MIPS architecture is that it you find on a PC USB port. Finally, One of the hallmarks of architecalways executes the instruction in it’s important to note the speed is tural evolution has been the the “delay slot” following a somewhat limited, offering “full branch (often a code-bloating speed” (12 Mbps) when configNOP when the compiler can’t ured as a device but just “lowfind something more useful to speed” (1.5 Mbps) as a host. put there). You have to hit Nevertheless, with the STEP again to see if indeed the caveats in mind, the kit condition failed (in which case includes some pragmatic demos. you’ll see the cursor step to the One turns the starter kit into a next sequential instruction) or standard Human Interface succeeded (cursor jumps to the Device (HID)—for example, a branch target). More advanced mouse—that will plug right into “code motion” optimizations any PC since HID drivers are can inspire even more headstandard issue these days. scratching. Consider the fact Alternatively, configured as a instructions can be moved a USB host and taking advantage long way—for instance, comof the growing PIC32 software pletely outside a loop you library’s FAT file system, other thought you put them in. demos show how to access the Yes, it’s possible to debug optiubiquitous USB thumb drives mized code, especially if you (see Photo 3). enjoy brain teasers. (For example, I should note the kit didn’t I wonder what would happen if include any CAN demos. It’s a you stuck a branch instruction bit of a moot point since I have Photo 4—One thing “computer” guys are good at is the in the branch delay slot?) With all neither the expertise nor lab black art of optimizing compilers. As shown here, there this in mind, the default compiler setup to perform any meaningare a lot of options to choose from covering a spectrum of speed, code size, and compile time trade-offs. (non)optimization specifically ful testing anyway. If CAN is CIRCUIT CELLAR®
•
www.circuitcellar.com
71_Layout 1 7/2/2010 10:48 AM Page 1
ition d E A S U r Elekto /usa m o c . r o t k e l www.e “Elektor? Prescribed reading for our R&D staff because that’s where we need professional guidance for microcontroller technology.” – Frank Hawkes, 39, development engineer – [Analog Digital Microcontrollers & Embedded Audio Test & Measurement ] US $ 7.95 - Canada $ 7.95
January 2010
[Analog Digital Micro
controllers & Embedded
December 2009
Audio Test & Measurement
]
US $ 7.95 - Canada $ 7.95
[Analog Digital Micro
controllers & Embedded
www.elektor.com Januar y 2010
February 2010
]
ent ] Test & Measurem
There’s More to Life than just USB!
ded Audio ollers & Embed l Microcontr Analog Digita
[
Audio Test & Measurement
US $ 7.95 - Canada $ 7.95
www.elektorusa.com
Preselector Elektor SDR for Here’s the USB Magic Eye automat ic tuning upgrade
!
www.elektor. com
$ 7.95 US $ 7.95 - Canada
Put a Stop to Throwawayism!
Buses USB and I2C Energybeyond Sav
com www.elektor.
Subscribe to Elektor now!
ings from Home Autom ation Fourier Analysis using Standards com LTspice & Excel Tech ATM18 pared
There’s Mor nolo gy to Life than just USB!e Proj N KDOW AC Dimmer with a Micro a Sto PFCPutCR p to Throwawa led Christm r reveayism
ects Logic Analyzer USB Magic Eye
as ! Hol fac Buses mp rida ysto we Circuits po 13 pag yo esnd La be of beg US Br’sAVR-USB inne an andd I2box junk C projollers & Embedded Test & Measurement ] My First Microcontr ects
ER olsPOW ing [ Fou TAwTH S rieerToE An ign aly des VE GO ,NEW DIY U’18 lingsis usi Thetrol YO ngPROJECT ATM rc , coo ard uling follo , con0 w7 the LTs pic So e story ds on testing l Audio Analogue Digita February 2010
2pen Logic AnalOyz TS 6 NEW PROJerEC Han
ty paci ery Ca Batt ker Chec
elektor.com stem PA Sy
& Excel
oth ueto TTL Blgle Don ain ke Ch orbi ot M
LET THE
Join the fascinating world of electronics worldwide!
SCEPTER RULE! 7
A 32-bit ARM g fast prototypin system
applications design for AVR Low power e DMX Interfac ED Mixer with LED Linux on a Chip Linu ar Parking Rad pacctt ... mpa -com a-co ltra Ultr
ULO D MOD amplifier fledged stereo A full-
H ELECTRONICS WIN $100 WIT
Creative & fresh articles since 1961
$ 7.95 US $ 7.95 - Canada
PUZZLE
ues 11 Iss the ing includ le r doub e m m t su or jus f e u s is 5* $39.9
Electronics projects to delight and educate in diverse areas of electronics Each project is built, tested, and approved by Elektor’s laboratory staff Access to a wide range of products to support magazine projects in our online shop Cheaper than 11 issues from the newsstand: Save 57% of the cover price of $92.45 * Offer available in US and Canada only. Canada add $11 per year.
Take out your subscription now:
XXXFMFLUPSDPNVTBt1IPOF
electronics worldwide
electronics worldwide
ty while retaining the performance of the current version. "0" No opt m zat on, debugg ng 27 27 20 produces expected resu ts. The most profound change "1" Reduces code s ze, ncreases 20 24 16 is a new “microMIPS” speed and comp e t me. instruction set capability. "2" Fu opt m zat on, further ncreas 19 22 15 Like ARM’s Thumb-2, es speed and comp e t me. microMIPS utilizes variablelength opcodes (16- and 32"s" Leve "2" opt m zat ons that do 18 21 15 bit) that achieves the best of not ncrease code s ze and others to both worlds—that is, nearly reduce code s ze. the performance of 32-bit "3" Leve "2" opt m zat ons and func 24 32 19 code with code density t on n n ng. approaching that of 16-bit Table 1—Smart compilers are all well and good, but keep in mind optimized code can be very tricky to (see Figure 2). Call it the debug. Get your code working first, then turn on the optimizations and keep your fingers crossed. final nail in the coffin for the fixed length instruction generates simpler code that preserves sets that were a hallmark of the origito better serve the embedded masses. your inefficient-it-may-be intent, and nal RISC revolution. That may have For instance, fully active power conthus your sanity, when it comes to made sense at the time (though barely sumption is on the order of debugging. For instance, after hitting 1mA/MHz, which is decent consider- in my opinion); but these days (as they a breakpoint, you can change the did long before RISC), architects realize ing the horsepower on tap. And the value of a variable without worrying spending 32 bits of memory (not to pricing for the new parts, ranging that the compiler pulled a fast one mention burning the power needed to from around $5 to $7 in volume, on you, such as having moved and shuffle them around) in order to increseems reasonable considering the already executed an assignment your kitchen-sink complement of memory ment a register or do a short branch source code says hasn’t happened yet. and peripherals. just doesn’t make sense. Keeping the quirks in mind, playDitto on the software front. The Nevertheless, the competition ing with the optimizer settings (see fancy compilers and IDE’s are all well from chips like Cortex-M3, Renesas Photo 4) can have a significant and good, but MIPS and Microchip SH (and now RX), Atmel AVR32, and impact. I ran one of the demos (USB should also take note of simpler alterFreescale Coldfire is formidable. Host) through the compiler with difnatives like ARM’s mbed, the AVRWith significant headstarts, these ferent settings as shown in Table 1. based Arduino, and for that matter the alternatives generally feature larger As you can see, between the various PICAXE in their own backyard. Some lineups that roughly match PIC32 optimizer settings (speed/size trademay still think 32-bit chips are only for integration and performance at the offs, loop unrolling, and, most rocket scientists, but how many rockhigh-end but offer leaner-and-meaner notably, taking advantage of the ets get sold? (i.e. lower price and power-consumpMIPS-16 16-bit code option) the size Want to sell a lot of chips? Simple. tion) entry-level variants. of the code generated varies by fully Just make them cheaper, lower-power, I think MIPS “gets it” as evia factor of 2:1. and easier to use. And then do it denced by their recent announceagain. I ment of a “14K” core that races forward to the past with features that KEEP IT SIMPLER Tom Cantrell has been working on chip, improve code density, interrupt PIC32 does a good job of downsizboard, and systems design and marketing response, and peripheral compatibiliing the venerable MIPS architecture for several years. You may reach him by e-mail at [email protected]. Optimization Level
Code Size (KB) - 32-bit
Code Size (KB) - 32-bit with loop unrolling
Code Size (KB) - 16-bit
CSiBE (code size)
Dhrystone (performance) 100.00%
1.60
90.00%
1.20 98% Performance
80.00%
35% Smaller
August 2010 – Issue 241
0.80
72
70.00% 0.40
60.00%
SOURCES PIC32MX 5xx/6xx/7xx MIPSbased MCU with CAN, Ethernet, USB Microchip Technology | www.microchip.com
50.00%
0.00 MIPS32
microMIPS
MIPS32
microMIPS
Figure 2—The forthcoming MIPS14K architecture dispenses with some of the aforementioned “computer” baggage such as code bloating fixed-length 32-bit instructions and delay slots. As a result, high-performance is retained while dramatically reducing the code footprint.
M14K Core MIPS Technologies | www.mips.com
CIRCUIT CELLAR®
•
www.circuitcellar.com
www.DevtoolsXpress.com
Pick a Tool. Any Tool. Find the Right Development Tool, Compare it to Other Tools, Evaluate It, and Buy It from Digi-Key Tools Xpress -- Without Leaving Our Site. The Digi-Key Tools Xpress intuitive research engines are used by engineers worldwide to locate, compare and evaluate hardware or software development tools.
Compare before you buy: tools are listed side-by-side, with features and performance specs, availability, and prices, so you can make an educated decision!
FIND COMPARE BUY
Digi-Key Tools Xpress, engineered by Embedded Developer, is the only site in the industry where engineers can quickly find, compare and buy the leading development tools.
1
2
3
4
5 6 7 8
9
10
11
12 13 14 15 16
17
18
August 2010 – Issue 241
19
74
Across
Down
1. 4. 5. 8. 10. 12. 13. 14. 16.
2. 3. 6. 7. 9. 11. 15. 18.
17. 19.
Eddy The “Q” in Q Point Elektor’s location in The Netherlands Glitch “EOL” is the end of … A stylus lacks Founded MIT 103 He connected U.S. President Roosevelt and Britain’s King Edward VII with a transmitter Y SSB, Communication method [two words]
2/7 to 7/2 Can block or allow to pass Algorithm map Scr Lk [two words] The “time” from 90% to 10% A signal that initiates Hypersonic is above Mach what? 1914, ARRL
The answers will be available in the next issue and at www.circuitcellar.com/crossword. CIRCUIT CELLAR®
•
www.circuitcellar.com
I
DEA BOX
THE DIRECTORY OF PRODUCTS AND SERVICES
AD FORMAT: Advertisers must furnish digital files that meet our specifications (www.circuitcellar.com/advertise). ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. E-mail [email protected] with your file or send it to IDEA BOX, Circuit Cellar, PO Box 180, Vernon, CT 06066. For current rates, deadlines, and more information contact Peter Wostrel at 800.454.3741, 978.281.7708 or [email protected].
August 2010 – Issue 241
The Vendor Directory at www.circuitcellar.com/vendor/ is your guide to a variety of engineering products and services.
www.circuitcellar.com
•
CIRCUIT CELLAR®
75
ATRIA Technologies Inc. The Heart of Your Design Simple, easy to use electronic modules for school, work and home. Great for prototypes, test fixtures, home projects, microcontroller labs and more. Microcontroller modules with the Freescale® MC9S08 and MCF51 series of 8 and 32 bit devices (AC, CN, JM, QE) are available starting at $23.
BAASIC is installed on many of the microcontroller modules. Other modules are available with USB, RS-232, Bluetooth, user I/O, LCD and power.
Visit our online store to see our expanding product line.
www.atriatechnologies.com
Rowley CrossWorks $50 $50 &RUWH[ C/C++ Compiler, IDE, Debugger, and JTAG programming tools in a single professional package Board and CPU support for NXP, STMicroelectronics, Atmel, TI, and many other microcontrollers
August 2010 – Issue 241
Includes royalty-free tasking library
76
Come and see what we have! Mention Circuit Cellar when you buy and we’ll gladly send you a JTAG adapter—for free!
RowleyAssociates.com
FS M QJ N P $$.$6r%FDS FB T FD PEF ¥ [FE* J T J [ FCZ N S1$ J U Pr6T 0Q G FM FT TF Y QFOT J W F.$6XJ U I
T NB M M FSQS PHS B NNFNPS Z r 4 B W FU IPVT B OETPG EPM M B S TJ OD PNQPOF OU D PT U TPW F SQS PEVD U M J G F U J NF
$$4 $PNQJ M FS T 4BWF: PV .POFZ $PNQJ M FS T4U BS U J OHBU XXX D D T J OG P D PN 4"7& T BM FT !D D T J OG P D PN Y
1$¥ .$6B OEET 1$¥ %4 $BFS F HJ T U FF ES B EF NB S L TPG .J D S PD IJ Q5 F D IOPM PHZ* OD
CIRCUIT CELLAR®
•
www.circuitcellar.com
MaxSonar Ultrasonic Ranging is EZ LV-MaxSonar-EZ Power-up calibration Smallest MaxSonar 1 inch resolution Low power, 2.5V-5.5V
MaxSonar-WR (IP67)
Industrial packaging Weather resistant Standard ô´ ILWWLQJ Quality narrow beam
XL-MaxSonar-EZ Beam pattern choice Tiny size Real-time calibration High acoustic power
MaxSonar-WRC (IP67)) Compact packaging Weather resistant Standard ô´ ILWWLQJ Quality narrow beam
630*213*8700 PROUDLY PRESENT: Instant Online Order...
Free 1st article with production order...
SP 2 L ECIA L 4 L AYER OFF AY S @ ER FR ERS 11 S EE @ / SH GRO 33 EA /E IPP U ING ND A
Quality supplier of PCB with wide range of rigid and flex manufacturing capabilities include.. 1-30 Layers same day to standard lead time, 4mil laser drill 3/3 line spacing hybrid and Teflon PCB. Noflow prepregs and dielectric thickness, Impedance control with polar report. Stock Material: FR4 TG 140-180 370HR/IS410 poly Nelco, Rogers, Lead Free
August 2010 – Issue 241
www.maxbotix.com
[email protected]
www.circuitcellar.com
•
CIRCUIT CELLAR®
77
I/O-Rich SBC Supports Embedded Ethernet/WiFi
O
O O O O
O
PDQ Board with
The PDQ Board Ethernet module a low cost 2 5”x4” C-programmable single-board computer Fast 16-bit Freescale HCS12 processor Ideal for data acquisition and control Embedded dynamic web server Email program-controlled messages from your instrument Plug-in modules for any kind of I/O, including GPS, A/D, D/A, UART, USB, AC and DC relays, and many more
Mosaic Industries Inc.
tel: 510 790 1255 fax: 510 790 0925
www.mosaic-industries.com
CROSSWORD ANSWERS from Issue 240
1
August 2010 – Issue 241
C
78
Across 3. INSTRUCTIONS—M PS means millions of these per second 8. LUMINANCE—Brightness 9. ANALOG—QAM FM AM SM 011. MILITARY— 255 ML 13. iesLUMEN—A com lux is what per square meter? 16. MEBI—Mega binary 17. SERVLET—Java app for your server 18. NULL—Valueless character 19. GIGAFLOPS—1 billion FLOPS 20. ROGERS—M T 1861 21. COMPILER—Code parser
Down 1. CCGOLD—8-GB USB flash drive holding every issue if Circuit Cellar 2. VIRTUALMACHINE—VM [two words] 4. ENQUIRY—EQN 5. DAUGHTERBOARD—Off the motherboard but connected 6. TEBI—Tera binary 7. DATARATE—Bps [two words] 10. GND—Ground pin 12. CLUSTER—Group larger than a sector 14. FIREWIRE— EEE 1394 15. OBSOLETE—Unavailable outdated
C 2
G
V 3
I
N S
T R U C T I
O N S L
R
D
T
4
E
U 5
6
7
D
T
N
N A N C E
Q
A N A L O G
B
U
T
D
A 8
9
L U M I M
U
A
G
10
N
11
M I
L I
D
R
R
H
C
T A R Y
12
H
A
Y
T
C 13
I
14 15
N
U
R
E
S
B
T
O
E
A
R
R
F
T
L U M E N 16
M E B I
O
R
B 17
S
E R V L E T W
O 18
19
G I
N U L L
G A F
L O P
S
R
E
D
20
R O G E R S
T 21
C O M P
I
L E R
CIRCUIT CELLAR®
•
www.circuitcellar.com
I
NDEX OF ADVERTISERS
located at www.circuitcellar.com under the current issue. Page
Page
78
AAG Electronica, LLC
45
ESC Boston
41
AP Circuits
76
Earth Computer Technologies
75
All Electronics Corp.
69
Electronica 2010
77
Apex Embedded Systems
26, 27
76
ATRIA Technologies, Inc.
77
Page ICbank, Inc.
78
Mosaic Industries, Inc.
Imagineering, Inc.
19
Mouser Electronics
47
Intuitive Circuits LLC
C2
NetBurner
Elektor
78
Ironwood Electronics
14
PCB-Pool
71
Elektor
15, 32
JK microsystems, Inc.
C4
Parallax, Inc.
Bitwise Systems
34
Elsevier
75, 77
JK microsystems, Inc.
13
PoLabs
CC Gold
76
Embedded Adventures Ltd.
Jameco
49
Pololu Corp.
48
CC-Access
73
Embedded Developer
47
Jeffrey Kerr, LLC
76
Reach Technology, Inc.
33
CWAV
23
ExpressPCB
12
Keil Software
76
Rowley Associates
10
Cleverscope
46
FTDI
77
Lawicel AB
37
Comfile Technology, Inc.
77
Fine Circuits, Inc.
15
Lemos International Co. Inc.
76
Custom Computer Services, Inc.
18
Flash Memory Summit
41
Linx Technologies, Inc.
77
Tern, Inc.
75
Decade Engineering
75
FlexiPanel Ltd.
77
MCC (Micro Computer Control)
57
Total Phase, Inc.
48
DesignNotes
32
Grid Connect, Inc.
77
Maxbotix, Inc.
78
Trace Systems, Inc.
C3
Digi International
47
HobbyLab, LLC
76
microEngineering Labs, Inc.
75
Triangle Research Int’l, Inc.
14
EMAC, Inc.
35
Hot Chips 22 Symposium
11
ModularLogix
63, 64
P
REVIEW
54, 55 1
5
of September Issue 242
Doppler Radar Design Mesh Telephony System: The Mesh Potato Project from an Embedded Designer’s POV Precision Temperature Control Circuitry THE CONSUMMATE ENGINEER Is the Door Closed?: Why Designing Safety-Critical Systems Is Essential LESSONS FROM THE TRENCHES State Machines Revisited: Addressing Real-World Word Problems FROM THE BENCH Data Transmission and Decoding: Design & Implement a Keyfob Decoder SILICON UPDATE Once More, With Feeling: An MCU + FPGA Without the Compromises •
SparkFun Electronics
2, 3
Technologic Systems
A TTENTION A DVERTISERS
Theme: Data Acquisition
www.circuitcellar.com
7
CIRCUIT CELLAR®
October Issue 243 Deadlines Space Close: Aug. 13 Material Close: Aug. 20
Theme Signal Processing Bonus Distribution ARM TechCon3 Call Peter Wostrel now to reserve your space! 800.454.3741 or 978.281.7708 e-mail: [email protected]
August 2010 – Issue 241
Page
The Index of Advertisers with links to their web sites is
79
RIORITY
PINTERRUPT by Steve Ciarcia, Founder and Editorial Director
Is the Internet Making Us Smarter or Dumber?
August 2010 – Issue 241
I
80
f I were 25 years o d, I probab y wou dn t be ask ng th s quest on. But, does the fact that so many more peop e I run nto these days know what I know make me dumber than I used to be? Or, s everybody just smarter now? It s not ke I used to crave the attent on, but et s face t, when you need techn ca nformat on and you are the on y eng neer at the party, guess who gets asked. ;-) These days, when any tough subject comes up n conversat on, t s on y about 5 seconds before some guy wh ps out h s smart phone and Goog e s t. It certa n y doesn t g ve me an nfer or ty comp ex, but short of nsta ng a ce phone jammer, t s hard to know how much know edge these peop e have or s mp y how good they have become at f nd ng someone who does. Th s sn t a sermon. I m s mp y po nt ng out a part cu ar behav or that I have observed and I m shar ng t w th you. I rea y don t have any concrete stat st cs on whether a th s nformat on access s mak ng us smarter or dumber, but I do th nk t s chang ng the way we th nk. Before c ocks were nvented, I m sure peop e dec ded d nner t me based on a sense of hunger rather than th nk ng: “It s 5 PM and t me to eat.” Is th s nstant y ava ab e Internet “know edge” ke add ng another c ock to our da y th nk ng? I wonder f the saturat on of techno ogy we exper ence today s mak ng our th nk ng and nformat on-process ng methodo ogy more superf c a . When was the ast t me you just sat and read a book w thout do ng f ve other th ngs at the same t me? Have we mere y become brar es fu of Goog ed t db ts? Have we ost the mot vat on to th nk beyond cata oged sources? More mportant y, are we beg nn ng to confuse the d fference between “ nformat on” and “know edge”? Search eng nes and the un m ted nformat on on the Internet have tru y changed our ves. I know when I ook up a subject I have at east two mon tors and a dozen w ndows d sp ay ng var ous answers. I don t know whether my capacty for concentrat on has essened, but nstead of ong contemp at on, t seems I ve moved to sw ft y stream ng data sources and subject sk mm ng. Ca t reprogramm ng, evo ut on, or consp racy, but for fe on ne, the more nks we c ck and the more pages we v ew, the greater the apparent reward. The quest on s: Has “power brows ng,” the econom c foundat on of Goog e and the Internet, moved us from med tat ve to ut tar an nte gence? In Goog e s defense, I apprec ate that I no onger have to remember everyth ng n my head. When I m asked wh ch s heav er, b smuth or ead, even I Goog e the per od c tab e rather than “w ng t” from memory (and, yeah, somet mes I meet some rea y strange peop e at these part es). I suppose th s m ght be the same reve at on peop e had about the nvent on of paper and the Gutenberg press. We can t b ame search eng nes for th s, but the downs de of nstant nformat on can be nstant ana ys s and conc us on. Goog e prov des us w th more nformat on than we can poss b y use, but t s a quant tat ve rather than qua tat ve presentat on. The presentat on order of search eng nes s based f rst on advert s ng revenue and then on popu ar ty, not verac ty. The per od c tab e s an unquest onab e fact, but st ngs regard ng sc ent f c op n ons, med ca procedures, po t ca op n on, and product rev ews can be skewed s mp y by the amount of web traff c v ew ng that nformat on. A s ng e bad restaurant rev ew nked to hundreds of b ogs or trave s tes w appear at the top of the search eng ne st ngs regard ess of whether t s true. Our future does ndeed requ re sh ft ng certa n tasks to the Internet. The greatest benef t w be that we no onger have to remember tt e-used facts or vo umes of mater a . The downs de s that we have become dependent on var ous Internet resources ke Goog e and W k ped a to retr eve t. In pr nc p e, th s s no d fferent than an o d-fash oned brary. Hav ng access to a arge resource ke th s doesn t mean we re stup d when we s mp y don t know a spec f c fact. At the same t me, nf n te nformat on sources don t necessar y make us smarter e ther. It s how we use and process nformat on that promotes pos t ve evo ut on. The Internet sn t damag ng our ab ty to th nk, but t s foster ng behav ors that you have to th nk about. Rep ac ng d sc p ned, carefu , near thought ke read ng a good book w th superf c a attent on to a dozen d fferent streams of s mu taneous nformat on certa n y must have a downs de somep ace. Determ n ng exact y what or how s above my pay grade. The on y mora I can offer now s that tru y smart peop e w add some fact-check ng and ut ze the Internet as a creat ve too . The rest w s mp y et Goog e do the th nk ng for them.
[email protected]
CIRCUIT CELLAR®
•
www.circuitcellar.com
XBee
®
7KH 0RVW )OH[LEOH =LJ%HH 3ODWIRUP
: ZigBee PRO interoperability : Out-of-the-box RF communications : Common XBee footprint makes substituting modules easy
NEW! Programmable ZigBee modules : Optimized for ZigBee application profiles including Smart Energy : iDigi™ Energy solution bundle : Complete solution: Modules, adapters, gateways, services
The industry’s first ZigBee Smart Energy modules
'LJL VMMLYZ [OL PUK\Z[Y`»Z TVZ[ JVTWSL[L ZL[ VM OHYK^HYL HUK ZLY]PJLZ MVY `V\Y APN)LLLUHISLK ZVS\[PVU ?)LL WYVK\J[Z Z\WWVY[ H ^PKL YHUNL VM HWWSPJH[PVUZ PUJS\KPUN :THY[ ,ULYN` /VTL HUK )\PSKPUN (\[VTH[PVU 9LTV[L +L]PJL 4HUHNLTLU[ HUK TVYL >P[O H OVZ[ VM TVK\SLZ Z[HUKHSVUL Gateways
HKHW[LYZ 07LUHISLK NH[L^H`Z HUK P+PNP KH[H ZLY]PJLZ +PNP OHZ [OL [VVSZ [V ZLL `V\Y WYVQLJ[ [OYV\NO MYVT ILNPUUPUN [V LUK
Modules
Get started today with an XBee Development Kit Digi International Tel. 1-877-912-3444
Adapters
www.digi.com/getXBee